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 { Clinic } from '../types';
import { formatDate, 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';

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

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

  const deleteMutation = useMutation({
    mutationFn: (c: Clinic) => api.delete<ApiResponse<null>>(`/api/v1/clinic/${c.uuid}`),
    onSuccess: () => {
      toast.success('کلینیک حذف شد');
      setDeleteTarget(null);
      qc.invalidateQueries({ queryKey: ['clinics'] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const columns: Column<Clinic>[] = [
    {
      key: 'name',
      header: 'نام کلینیک',
      render: (c) => (
        <div className="flex items-center gap-3">
          {c.logo ? (
            <img src={c.logo} alt="" className="w-8 h-8 rounded-lg object-cover" />
          ) : (
            <div className="w-8 h-8 rounded-lg bg-blue-100 flex items-center justify-center text-blue-700 text-xs font-bold">
              {c.name?.[0]}
            </div>
          )}
          <span className="font-medium text-slate-800 dark:text-slate-100">{c.name}</span>
        </div>
      ),
    },
    { key: 'phone', header: 'تلفن', render: (c) => c.phone ? <span dir="ltr">{c.phone}</span> : '—' },
    {
      key: 'doctors_count',
      header: 'پزشکان',
      render: (c) => (
        <span className="text-xs bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded-full">
          {formatNumber(c.doctors_count ?? 0)} پزشک
        </span>
      ),
    },
    { key: 'is_active', header: 'وضعیت', render: (c) => <ActiveBadge active={c.is_active} /> },
    { key: 'created_at', header: 'تاریخ ثبت', render: (c) => formatDate(c.created_at) },
  ];

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

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

      <div className="cp-card p-6">
        <DataTable<Clinic>
          columns={columns}
          data={items}
          loading={isLoading}
          searchValue={search}
          onSearchChange={(v) => { setSearch(v); setPage(1); }}
          searchPlaceholder="جستجو بر اساس نام کلینیک..."
          emptyMessage="هیچ کلینیکی یافت نشد"
          actions={(clinic) => (
            <>
              <button onClick={() => navigate(`/admin/clinics/${clinic.uuid}`)}
                className="cp-action-view" title="مشاهده">
                <EyeIcon className="w-4 h-4" />
              </button>
              <button onClick={() => navigate(`/admin/clinics/${clinic.uuid}?edit=1`)}
                className="cp-action-edit" title="ویرایش">
                <PencilIcon className="w-4 h-4" />
              </button>
              <button onClick={() => setDeleteTarget(clinic)}
                className="cp-action-delete" title="حذف">
                <TrashIcon className="w-4 h-4" />
              </button>
            </>
          )}
        />
        <Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
      </div>

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