import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { TrashIcon, PlusIcon, PencilIcon } from '@heroicons/react/24/outline';
import { useForm } 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 { Category, CategoryBundle } from '../types';
import PageHeader from '../components/ui/PageHeader';
import DataTable, { Column } from '../components/ui/DataTable';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import Modal from '../components/ui/Modal';

const TABS: { key: CategoryBundle; label: string }[] = [
  { key: 'state', label: 'استان‌ها' },
  { key: 'city', label: 'شهرها' },
  { key: 'specialty', label: 'تخصص‌ها' },
  { key: 'doctor_service', label: 'خدمات پزشک' },
  { key: 'insurance_type', label: 'نوع بیمه' },
  { key: 'supplementary_insurance', label: 'بیمه تکمیلی' },
  { key: 'tag', label: 'تگ‌های بلاگ' },
];

const schema = z.object({
  name: z.string().min(1, 'نام الزامی است'),
  code: z.string().optional(),
  parent_uuid: z.string().optional(),
});
type FormData = z.infer<typeof schema>;

export default function CategoriesPage() {
  const qc = useQueryClient();
  const [activeTab, setActiveTab] = useState<CategoryBundle>('state');
  const [search, setSearch] = useState('');
  const [addOpen, setAddOpen] = useState(false);
  const [editTarget, setEditTarget] = useState<Category | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Category | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['categories', activeTab],
    queryFn: () =>
      api.get<ApiResponse<Category[]>>(`/api/v1/categorys/${activeTab}`),
  });

  const { register, handleSubmit, reset, setValue, formState: { errors, isSubmitting } } = useForm<FormData>({
    resolver: zodResolver(schema),
  });

  const createMutation = useMutation({
    mutationFn: (d: FormData) =>
      api.post<ApiResponse<Category>>('/api/v1/category', { ...d, bundle: activeTab }),
    onSuccess: () => {
      toast.success('دسته‌بندی اضافه شد');
      setAddOpen(false);
      reset();
      qc.invalidateQueries({ queryKey: ['categories', activeTab] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const updateMutation = useMutation({
    mutationFn: ({ uuid, d }: { uuid: string; d: FormData }) =>
      api.patch<ApiResponse<Category>>(`/api/v1/category/${uuid}`, d),
    onSuccess: () => {
      toast.success('دسته‌بندی بروزرسانی شد');
      setEditTarget(null);
      reset();
      qc.invalidateQueries({ queryKey: ['categories', activeTab] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const deleteMutation = useMutation({
    mutationFn: (c: Category) => api.delete<ApiResponse<null>>(`/api/v1/category/${c.uuid}`),
    onSuccess: () => {
      toast.success('دسته‌بندی حذف شد');
      setDeleteTarget(null);
      qc.invalidateQueries({ queryKey: ['categories', activeTab] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const openEdit = (c: Category) => {
    setEditTarget(c);
    setValue('name', c.name);
    setValue('code', c.code ?? '');
    setValue('parent_uuid', c.parent_uuid ?? '');
  };

  const allItems = data?.data ?? [];
  const filtered = search
    ? allItems.filter((c) => c.name.includes(search))
    : allItems;

  const columns: Column<Category>[] = [
    { key: 'name', header: 'نام', render: (c) => <span className="font-medium">{c.name}</span> },
    { key: 'code', header: 'کد', render: (c) => c.code ? <span dir="ltr" className="font-mono text-xs">{c.code}</span> : '—' },
    { key: 'parent_name', header: 'والد', render: (c) => c.parent_name ?? '—' },
  ];

  const handleTabChange = (tab: CategoryBundle) => {
    setActiveTab(tab);
    setSearch('');
  };

  return (
    <div>
      <PageHeader
        title="دسته‌بندی‌ها"
        breadcrumbs={[{ label: 'داشبورد', to: '/admin/dashboard' }, { label: 'دسته‌بندی‌ها' }]}
        action={
          <button onClick={() => setAddOpen(true)}
            className="flex items-center gap-2 px-4 py-2 bg-primary-600 text-white text-sm rounded-[10px] hover:bg-primary-700 transition-colors">
            <PlusIcon className="w-4 h-4" />
            افزودن
          </button>
        }
      />

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100">
        <div className="flex flex-wrap border-b border-gray-200 px-6 pt-4 gap-1">
          {TABS.map((t) => (
            <button key={t.key} onClick={() => handleTabChange(t.key)}
              className={`pb-3 px-4 text-sm font-medium border-b-2 transition-colors -mb-px ${
                activeTab === t.key
                  ? 'border-primary-600 text-primary-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}>
              {t.label}
            </button>
          ))}
        </div>

        <div className="p-6">
          <DataTable<Category>
            columns={columns}
            data={filtered}
            loading={isLoading}
            searchValue={search}
            onSearchChange={setSearch}
            searchPlaceholder="جستجو..."
            emptyMessage="هیچ موردی یافت نشد"
            actions={(cat) => (
              <>
                <button onClick={() => openEdit(cat)}
                  className="p-1.5 text-gray-400 hover:text-primary-600 hover:bg-primary-50 rounded-lg transition-colors" title="ویرایش">
                  <PencilIcon className="w-4 h-4" />
                </button>
                <button onClick={() => setDeleteTarget(cat)}
                  className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors" title="حذف">
                  <TrashIcon className="w-4 h-4" />
                </button>
              </>
            )}
          />
        </div>
      </div>

      <Modal open={addOpen} title={`افزودن — ${TABS.find((t) => t.key === activeTab)?.label}`}
        onClose={() => { setAddOpen(false); reset(); }}
        footer={
          <>
            <button onClick={() => { setAddOpen(false); reset(); }}
              className="px-4 py-2 border border-gray-300 text-sm text-gray-700 rounded-[10px] hover:bg-gray-50 transition-colors">
              لغو
            </button>
            <button form="cat-form" type="submit" disabled={isSubmitting}
              className="px-4 py-2 bg-primary-600 text-white text-sm rounded-[10px] hover:bg-primary-700 disabled:opacity-50 transition-colors">
              ذخیره
            </button>
          </>
        }
      >
        <form id="cat-form" onSubmit={handleSubmit((d) => createMutation.mutate(d))} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">نام</label>
            <input {...register('name')}
              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.name && <p className="text-red-500 text-xs mt-1">{errors.name.message}</p>}
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">کد (اختیاری)</label>
            <input {...register('code')} dir="ltr"
              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>
          {(activeTab === 'city') && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">استان (UUID)</label>
              <input {...register('parent_uuid')} dir="ltr" placeholder="uuid استان"
                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>
          )}
        </form>
      </Modal>

      <Modal open={!!editTarget} title="ویرایش دسته‌بندی"
        onClose={() => { setEditTarget(null); reset(); }}
        footer={
          <>
            <button onClick={() => { setEditTarget(null); reset(); }}
              className="px-4 py-2 border border-gray-300 text-sm text-gray-700 rounded-[10px] hover:bg-gray-50 transition-colors">
              لغو
            </button>
            <button form="edit-cat-form" type="submit" disabled={isSubmitting}
              className="px-4 py-2 bg-primary-600 text-white text-sm rounded-[10px] hover:bg-primary-700 disabled:opacity-50 transition-colors">
              ذخیره
            </button>
          </>
        }
      >
        <form id="edit-cat-form"
          onSubmit={handleSubmit((d) => editTarget && updateMutation.mutate({ uuid: editTarget.uuid, d }))}
          className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">نام</label>
            <input {...register('name')}
              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.name && <p className="text-red-500 text-xs mt-1">{errors.name.message}</p>}
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">کد (اختیاری)</label>
            <input {...register('code')} dir="ltr"
              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>
        </form>
      </Modal>

      <ConfirmDialog
        open={!!deleteTarget}
        title="حذف دسته‌بندی"
        message={`آیا از حذف "${deleteTarget?.name}" اطمینان دارید؟`}
        confirmLabel="حذف"
        danger
        loading={deleteMutation.isPending}
        onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget)}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}
