import React 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 { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { Blog } from '../types';
import PageHeader from '../components/ui/PageHeader';

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

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

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

  const blog = data?.data;

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

  const createMutation = useMutation({
    mutationFn: (d: FormData) =>
      api.post<ApiResponse<Blog>>('/api/v1/blog', {
        ...d,
        tags: d.tags ? d.tags.split(',').map((t) => t.trim()).filter(Boolean) : [],
      }),
    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}`, {
        ...d,
        tags: d.tags ? d.tags.split(',').map((t) => t.trim()).filter(Boolean) : [],
      }),
    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);
  };

  if (isEdit && isLoading) {
    return (
      <div className="bg-white rounded-2xl border border-gray-100 p-6 space-y-3">
        {Array.from({ length: 5 }).map((_, i) => (
          <div key={i} className="h-10 bg-gray-100 rounded-lg animate-pulse" />
        ))}
      </div>
    );
  }

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

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 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="block text-sm font-medium text-gray-700 mb-1">عنوان مقاله *</label>
                <input {...register('title')} placeholder="عنوان جذاب بنویسید..."
                  className="w-full h-11 border border-gray-300 rounded-[10px] px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500" />
                {errors.title && <p className="text-red-500 text-xs mt-1">{errors.title.message}</p>}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">خلاصه</label>
                <textarea {...register('summary')} rows={2} placeholder="خلاصه کوتاه مقاله..."
                  className="w-full border border-gray-300 rounded-[10px] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none" />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">محتوا *</label>
                <textarea {...register('content')} rows={16} placeholder="محتوای مقاله را بنویسید..."
                  className="w-full border border-gray-300 rounded-[10px] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none font-mono" />
                {errors.content && <p className="text-red-500 text-xs mt-1">{errors.content.message}</p>}
              </div>
            </div>

            <div className="space-y-5">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">وضعیت انتشار</label>
                <Controller
                  control={control}
                  name="status"
                  render={({ field }) => (
                    <select {...field}
                      className="w-full h-11 border border-gray-300 rounded-[10px] px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500">
                      <option value="draft">پیش‌نویس</option>
                      <option value="published">منتشر</option>
                    </select>
                  )}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">تگ‌ها (با ویرگول جدا کنید)</label>
                <input {...register('tags')} dir="ltr" placeholder="tag1, tag2, tag3"
                  className="w-full h-11 border border-gray-300 rounded-[10px] px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500" />
              </div>

              <div className="pt-4 space-y-3">
                <button type="submit" disabled={isSubmitting}
                  className="w-full py-2.5 bg-primary-600 text-white text-sm font-medium rounded-[10px] hover:bg-primary-700 disabled:opacity-50 transition-colors">
                  {isSubmitting ? 'در حال ذخیره...' : isEdit ? 'بروزرسانی' : 'ذخیره'}
                </button>
                <button type="button" onClick={() => navigate('/admin/blogs')}
                  className="w-full py-2.5 border border-gray-300 text-sm text-gray-700 rounded-[10px] hover:bg-gray-50 transition-colors">
                  لغو
                </button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}
