import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { EyeIcon, TrashIcon, PlusIcon } 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, PaginatedResponse } from '../lib/api';
import type { Representation } from '../types';
import { formatDate, formatRial, formatNumber } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
import DataTable, { Column } from '../components/ui/DataTable';
import { ActiveBadge } from '../components/ui/StatusBadge';
import Pagination from '../components/ui/Pagination';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import Modal from '../components/ui/Modal';

const schema = z.object({
  domain: z.string().min(3, 'دامنه معتبر نیست'),
  city: z.string().min(2, 'شهر را وارد کنید'),
  commission_percent: z.coerce.number().min(0).max(100),
});
type FormData = z.infer<typeof schema>;

export default function RepresentationsPage() {
  const navigate = useNavigate();
  const qc = useQueryClient();
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [addOpen, setAddOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Representation | null>(null);
  const limit = 15;

  const { data, isLoading } = useQuery({
    queryKey: ['representations', page, search],
    queryFn: () => {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (search) params.set('search', search);
      return api.get<PaginatedResponse<Representation>>(`/api/v1/representations?${params}`);
    },
  });

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

  const createMutation = useMutation({
    mutationFn: (d: FormData) => api.post<ApiResponse<Representation>>('/api/v1/representation', d),
    onSuccess: () => {
      toast.success('نماینده اضافه شد');
      setAddOpen(false);
      reset();
      qc.invalidateQueries({ queryKey: ['representations'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const deleteMutation = useMutation({
    mutationFn: (r: Representation) => api.delete<ApiResponse<null>>(`/api/v1/representation/${r.uuid}`),
    onSuccess: () => {
      toast.success('نماینده حذف شد');
      setDeleteTarget(null);
      qc.invalidateQueries({ queryKey: ['representations'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const columns: Column<Representation>[] = [
    { key: 'domain', header: 'دامنه', render: (r) => <span dir="ltr" className="font-medium text-primary-700">{r.domain}</span> },
    { key: 'city', header: 'شهر' },
    {
      key: 'commission_percent',
      header: 'کمیسیون',
      render: (r) => `${formatNumber(r.commission_percent)}٪`,
    },
    {
      key: 'wallet_balance',
      header: 'موجودی کیف‌پول',
      render: (r) => formatRial(r.wallet_balance),
    },
    { key: 'is_active', header: 'وضعیت', render: (r) => <ActiveBadge active={r.is_active} /> },
    { key: 'created_at', header: 'تاریخ ثبت', render: (r) => formatDate(r.created_at) },
  ];

  const items = data?.data?.items ?? [];
  const total = data?.data?.total ?? 0;

  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 p-6">
        <DataTable<Representation>
          columns={columns}
          data={items}
          loading={isLoading}
          searchValue={search}
          onSearchChange={(v) => { setSearch(v); setPage(1); }}
          searchPlaceholder="جستجو بر اساس دامنه یا شهر..."
          emptyMessage="هیچ نماینده‌ای یافت نشد"
          actions={(rep) => (
            <>
              <button onClick={() => navigate(`/admin/representations/${rep.uuid}`)}
                className="p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors" title="مشاهده">
                <EyeIcon className="w-4 h-4" />
              </button>
              <button onClick={() => setDeleteTarget(rep)}
                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>
            </>
          )}
        />
        <Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
      </div>

      <Modal open={addOpen} title="افزودن نماینده" onClose={() => setAddOpen(false)}
        footer={
          <>
            <button onClick={() => setAddOpen(false)}
              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="add-rep-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">
              {isSubmitting ? 'در حال ذخیره...' : 'ذخیره'}
            </button>
          </>
        }
      >
        <form id="add-rep-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('domain')} dir="ltr" placeholder="example.com"
              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.domain && <p className="text-red-500 text-xs mt-1">{errors.domain.message}</p>}
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">شهر</label>
            <input {...register('city')} 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.city && <p className="text-red-500 text-xs mt-1">{errors.city.message}</p>}
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">درصد کمیسیون</label>
            <input {...register('commission_percent')} type="number" min="0" max="100" placeholder="10"
              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.commission_percent && <p className="text-red-500 text-xs mt-1">{errors.commission_percent.message}</p>}
          </div>
        </form>
      </Modal>

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