import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import {
  MagnifyingGlassIcon, EyeIcon,
  CalendarIcon, ClockIcon, CheckCircleIcon, XCircleIcon,
} from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { PaginatedResponse } from '../lib/api';
import type { Appointment } from '../types';
import { formatDate, formatRial, maskMobile } from '../lib/utils';
import DataTable, { Column } from '../components/ui/DataTable';
import StatusBadge from '../components/ui/StatusBadge';
import Pagination from '../components/ui/Pagination';

const STATUS_FILTERS = [
  { value: '', label: 'همه' },
  { value: 'waiting_for_payment', label: 'در انتظار پرداخت' },
  { value: 'reserved', label: 'رزرو شده' },
  { value: 'visited', label: 'ویزیت شده' },
  { value: 'cancelled_by_user', label: 'لغو شده' },
];

export default function AppointmentsPage() {
  const navigate = useNavigate();
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const limit = 15;

  const { data, isLoading } = useQuery({
    queryKey: ['appointments', page, search, statusFilter],
    queryFn: () => {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (search) params.set('search', search);
      if (statusFilter) params.set('status', statusFilter);
      return api.get<PaginatedResponse<Appointment>>(`/api/v1/admin/appointments?${params}`);
    },
  });

  const columns: Column<Appointment>[] = [
    {
      key: 'patient',
      header: 'بیمار',
      render: (a) => (
        <div className="cell-user">
          <div className="avatar sm" style={{
            background: `linear-gradient(145deg, oklch(0.62 0.15 222), oklch(0.48 0.16 222))`,
          }}>
            {(a.patient_name ?? '؟').slice(0, 2)}
          </div>
          <div>
            <b>{a.patient_name || '—'}</b>
            <br /><small dir="ltr">{maskMobile(a.patient_mobile)}</small>
          </div>
        </div>
      ),
    },
    { key: 'doctor_name', header: 'پزشک', render: (a) => `دکتر ${a.doctor_name}` },
    { key: 'clinic_name', header: 'کلینیک', render: (a) => <span className="muted">{a.clinic_name ?? '—'}</span> },
    {
      key: 'appointment_date',
      header: 'تاریخ نوبت',
      render: (a) => (
        <div>
          <span>{formatDate(a.appointment_date)}</span>
          <br /><small className="muted">{a.appointment_time}</small>
        </div>
      ),
    },
    {
      key: 'status',
      header: 'وضعیت',
      render: (a) => <StatusBadge type="appointment" value={a.status} />,
    },
    {
      key: 'amount',
      header: 'مبلغ',
      render: (a) => <><b>{formatRial(a.amount)}</b> <span className="muted" style={{ fontSize: 11 }}>تومان</span></>,
    },
    { key: 'created_at', header: 'تاریخ ثبت', render: (a) => <span className="muted">{formatDate(a.created_at)}</span> },
  ];

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

  const statCards = [
    { label: 'کل نوبت‌ها',  value: total > 0 ? String(total) : null, bg: 'var(--info-bg)',    color: 'var(--info)',    Icon: CalendarIcon },
    { label: 'در انتظار',    value: null,                              bg: 'var(--warning-bg)', color: 'var(--warning)', Icon: ClockIcon },
    { label: 'ویزیت شده',    value: null,                              bg: 'var(--success-bg)', color: 'var(--success)', Icon: CheckCircleIcon },
    { label: 'لغو شده',      value: null,                              bg: 'var(--danger-bg)',  color: 'var(--danger)',  Icon: XCircleIcon },
  ];

  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>
        <button className="btn primary sm">
          <CalendarIcon style={{ width: 15, height: 15 }} />
          ثبت نوبت جدید
        </button>
      </div>

      {/* Stat cards */}
      <div className="stat-grid" style={{ gridTemplateColumns: 'repeat(4,1fr)' }}>
        {statCards.map((c) => (
          <div key={c.label} className="stat">
            <div className="ico" style={{ background: c.bg, color: c.color }}>
              <c.Icon style={{ width: 20, height: 20 }} />
            </div>
            <div className="lbl">{c.label}</div>
            <div className="val">
              {isLoading
                ? <span className="skeleton" style={{ display: 'inline-block', width: 48, height: 26, borderRadius: 4 }} />
                : c.value ?? '—'}
            </div>
          </div>
        ))}
      </div>

      {/* Main card */}
      <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
                placeholder="جستجو بر اساس موبایل یا نام..."
                value={search}
                onChange={(e) => { setSearch(e.target.value); setPage(1); }}
              />
            </div>
            <div className="seg">
              {STATUS_FILTERS.map((f) => (
                <button
                  key={f.value}
                  className={statusFilter === f.value ? 'on' : ''}
                  onClick={() => { setStatusFilter(f.value); setPage(1); }}
                >
                  {f.label}
                </button>
              ))}
            </div>
          </div>
        </div>

        <DataTable<Appointment>
          columns={columns}
          data={items}
          loading={isLoading}
          emptyMessage="هیچ نوبتی یافت نشد"
          actions={(appt) => (
            <button
              className="mini-btn"
              onClick={() => navigate(`/admin/appointments/${appt.uuid}`)}
              title="مشاهده"
            >
              <EyeIcon style={{ width: 16, height: 16 }} />
            </button>
          )}
        />
        <Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
      </div>
    </div>
  );
}
