import { useParams, useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { CKEditor } from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { Blog } from '../types';
import { blogFormSchema, blogDefaults, buildBlogPayload } from '../lib/blogForm';
import type { BlogFormData } from '../lib/blogForm';
import PageHeader from '../components/ui/PageHeader';
import SearchableSelect from '../components/ui/SearchableSelect';
import BlogSeoFields from '../components/BlogSeoFields';

interface RepMe { cities: { id: number; name: string }[] }

export default function RepresentationBlogFormPage() {
  const { uuid } = useParams<{ uuid: string }>();
  const navigate = useNavigate();
  const qc = useQueryClient();
  const isEdit = !!uuid;

  const meQuery = useQuery({
    queryKey: ['rep-me-cities'],
    queryFn: () => api.get<ApiResponse<RepMe>>('/api/v1/representation/me'),
    staleTime: 5 * 60_000,
  });
  const cityOptions = (meQuery.data?.data?.cities ?? []).map((c) => ({ value: c.id, label: c.name }));

  const { data, isLoading, isError, error } = useQuery({
    queryKey: ['rep-blog', uuid],
    queryFn: () => api.get<ApiResponse<{ data: Blog }>>(`/api/v1/representation/blog/${uuid}`),
    enabled: isEdit,
    retry: false,
  });
  const blog = data?.data?.data;

  const { register, handleSubmit, control, formState: { errors } } = useForm<BlogFormData>({
    resolver: zodResolver(blogFormSchema),
    defaultValues: blogDefaults(),
    values: blog ? (blogDefaults(blog) as BlogFormData) : undefined,
  });

  const createMutation = useMutation({
    mutationFn: (d: BlogFormData) => api.post<ApiResponse<Blog>>('/api/v1/representation/blog', buildBlogPayload(d)),
    onSuccess: () => {
      toast.success('مقاله ذخیره شد');
      qc.invalidateQueries({ queryKey: ['rep-blogs'] });
      navigate('/admin/representation-blogs');
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const updateMutation = useMutation({
    mutationFn: (d: BlogFormData) => api.patch<ApiResponse<Blog>>(`/api/v1/representation/blog/${uuid}`, buildBlogPayload(d)),
    onSuccess: () => {
      toast.success('مقاله بروزرسانی شد');
      qc.invalidateQueries({ queryKey: ['rep-blogs'] });
      qc.invalidateQueries({ queryKey: ['rep-blog', uuid] });
      navigate('/admin/representation-blogs');
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const saving = createMutation.isPending || updateMutation.isPending;

  const onSubmit = (d: BlogFormData) => {
    if (!d.city_id) {
      toast.error('انتخاب شهر الزامی است');
      return;
    }
    if (isEdit) updateMutation.mutate(d);
    else createMutation.mutate(d);
  };

  if (isEdit && isLoading) {
    return <div className="cp-card p-6 space-y-3">{Array.from({ length: 5 }).map((_, i) => <div key={i} className="h-10 rounded-lg skeleton" />)}</div>;
  }

  if (isEdit && (isError || !blog)) {
    return (
      <div className="cp-card p-6 text-center space-y-4">
        <p className="text-[var(--danger)]">{(error as Error | null)?.message ?? 'مقاله یافت نشد'}</p>
        <button type="button" className="cp-btn-secondary" onClick={() => navigate('/admin/representation-blogs')}>
          بازگشت به فهرست مقالات
        </button>
      </div>
    );
  }

  return (
    <div>
      <PageHeader
        backTo="/admin/representation-blogs"
        title={isEdit ? 'ویرایش مقاله' : 'نوشتن مقالهٔ جدید'}
        breadcrumbs={[{ label: 'وبلاگ من', to: '/admin/representation-blogs' }, { label: isEdit ? 'ویرایش' : 'جدید' }]}
      />

      <div className="cp-card p-6">
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="lg:col-span-2 space-y-5">
              <div>
                <label className="cp-label">عنوان مقاله *</label>
                <input {...register('title')} className="cp-input h-11" placeholder="عنوان جذاب بنویسید..." />
                {errors.title && <p className="text-[var(--danger)] text-xs mt-1">{errors.title.message}</p>}
              </div>
              <div>
                <label className="cp-label">خلاصه</label>
                <textarea {...register('summary')} rows={2} className="cp-textarea resize-none" />
              </div>
              <div>
                <label className="cp-label">محتوا *</label>
                <Controller
                  control={control}
                  name="body"
                  render={({ field }) => (
                    <div dir="rtl" className="ck-rtl">
                      <CKEditor
                        editor={ClassicEditor as never}
                        data={field.value ?? ''}
                        onChange={(_e: unknown, editor: { getData: () => string }) => field.onChange(editor.getData())}
                        config={{ licenseKey: 'GPL', language: 'fa', toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|', 'blockQuote', 'insertTable', '|', 'undo', 'redo'] }}
                      />
                    </div>
                  )}
                />
                {errors.body && <p className="text-[var(--danger)] text-xs mt-1">{errors.body.message}</p>}
              </div>
            </div>

            <div className="space-y-5">
              <div>
                <label className="cp-label">شهر *</label>
                <Controller
                  control={control}
                  name="city_id"
                  render={({ field }) => (
                    <SearchableSelect
                      options={cityOptions}
                      value={field.value ?? null}
                      onChange={(v) => field.onChange(v ? Number(v) : null)}
                      placeholder="یکی از شهرهای حوزهٔ شما"
                      isLoading={meQuery.isLoading}
                    />
                  )}
                />
                <p className="text-[12px] text-[var(--text-3)] mt-1">فقط شهرهای حوزهٔ نمایندگی شما.</p>
              </div>
              <div>
                <label className="cp-label">وضعیت انتشار</label>
                <Controller
                  control={control}
                  name="status"
                  render={({ field }) => (
                    <SearchableSelect
                      options={[{ value: 'draft', label: 'پیش‌نویس' }, { value: 'published', label: 'منتشر شده' }]}
                      value={field.value ?? null}
                      onChange={(v) => field.onChange(v ?? 'draft')}
                    />
                  )}
                />
              </div>
              <div>
                <label className="cp-label">آدرس تصویر شاخص (URL)</label>
                <input {...register('image_url')} dir="ltr" className="cp-input h-11" placeholder="https://..." />
              </div>
              <div>
                <label className="cp-label">تگ‌ها (با ویرگول)</label>
                <input {...register('tags')} dir="ltr" className="cp-input h-11" placeholder="tag1, tag2" />
              </div>
            </div>
          </div>

          <div className="cp-card p-5" style={{ background: 'var(--surface-2)' }}>
            <BlogSeoFields control={control} register={register} />
          </div>

          <div className="flex gap-3">
            <button type="submit" disabled={saving} className="cp-btn-primary justify-center py-2.5" style={{ minWidth: 160 }}>
              {saving ? 'در حال ذخیره...' : isEdit ? 'بروزرسانی' : 'ذخیره'}
            </button>
            <button type="button" onClick={() => navigate('/admin/representation-blogs')} className="cp-btn-secondary justify-center py-2.5" style={{ minWidth: 120 }}>لغو</button>
          </div>
        </form>
      </div>
    </div>
  );
}
