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

const STATUS_FILTERS: { value: string; label: string }[] = [
  { value: '', label: 'همه' },
  { value: 'waiting_for_payment', label: 'در انتظار پرداخت' },
  { value: 'reserved', label: 'رزرو شده' },
  { value: 'checked_in', label: 'ورود به مطب' },
  { value: 'waiting', label: 'در صف انتظار' },
  { value: 'in_progress', label: 'در حال ویزیت' },
  { value: 'visited', label: 'ویزیت شده' },
  { value: 'completed', label: 'تکمیل شده' },
  { value: 'cancelled_by_user', label: 'لغو توسط بیمار' },
  { value: 'no_show', 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/appointments?${params}`);
    },
  });

  const columns: Column<Appointment>[] = [
    {
      key: 'patient',
      header: 'بیمار',
      render: (a) => (
        <div>
          <p className="font-medium text-gray-900">{a.patient_name || '—'}</p>
          <p className="text-xs text-gray-400 dir-ltr">{maskMobile(a.patient_mobile)}</p>
        </div>
      ),
    },
    { key: 'doctor_name', header: 'پزشک', render: (a) => `دکتر ${a.doctor_name}` },
    { key: 'clinic_name', header: 'کلینیک', render: (a) => a.clinic_name ?? '—' },
    {
      key: 'appointment_date',
      header: 'تاریخ نوبت',
      render: (a) => (
        <div>
          <p>{formatDate(a.appointment_date)}</p>
          <p className="text-xs text-gray-400">{a.appointment_time}</p>
        </div>
      ),
    },
    {
      key: 'status',
      header: 'وضعیت',
      render: (a) => <StatusBadge type="appointment" value={a.status} />,
    },
    {
      key: 'amount',
      header: 'مبلغ',
      render: (a) => <span className="text-sm">{formatRial(a.amount)}</span>,
    },
    { key: 'created_at', header: 'تاریخ ثبت', render: (a) => formatDate(a.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">
        <div className="flex items-center gap-3 mb-4 flex-wrap">
          {STATUS_FILTERS.map((f) => (
            <button
              key={f.value}
              onClick={() => { setStatusFilter(f.value); setPage(1); }}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                statusFilter === f.value
                  ? 'bg-primary-600 text-white'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              {f.label}
            </button>
          ))}
        </div>

        <DataTable<Appointment>
          columns={columns}
          data={items}
          loading={isLoading}
          searchValue={search}
          onSearchChange={(v) => { setSearch(v); setPage(1); }}
          searchPlaceholder="جستجو بر اساس موبایل یا نام پزشک..."
          emptyMessage="هیچ نوبتی یافت نشد"
          actions={(appt) => (
            <button
              onClick={() => navigate(`/admin/appointments/${appt.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>
          )}
        />
        <Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
      </div>
    </div>
  );
}
