import React, { useState } from 'react';
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 { z } from '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 { useAuthStore } from '../stores/authStore';
import PageHeader from '../components/ui/PageHeader';
import SearchableSelect from '../components/ui/SearchableSelect';

const schema = z.object({
  title: z.string().min(3, 'عنوان الزامی است'),
  summary: z.string().optional(),
  body: z.string().min(10, 'محتوا الزامی است'),
  tags: z.string().optional(),
  status: z.enum(['draft', 'published']),
  image_url: z.string().optional(),
});
type FormData = z.infer<typeof schema>;

async function uploadBlogImage(file: File): Promise<string> {
  const token = useAuthStore.getState().token;
  const fd = new FormData();
  fd.append('file', file);
  const res = await fetch('/file/upload/clinic_pro/blog/field_image', {
    method: 'POST',
    headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
    body: fd,
  });
  const json = await res.json().catch(() => ({}));
  if (res.status === 401) {
    useAuthStore.getState().logout();
    window.location.replace('/admin/login');
    throw new Error('نشست منقضی شده است');
  }
  if (!res.ok) throw new Error(json?.errors?.[0]?.message ?? 'خطا در آپلود تصویر');
  return json.data.image_url as string;
}

export default function BlogFormPage() {
  const { uuid } = useParams<{ uuid: string }>();
  const navigate = useNavigate();
  const qc = useQueryClient();
  const isEdit = !!uuid;
  const [uploading, setUploading] = useState(false);

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

  // detail endpoint is double-nested: success(['data' => $blog->toArray()])
  const blog = data?.data?.data;

  const { register, handleSubmit, control, watch, setValue, formState: { errors, isSubmitting } } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: { status: 'draft' },
    values: blog
      ? {
          title: blog.title,
          summary: blog.summary ?? '',
          body: blog.body,
          tags: blog.tags?.join(', ') ?? '',
          status: blog.status,
          image_url: blog.image_url ?? '',
        }
      : undefined,
  });

  const imageUrl = watch('image_url');

  const buildPayload = (d: FormData) => ({
    title: d.title,
    body: d.body,
    summary: d.summary,
    status: d.status,
    image_url: d.image_url ?? '',
    tags: d.tags ? d.tags.split(',').map((t) => t.trim()).filter(Boolean) : [],
  });

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

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

  const onSubmit = (d: FormData) => {
    if (isEdit) updateMutation.mutate(d);
    else createMutation.mutate(d);
  };

  const onImageSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const url = await uploadBlogImage(file);
      setValue('image_url', url, { shouldValidate: true });
      toast.success('تصویر آپلود شد');
    } catch (err) {
      toast.error((err as Error).message);
    } finally {
      setUploading(false);
      e.target.value = '';
    }
  };

  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>
    );
  }

  return (
    <div>
      <PageHeader
        title={isEdit ? 'ویرایش مقاله' : 'نوشتن مقاله جدید'}
        breadcrumbs={[
          { label: 'داشبورد', to: '/admin/dashboard' },
          { label: 'بلاگ', to: '/admin/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="">عنوان مقاله *</label>
                <input {...register('title')} placeholder="عنوان جذاب بنویسید..."
                  className="cp-input h-11" />
                {errors.title && <p className="text-red-500 text-xs mt-1">{errors.title.message}</p>}
              </div>

              <div>
                <label className="">خلاصه</label>
                <textarea {...register('summary')} rows={2} placeholder="خلاصه کوتاه مقاله..."
                  className="input resize-none" />
              </div>

              <div>
                <label className="">محتوا *</label>
                <Controller
                  control={control}
                  name="body"
                  render={({ field }) => (
                    <div dir="rtl" className="ck-rtl">
                      <CKEditor
                        editor={ClassicEditor as never}
                        data={field.value ?? ''}
                        onChange={(_evt: 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-red-500 text-xs mt-1">{errors.body.message}</p>}
              </div>
            </div>

            <div className="space-y-5">
              <div>
                <label className="">تصویر شاخص</label>
                {imageUrl ? (
                  <div className="relative">
                    <img src={imageUrl} alt="cover"
                      style={{ width: '100%', height: 160, objectFit: 'cover', borderRadius: 8 }} />
                    <button type="button" onClick={() => setValue('image_url', '', { shouldValidate: true })}
                      className="cp-btn-secondary w-full justify-center py-2 mt-2">
                      حذف تصویر
                    </button>
                  </div>
                ) : (
                  <label className="cp-btn-secondary w-full justify-center py-2.5 cursor-pointer"
                    style={{ display: 'flex' }}>
                    {uploading ? 'در حال آپلود...' : 'انتخاب تصویر'}
                    <input type="file" accept="image/*" hidden disabled={uploading} onChange={onImageSelect} />
                  </label>
                )}
              </div>

              <div>
                <label className="">وضعیت انتشار</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="">تگ‌ها (با ویرگول جدا کنید)</label>
                <input {...register('tags')} dir="ltr" placeholder="tag1, tag2, tag3"
                  className="cp-input h-11" />
              </div>

              <div className="pt-4 space-y-3">
                <button type="submit" disabled={isSubmitting}
                  className="cp-btn-primary w-full justify-center py-2.5">
                  {isSubmitting ? 'در حال ذخیره...' : isEdit ? 'بروزرسانی' : 'ذخیره'}
                </button>
                <button type="button" onClick={() => navigate('/admin/blogs')}
                  className="cp-btn-secondary w-full justify-center py-2.5">
                  لغو
                </button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}
