import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { EyeIcon, TrashIcon, PencilIcon, MagnifyingGlassIcon } 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 DataTable, { Column } from '../components/ui/DataTable';
import { ActiveBadge } from '../components/ui/StatusBadge';
import Pagination from '../components/ui/Pagination';
import ConfirmDialog from '../components/ui/ConfirmDialog';

const HUES_LIST = [256, 205, 162, 295, 272];

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) => {
        const hue = HUES_LIST[(c.uuid?.charCodeAt(0) ?? 0) % HUES_LIST.length];
        return (
          <div className="cell-user">
            {c.logo ? (
              <img src={c.logo} alt="" className="avatar sm" style={{ objectFit: 'cover' }} />
            ) : (
              <div className="avatar sm" style={{
                background: `linear-gradient(145deg, oklch(0.62 0.15 ${hue}), oklch(0.48 0.16 ${hue}))`,
              }}>
                {c.name?.[0] ?? '?'}
              </div>
            )}
            <div>
              <b>{c.name}</b>
            </div>
          </div>
        );
      },
    },
    { key: 'phone', header: 'تلفن', render: (c) => c.phone ? <span dir="ltr">{c.phone}</span> : '—' },
    {
      key: 'doctors_count',
      header: 'پزشکان',
      render: (c) => (
        <span className="badge blue">
          <span className="bdot" />
          {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 className="fade-in">
      <div className="card-title-row" style={{ marginBottom: 'var(--gap)' }}>
        <div>
          <h1 className="section-title">کلینیک‌ها</h1>
          <div className="muted">{total} کلینیک ثبت‌شده</div>
        </div>
      </div>

      <div className="card">
        <div className="card-pad" style={{ paddingBottom: 0 }}>
          <div className="toolbar">
            <div className="field" style={{ minWidth: 240 }}>
              <MagnifyingGlassIcon style={{ width: 17, height: 17 }} />
              <input
                value={search}
                onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                placeholder="جستجو بر اساس نام کلینیک..."
              />
            </div>
          </div>
        </div>
        <DataTable<Clinic>
          columns={columns}
          data={items}
          loading={isLoading}
          emptyMessage="هیچ کلینیکی یافت نشد"
          actions={(clinic) => (
            <>
              <button onClick={() => navigate(`/admin/clinics/${clinic.uuid}`)}
                className="mini-btn" title="مشاهده">
                <EyeIcon style={{ width: 15, height: 15 }} />
              </button>
              <button onClick={() => navigate(`/admin/clinics/${clinic.uuid}?edit=1`)}
                className="mini-btn" title="ویرایش">
                <PencilIcon style={{ width: 15, height: 15 }} />
              </button>
              <button onClick={() => setDeleteTarget(clinic)}
                className="mini-btn danger" title="حذف">
                <TrashIcon style={{ width: 15, height: 15 }} />
              </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>
  );
}
