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: 'specially_doctor', label: 'تخصص‌ها' },
  { key: 'doctor_services', label: 'خدمات پزشک' },
  { key: 'insurance_type', label: 'نوع بیمه' },
  { key: 'supplementary_insurance', label: 'بیمه تکمیلی' },
  { key: 'tag', label: 'تگ‌های بلاگ' },
];

const schema = z.object({
  label: z.string().min(1, 'نام الزامی است'),
  parent_id: 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<{ data: 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', {
        label: d.label,
        bundle: activeTab,
        ...(d.parent_id ? { parent_id: parseInt(d.parent_id) } : {}),
      }),
    onSuccess: () => {
      toast.success('دسته‌بندی اضافه شد');
      setAddOpen(false);
      reset();
      qc.invalidateQueries({ queryKey: ['categories', activeTab] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, d }: { id: number; d: FormData }) =>
      api.patch<ApiResponse<Category>>(`/api/v1/category/${id}`, { label: d.label }),
    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.id}`),
    onSuccess: () => {
      toast.success('دسته‌بندی حذف شد');
      setDeleteTarget(null);
      qc.invalidateQueries({ queryKey: ['categories', activeTab] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const openEdit = (c: Category) => {
    setEditTarget(c);
    setValue('label', c.label);
  };

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

  const columns: Column<Category>[] = [
    { key: 'label', header: 'نام', render: (c) => <span className="font-medium">{c.label}</span> },
    {
      key: 'bundle',
      header: 'نوع',
      render: (c) => (
        <span className="text-xs bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 px-2 py-0.5 rounded-full">{c.bundle}</span>
      ),
    },
    {
      key: 'status',
      header: 'وضعیت',
      render: (c) => (
        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
          c.status === 1 ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
        }`}>
          {c.status === 1 ? 'فعال' : 'غیرفعال'}
        </span>
      ),
    },
  ];

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

  return (
    <div>
      <PageHeader
        title="دسته‌بندی‌ها"
        breadcrumbs={[{ label: 'داشبورد', to: '/admin/dashboard' }, { label: 'دسته‌بندی‌ها' }]}
        action={
          <button onClick={() => setAddOpen(true)}
            className="cp-btn-primary">
            <PlusIcon className="w-4 h-4" />
            افزودن
          </button>
        }
      />

      <div className="cp-card">
        <div className="flex flex-wrap border-b border-slate-200 dark:border-gray-700 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-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200'
              }`}>
              {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="cp-action-edit" title="ویرایش">
                  <PencilIcon className="w-4 h-4" />
                </button>
                <button onClick={() => setDeleteTarget(cat)}
                  className="cp-action-delete" title="حذف">
                  <TrashIcon className="w-4 h-4" />
                </button>
              </>
            )}
          />
        </div>
      </div>

      {/* Add Modal */}
      <Modal open={addOpen} title={`افزودن — ${TABS.find((t) => t.key === activeTab)?.label}`}
        onClose={() => { setAddOpen(false); reset(); }}
        footer={
          <>
            <button onClick={() => { setAddOpen(false); reset(); }}
              className="cp-btn-secondary">
              لغو
            </button>
            <button form="cat-form" type="submit" disabled={isSubmitting}
              className="cp-btn-primary">
              ذخیره
            </button>
          </>
        }
      >
        <form id="cat-form" onSubmit={handleSubmit((d) => createMutation.mutate(d))} className="space-y-4">
          <div>
            <label className="cp-label">نام</label>
            <input {...register('label')}
              className="cp-input h-11" />
            {errors.label && <p className="text-red-500 text-xs mt-1">{errors.label.message}</p>}
          </div>
          {activeTab === 'city' && (
            <div>
              <label className="cp-label">شناسه استان</label>
              <input {...register('parent_id')} dir="ltr" placeholder="ID عددی استان"
                className="cp-input h-11" />
            </div>
          )}
        </form>
      </Modal>

      {/* Edit Modal */}
      <Modal open={!!editTarget} title="ویرایش دسته‌بندی"
        onClose={() => { setEditTarget(null); reset(); }}
        footer={
          <>
            <button onClick={() => { setEditTarget(null); reset(); }}
              className="cp-btn-secondary">
              لغو
            </button>
            <button form="edit-cat-form" type="submit" disabled={isSubmitting}
              className="cp-btn-primary">
              ذخیره
            </button>
          </>
        }
      >
        <form id="edit-cat-form"
          onSubmit={handleSubmit((d) => editTarget && updateMutation.mutate({ id: editTarget.id, d }))}
          className="space-y-4">
          <div>
            <label className="cp-label">نام</label>
            <input {...register('label')}
              className="cp-input h-11" />
            {errors.label && <p className="text-red-500 text-xs mt-1">{errors.label.message}</p>}
          </div>
        </form>
      </Modal>

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