import React, { useState, useEffect, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import {
  MagnifyingGlassIcon, PlusIcon, EyeIcon, TrashIcon, ArrowPathIcon,
  CheckCircleIcon, XCircleIcon, TableCellsIcon, Squares2X2Icon,
} from '@heroicons/react/24/outline';
import { StarIcon as StarSolid } from '@heroicons/react/24/solid';
import { StarIcon } from '@heroicons/react/24/outline';
import { XMarkIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
import { formatDate, formatNumber } from '../lib/utils';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import Pagination from '../components/ui/Pagination';

// ── Types ─────────────────────────────────────────────────────────────────

interface AdminDoctor {
  uuid: string;
  id: number;
  name: string;
  gender: string | null;
  degree: string | null;
  medical_code: string | null;
  mobile: string | null;
  email: string | null;
  is_active: boolean;
  rate: number;
  specialties: { id: number; name: string }[];
  profile_image: string | null;
  created_at: string;
}

interface DoctorStats {
  total: number;
  active: number;
  inactive: number;
  male: number;
  female: number;
}

interface SpecialtyOption {
  id: number;
  uuid: string;
  name: string;
}

// ── Helpers ───────────────────────────────────────────────────────────────

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

const DEGREE_BADGE: Record<string, string> = {
  general:           'gray',
  specialist:        'blue',
  expert:            'violet',
  subspecialistplus: 'amber',
};

const DEGREE_LABEL: Record<string, string> = {
  general:           'عمومی',
  specialist:        'متخصص',
  expert:            'فوق تخصص',
  subspecialistplus: 'فلوشیپ',
};

function DoctorAvatar({ name, id, image, size = 'sm' }: {
  name: string; id: number; image: string | null; size?: 'sm' | 'lg';
}) {
  const initials = name.split(' ').filter(Boolean).map((w) => w[0]).join('').toUpperCase().slice(0, 2) || 'Dr';
  const hue = HUES_LIST[id % HUES_LIST.length];
  if (image) {
    return (
      <div className={`avatar ${size}`} style={{ padding: 0, overflow: 'hidden' }}>
        <img src={image} alt={name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
      </div>
    );
  }
  return (
    <div
      className={`avatar ${size}`}
      style={{ background: `linear-gradient(145deg, oklch(0.62 0.15 ${hue}), oklch(0.48 0.16 ${hue}))` }}
    >
      {initials}
    </div>
  );
}

function StarRating({ rate }: { rate: number }) {
  return (
    <span className="stars" dir="ltr">
      {Array.from({ length: 5 }).map((_, i) =>
        i < Math.round(rate)
          ? <StarSolid key={i} style={{ width: 13, height: 13 }} />
          : <StarIcon key={i} style={{ width: 13, height: 13, color: 'var(--border-2)' }} />
      )}
    </span>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────

export default function DoctorsPage() {
  const navigate = useNavigate();
  const qc       = useQueryClient();

  const [page, setPage]               = useState(1);
  const [limit]                       = useState(25);
  const [searchInput, setSearchInput] = useState('');
  const [search, setSearch]           = useState('');
  const [status, setStatus]           = useState('');
  const [specialtyId, setSpecialty]   = useState('');
  const [view, setView]               = useState<'table' | 'grid'>('table');
  const [selected, setSelected]       = useState<string[]>([]);
  const [deleteTarget, setDeleteTarget]     = useState<AdminDoctor | null>(null);
  const [confirmBulkDel, setConfirmBulkDel] = useState(false);
  const [bulkDeleting, setBulkDeleting]     = useState(false);

  useEffect(() => {
    const t = setTimeout(() => { setSearch(searchInput); setPage(1); }, 350);
    return () => clearTimeout(t);
  }, [searchInput]);

  useEffect(() => { setPage(1); setSelected([]); }, [status, specialtyId]);

  // ── Queries ──

  const statsQ = useQuery({
    queryKey: ['doctors-stats'],
    queryFn: () => api.get<ApiResponse<DoctorStats>>('/api/v1/admin/doctors/stats'),
    staleTime: 30_000,
  });

  const specialtiesQ = useQuery({
    queryKey: ['specialties-list'],
    queryFn: () => api.get<ApiResponse<SpecialtyOption[]>>('/api/v1/specialties'),
    staleTime: 300_000,
  });

  const doctorsQ = useQuery({
    queryKey: ['admin-doctors', page, limit, search, status, specialtyId],
    queryFn: () => {
      const p = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (search)      p.set('search', search);
      if (status)      p.set('status', status);
      if (specialtyId) p.set('specialty_id', specialtyId);
      return api.get<PaginatedResponse<AdminDoctor>>(`/api/v1/admin/doctors?${p}`);
    },
  });

  const stats: DoctorStats | undefined = useMemo(
    () => (statsQ.data?.data as any)?.data ?? statsQ.data?.data, [statsQ.data]
  );
  const items: AdminDoctor[] = doctorsQ.data?.data ?? [];
  const total                = doctorsQ.data?.meta?.totalRecords ?? 0;
  const specialties: SpecialtyOption[] = useMemo(
    () => (specialtiesQ.data?.data as any)?.data ?? specialtiesQ.data?.data ?? [],
    [specialtiesQ.data]
  );

  // ── Mutations ──

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

  const toggleMut = useMutation({
    mutationFn: (uuid: string) => api.post<ApiResponse<{ is_active: boolean }>>(`/api/v1/admin/doctors/${uuid}/status`, {}),
    onSuccess: () => {
      toast.success('وضعیت پزشک تغییر کرد');
      qc.invalidateQueries({ queryKey: ['admin-doctors'] });
      qc.invalidateQueries({ queryKey: ['doctors-stats'] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  // ── Bulk ──

  const allSelected = items.length > 0 && items.every((d) => selected.includes(d.uuid));
  const toggleAll   = () => setSelected(allSelected ? [] : items.map((d) => d.uuid));
  const toggleOne   = (uuid: string) =>
    setSelected((prev) => prev.includes(uuid) ? prev.filter((id) => id !== uuid) : [...prev, uuid]);

  const handleBulkDelete = async () => {
    setBulkDeleting(true);
    let count = 0;
    for (const uuid of selected) {
      try { await api.delete(`/api/v1/doctor/${uuid}`); count++; } catch {}
    }
    setBulkDeleting(false);
    setConfirmBulkDel(false);
    setSelected([]);
    toast.success(`${formatNumber(count)} پزشک حذف شد`);
    qc.invalidateQueries({ queryKey: ['admin-doctors'] });
    qc.invalidateQueries({ queryKey: ['doctors-stats'] });
  };

  const kpiCards = [
    { label: 'کل پزشکان', value: stats?.total,    bg: 'var(--surface-3)',  color: 'var(--text-2)'  },
    { label: 'فعال',       value: stats?.active,   bg: 'var(--success-bg)', color: 'var(--success)' },
    { label: 'غیرفعال',    value: stats?.inactive, bg: 'var(--surface-3)',  color: 'var(--text-3)'  },
    { label: 'مرد',        value: stats?.male,     bg: 'var(--info-bg)',    color: 'var(--info)'    },
    { label: 'زن',         value: stats?.female,   bg: 'var(--violet-bg)',  color: 'var(--violet)'  },
  ];

  return (
    <div className="fade-in">
      {/* Header */}
      <div className="card-title-row" style={{ marginBottom: 'var(--gap)' }}>
        <div>
          <h1 className="section-title">پزشکان</h1>
          <div className="muted" style={{ fontSize: 13, marginTop: 3 }}>مدیریت پزشکان، تخصص‌ها و وضعیت همکاری</div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn ghost sm">
            <ArrowPathIcon style={{ width: 15, height: 15 }} />
            خروجی
          </button>
          <button className="btn primary sm" onClick={() => navigate('/admin/doctors/new')}>
            <PlusIcon style={{ width: 15, height: 15 }} />
            افزودن پزشک
          </button>
        </div>
      </div>

      {/* KPI cards */}
      <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(5,1fr)' }}>
        {kpiCards.map((c) => (
          <div key={c.label} className="stat">
            <div className="ico" style={{ background: c.bg, color: c.color }}>
              <svg style={{ width: 20, height: 20 }} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
              </svg>
            </div>
            <div className="lbl">{c.label}</div>
            <div className="val">
              {c.value === undefined
                ? <span className="skeleton" style={{ display: 'inline-block', width: 48, height: 26, borderRadius: 4 }} />
                : formatNumber(c.value)}
            </div>
          </div>
        ))}
      </div>

      {/* Main card */}
      <div className="card">
        {/* Toolbar */}
        <div className="card-pad" style={{ paddingBottom: 0 }}>
          <div className="toolbar">
            <div className="field" style={{ minWidth: 240 }}>
              <MagnifyingGlassIcon style={{ width: 17, height: 17 }} />
              <input
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
                placeholder="نام پزشک یا موبایل..."
              />
            </div>
            {specialties.length > 0 && (
              <div className="field">
                <select value={specialtyId} onChange={(e) => setSpecialty(e.target.value)}>
                  <option value="">همه تخصص‌ها</option>
                  {specialties.map((s) => (
                    <option key={s.id} value={String(s.id)}>{s.name}</option>
                  ))}
                </select>
              </div>
            )}
            <div className="seg">
              <button className={!status ? 'on' : ''} onClick={() => setStatus('')}>همه</button>
              <button className={status === 'active' ? 'on' : ''} onClick={() => setStatus('active')}>فعال</button>
              <button className={status === 'inactive' ? 'on' : ''} onClick={() => setStatus('inactive')}>غیرفعال</button>
            </div>
            <div className="spacer" />
            <div className="seg">
              <button className={view === 'table' ? 'on' : ''} onClick={() => setView('table')} title="جدول">
                <TableCellsIcon style={{ width: 16, height: 16 }} />
              </button>
              <button className={view === 'grid' ? 'on' : ''} onClick={() => setView('grid')} title="کارت">
                <Squares2X2Icon style={{ width: 16, height: 16 }} />
              </button>
            </div>
            <button className="btn ghost sm" onClick={() => doctorsQ.refetch()} disabled={doctorsQ.isFetching}>
              <ArrowPathIcon style={{ width: 15, height: 15, animation: doctorsQ.isFetching ? 'spin 1s linear infinite' : undefined }} />
            </button>
          </div>
        </div>

        {/* Bulk bar */}
        {selected.length > 0 && (
          <div style={{
            padding: '10px 16px', background: 'var(--primary-soft)',
            borderBottom: '1px solid var(--border)',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <span style={{ fontSize: 13, color: 'var(--primary-700)', fontWeight: 600 }}>
              {formatNumber(selected.length)} پزشک انتخاب شده
            </span>
            <div style={{ display: 'flex', gap: 8, marginRight: 'auto' }}>
              <button className="btn danger sm" onClick={() => setConfirmBulkDel(true)}>حذف انتخاب‌شده‌ها</button>
              <button className="btn ghost sm" onClick={() => setSelected([])}>لغو</button>
            </div>
          </div>
        )}

        {/* Table view */}
        {view === 'table' && (
          <div className="table-wrap">
            <table className="t">
              <thead>
                <tr>
                  <th style={{ width: 42 }}>
                    <input type="checkbox" checked={allSelected} onChange={toggleAll}
                      style={{ accentColor: 'var(--primary)', cursor: 'pointer' }} />
                  </th>
                  <th>پزشک</th>
                  <th>تخصص</th>
                  <th>درجه</th>
                  <th>امتیاز</th>
                  <th>موبایل</th>
                  <th>وضعیت</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {doctorsQ.isLoading && Array.from({ length: 6 }).map((_, i) => (
                  <tr key={i}>
                    {Array.from({ length: 8 }).map((_, j) => (
                      <td key={j}>
                        <div className="skeleton" style={{ height: 14, borderRadius: 6, width: j === 1 ? '70%' : '55%' }} />
                      </td>
                    ))}
                  </tr>
                ))}

                {!doctorsQ.isLoading && items.length === 0 && (
                  <tr>
                    <td colSpan={8}>
                      <div className="empty">هیچ پزشکی یافت نشد</div>
                    </td>
                  </tr>
                )}

                {!doctorsQ.isLoading && items.map((doc) => (
                  <tr key={doc.uuid} style={{ cursor: 'pointer' }} onClick={() => navigate(`/admin/doctors/${doc.uuid}`)}>
                    <td onClick={(e) => e.stopPropagation()}>
                      <input type="checkbox" checked={selected.includes(doc.uuid)}
                        onChange={() => toggleOne(doc.uuid)}
                        style={{ accentColor: 'var(--primary)', cursor: 'pointer' }} />
                    </td>
                    <td>
                      <div className="cell-user">
                        <DoctorAvatar name={doc.name} id={doc.id} image={doc.profile_image} />
                        <div>
                          <b>دکتر {doc.name}</b>
                          <br /><small>{doc.gender ?? '—'}</small>
                        </div>
                      </div>
                    </td>
                    <td>
                      {doc.specialties.slice(0, 2).map((s) => (
                        <span key={s.id} className="badge gray" style={{ marginInlineEnd: 4, fontSize: 11 }}>{s.name}</span>
                      ))}
                      {doc.specialties.length > 2 && (
                        <span className="muted" style={{ fontSize: 11 }}>+{doc.specialties.length - 2}</span>
                      )}
                    </td>
                    <td>
                      {doc.degree && (
                        <span className={`badge ${DEGREE_BADGE[doc.degree] ?? 'gray'}`}>
                          <span className="bdot" />
                          {DEGREE_LABEL[doc.degree] ?? doc.degree}
                        </span>
                      )}
                    </td>
                    <td>
                      <div className="flex" style={{ gap: 5 }}>
                        <StarRating rate={doc.rate} />
                        <b style={{ fontSize: 12.5 }}>{doc.rate.toFixed(1)}</b>
                      </div>
                    </td>
                    <td style={{ fontFamily: 'monospace', direction: 'ltr', textAlign: 'right' }} className="muted">
                      {doc.mobile ?? '—'}
                    </td>
                    <td>
                      <span className={`badge ${doc.is_active ? 'green' : 'gray'}`}>
                        <span className="bdot" />
                        {doc.is_active ? 'فعال' : 'غیرفعال'}
                      </span>
                    </td>
                    <td onClick={(e) => e.stopPropagation()}>
                      <div className="row-actions">
                        <button className="mini-btn" title="مشاهده"
                          onClick={() => navigate(`/admin/doctors/${doc.uuid}`)}>
                          <EyeIcon style={{ width: 16, height: 16 }} />
                        </button>
                        <button className="mini-btn" title={doc.is_active ? 'غیرفعال کردن' : 'فعال‌سازی'}
                          onClick={() => toggleMut.mutate(doc.uuid)} disabled={toggleMut.isPending}>
                          {doc.is_active
                            ? <XCircleIcon style={{ width: 16, height: 16 }} />
                            : <CheckCircleIcon style={{ width: 16, height: 16 }} />}
                        </button>
                        <button className="mini-btn danger" title="حذف" onClick={() => setDeleteTarget(doc)}>
                          <TrashIcon style={{ width: 16, height: 16 }} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Grid view */}
        {view === 'grid' && (
          <div className="card-pad" style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
            gap: 'var(--gap)',
          }}>
            {doctorsQ.isLoading && Array.from({ length: 8 }).map((_, i) => (
              <div key={i} className="card card-pad" style={{ boxShadow: 'none' }}>
                <div className="flex" style={{ gap: 12, marginBottom: 12 }}>
                  <div className="skeleton" style={{ width: 38, height: 38, borderRadius: '50%', flexShrink: 0 }} />
                  <div style={{ flex: 1 }}>
                    <div className="skeleton" style={{ height: 14, borderRadius: 4, width: '70%', marginBottom: 8 }} />
                    <div className="skeleton" style={{ height: 12, borderRadius: 4, width: '50%' }} />
                  </div>
                </div>
              </div>
            ))}

            {!doctorsQ.isLoading && items.map((doc) => (
              <div
                key={doc.uuid}
                className="card card-pad"
                style={{ cursor: 'pointer', boxShadow: 'none' }}
                onClick={() => navigate(`/admin/doctors/${doc.uuid}`)}
              >
                <div className="flex" style={{ gap: 12, marginBottom: 12 }}>
                  <DoctorAvatar name={doc.name} id={doc.id} image={doc.profile_image} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <b style={{ display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      دکتر {doc.name}
                    </b>
                    <span className="muted" style={{ fontSize: 12.5 }}>
                      {doc.specialties[0]?.name ?? '—'}
                    </span>
                  </div>
                  <span className={`badge ${doc.is_active ? 'green' : 'gray'}`}>
                    <span className="bdot" />
                    {doc.is_active ? 'فعال' : 'غیرفعال'}
                  </span>
                </div>
                <div className="flex" style={{ justifyContent: 'space-between', fontSize: 12.5 }}>
                  <span className="flex" style={{ gap: 5 }}>
                    <StarRating rate={doc.rate} />
                    <b>{doc.rate.toFixed(1)}</b>
                  </span>
                  <span className="muted">{formatDate(doc.created_at)}</span>
                </div>
              </div>
            ))}

            {!doctorsQ.isLoading && items.length === 0 && (
              <div className="empty" style={{ gridColumn: '1/-1' }}>هیچ پزشکی یافت نشد</div>
            )}
          </div>
        )}

        <Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
      </div>

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

      <ConfirmDialog
        open={confirmBulkDel}
        title="حذف گروهی"
        message={`آیا از حذف ${formatNumber(selected.length)} پزشک انتخاب‌شده اطمینان دارید؟`}
        confirmLabel={`حذف ${formatNumber(selected.length)} پزشک`}
        danger
        loading={bulkDeleting}
        onConfirm={handleBulkDelete}
        onCancel={() => setConfirmBulkDel(false)}
      />
    </div>
  );
}
