import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { EyeIcon, TrashIcon, PencilIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
import type { Doctor } from '../types';
import { formatDate } 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';

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

  const { data, isLoading } = useQuery({
    queryKey: ['doctors', page, search],
    queryFn: () =>
      api.get<PaginatedResponse<Doctor>>(
        `/api/v1/doctors?page=${page}&limit=${limit}${search ? `&search=${encodeURIComponent(search)}` : ''}`,
      ),
  });

  const deleteMutation = useMutation({
    mutationFn: (d: Doctor) => api.delete<ApiResponse<null>>(`/api/v1/doctor/${d.uuid}`),
    onSuccess: () => {
      toast.success('پزشک حذف شد');
      setDeleteTarget(null);
      qc.invalidateQueries({ queryKey: ['doctors'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const columns: Column<Doctor>[] = [
    {
      key: 'name',
      header: 'نام',
      render: (d) => (
        <div className="flex items-center gap-3">
          {d.profile_image ? (
            <img src={d.profile_image} alt="" className="w-8 h-8 rounded-full object-cover" />
          ) : (
            <div className="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center text-primary-700 text-xs font-bold">
              {d.first_name?.[0] ?? '?'}
            </div>
          )}
          <span className="font-medium text-gray-900">{d.first_name} {d.last_name}</span>
        </div>
      ),
    },
    { key: 'medical_code', header: 'کد نظام پزشکی' },
    {
      key: 'degree',
      header: 'درجه',
      render: (d) => <span className="text-xs bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full">{d.degree}</span>,
    },
    {
      key: 'gender',
      header: 'جنسیت',
      render: (d) => d.gender === 'male' ? 'آقا' : 'خانم',
    },
    {
      key: 'specialties',
      header: 'تخصص‌ها',
      render: (d) => (
        <div className="flex flex-wrap gap-1">
          {d.specialties?.slice(0, 2).map((s) => (
            <span key={s.uuid} className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">{s.name}</span>
          ))}
          {(d.specialties?.length ?? 0) > 2 && (
            <span className="text-xs text-gray-400">+{d.specialties.length - 2}</span>
          )}
        </div>
      ),
    },
    {
      key: 'is_active',
      header: 'وضعیت',
      render: (d) => <ActiveBadge active={d.is_active} />,
    },
    {
      key: 'created_at',
      header: 'تاریخ ثبت',
      render: (d) => formatDate(d.created_at),
    },
  ];

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

  return (
    <div>
      <PageHeader
        title="پزشکان"
        breadcrumbs={[{ label: 'داشبورد', to: '/admin/dashboard' }, { label: 'پزشکان' }]}
      />

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <DataTable<Doctor>
          columns={columns}
          data={items}
          loading={isLoading}
          searchValue={search}
          onSearchChange={(v) => { setSearch(v); setPage(1); }}
          searchPlaceholder="جستجو بر اساس نام یا کد نظام پزشکی..."
          emptyMessage="هیچ پزشکی یافت نشد"
          actions={(doctor) => (
            <>
              <button
                onClick={() => navigate(`/admin/doctors/${doctor.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={() => navigate(`/admin/doctors/${doctor.uuid}?edit=1`)}
                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(doctor)}
                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>

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