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, Category } 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({
  full_name: z.string().min(2, 'نام الزامی است'),
  mobile_number: z.string().min(10, 'شماره موبایل معتبر نیست'),
  city_id: z.coerce.number().nullable().optional(),
  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 [cityFilter, setCityFilter] = useState('');
  const [addOpen, setAddOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Representation | null>(null);
  const limit = 15;

  // Load city list for filter and form
  const citiesQuery = useQuery({
    queryKey: ['categories', 'city'],
    queryFn: () => api.get<ApiResponse<{ data: Category[] }>>('/api/v1/categorys/city'),
    staleTime: 5 * 60_000,
  });
  const cities: Category[] = (citiesQuery.data?.data as any)?.data ?? [];

  const { data, isLoading } = useQuery({
    queryKey: ['representations', page, search, cityFilter],
    queryFn: () => {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (search) params.set('search', search);
      if (cityFilter) params.set('city_id', cityFilter);
      return api.get<PaginatedResponse<Representation>>(`/api/v1/admin/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', {
        full_name: d.full_name,
        mobile_number: d.mobile_number,
        city_id: d.city_id || null,
        commission_percent: d.commission_percent,
      }),
    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: 'full_name', header: 'نام', render: (r) => <span className="font-medium">{r.full_name}</span> },
    { key: 'mobile_number', header: 'موبایل', render: (r) => <span dir="ltr">{r.mobile_number ?? '—'}</span> },
    { key: 'city', header: 'شهر', render: (r) => r.city ?? '—' },
    {
      key: 'commission_percent',
      header: 'کمیسیون',
      render: (r) => `${formatNumber(r.commission_percent)}٪`,
    },
    {
      key: 'wallet_balance',
      header: 'موجودی کیف‌پول',
      render: (r) => formatRial(r.wallet_balance ?? 0),
    },
    { key: 'is_active', header: 'وضعیت', render: (r) => <ActiveBadge active={r.is_active ?? r.active ?? false} /> },
    { key: 'created_at', header: 'تاریخ ثبت', render: (r) => formatDate(r.created_at) },
  ];

  const items = data?.data ?? [];
  const total = data?.meta?.totalRecords ?? 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">
        {/* City filter */}
        <div className="mb-4 flex items-center gap-3">
          <select
            value={cityFilter}
            onChange={(e) => { setCityFilter(e.target.value); setPage(1); }}
            className="h-10 border border-gray-300 rounded-[10px] px-3 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-primary-500 bg-white min-w-[160px]"
          >
            <option value="">همه شهرها</option>
            {cities.map((c) => (
              <option key={c.id} value={String(c.id)}>{c.label}</option>
            ))}
          </select>
          {cityFilter && (
            <button
              onClick={() => { setCityFilter(''); setPage(1); }}
              className="text-xs text-gray-400 hover:text-gray-600 transition-colors"
            >
              پاک کردن فیلتر
            </button>
          )}
        </div>

        <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); 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="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('full_name')} 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.full_name && <p className="text-red-500 text-xs mt-1">{errors.full_name.message}</p>}
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">شماره موبایل</label>
            <input {...register('mobile_number')} dir="ltr" placeholder="09xxxxxxxxx"
              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.mobile_number && <p className="text-red-500 text-xs mt-1">{errors.mobile_number.message}</p>}
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">شهر</label>
            <select {...register('city_id')}
              className="w-full h-11 border border-gray-300 rounded-[10px] px-3 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-primary-500 bg-white">
              <option value="">انتخاب شهر</option>
              {cities.map((c) => (
                <option key={c.id} value={c.id}>{c.label}</option>
              ))}
            </select>
          </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" 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" />
            {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?.full_name}" اطمینان دارید؟`}
        confirmLabel="حذف"
        danger
        loading={deleteMutation.isPending}
        onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget)}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}
