import React, { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ArrowRightIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { Appointment, AppointmentStatus } from '../types';
import { formatDate, formatDateTime, formatRial } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
import StatusBadge from '../components/ui/StatusBadge';
import ConfirmDialog from '../components/ui/ConfirmDialog';

const ALL_STATUSES: { value: AppointmentStatus; label: string }[] = [
  { 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_admin', label: 'لغو توسط ادمین' },
  { value: 'no_show', label: 'غیبت' },
];

function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex items-center justify-between py-3 border-b border-gray-100 last:border-0">
      <span className="text-sm text-gray-500">{label}</span>
      <span className="text-sm font-medium text-gray-900">{value ?? '—'}</span>
    </div>
  );
}

export default function AppointmentDetailPage() {
  const { uuid } = useParams<{ uuid: string }>();
  const navigate = useNavigate();
  const qc = useQueryClient();
  const [cancelOpen, setCancelOpen] = useState(false);
  const [newStatus, setNewStatus] = useState('');

  const { data, isLoading } = useQuery({
    queryKey: ['appointment', uuid],
    queryFn: () => api.get<ApiResponse<Appointment>>(`/api/v1/appointment/${uuid}`),
    enabled: !!uuid,
  });

  const statusMutation = useMutation({
    mutationFn: (status: string) =>
      api.patch<ApiResponse<null>>(`/api/v1/appointment/${uuid}/status`, { status }),
    onSuccess: () => {
      toast.success('وضعیت نوبت بروزرسانی شد');
      qc.invalidateQueries({ queryKey: ['appointment', uuid] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const cancelMutation = useMutation({
    mutationFn: () => api.patch<ApiResponse<null>>(`/api/v1/appointment/${uuid}/cancel`, {}),
    onSuccess: () => {
      toast.success('نوبت لغو شد');
      setCancelOpen(false);
      qc.invalidateQueries({ queryKey: ['appointment', uuid] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const appt = data?.data;

  return (
    <div>
      <PageHeader
        title="جزئیات نوبت"
        breadcrumbs={[
          { label: 'داشبورد', to: '/admin/dashboard' },
          { label: 'نوبت‌ها', to: '/admin/appointments' },
          { label: 'جزئیات' },
        ]}
        action={
          <button onClick={() => navigate('/admin/appointments')}
            className="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-800 transition-colors">
            <ArrowRightIcon className="w-4 h-4" />
            بازگشت
          </button>
        }
      />

      {isLoading ? (
        <div className="bg-white rounded-2xl border border-gray-100 p-6 space-y-3">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="h-8 bg-gray-100 rounded-lg animate-pulse" />
          ))}
        </div>
      ) : appt ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
            <h3 className="font-semibold text-gray-800 mb-4">اطلاعات بیمار</h3>
            <InfoRow label="نام بیمار" value={appt.patient_name} />
            <InfoRow label="موبایل" value={<span dir="ltr">{appt.patient_mobile}</span>} />
            <InfoRow label="پزشک" value={`دکتر ${appt.doctor_name}`} />
            <InfoRow label="کلینیک" value={appt.clinic_name} />
            <InfoRow label="تاریخ نوبت" value={formatDate(appt.appointment_date)} />
            <InfoRow label="ساعت" value={appt.appointment_time} />
            <InfoRow label="مبلغ" value={formatRial(appt.amount)} />
            <InfoRow label="تاریخ ثبت" value={formatDateTime(appt.created_at)} />
          </div>

          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
            <h3 className="font-semibold text-gray-800 mb-4">وضعیت و اقدامات</h3>
            <div className="mb-4">
              <p className="text-sm text-gray-500 mb-2">وضعیت فعلی:</p>
              <StatusBadge type="appointment" value={appt.status} />
            </div>

            <div className="mt-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">تغییر وضعیت:</label>
              <div className="flex gap-2">
                <select
                  value={newStatus}
                  onChange={(e) => setNewStatus(e.target.value)}
                  className="flex-1 h-10 border border-gray-300 rounded-[10px] px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
                >
                  <option value="">انتخاب وضعیت...</option>
                  {ALL_STATUSES.map((s) => (
                    <option key={s.value} value={s.value}>{s.label}</option>
                  ))}
                </select>
                <button
                  onClick={() => newStatus && statusMutation.mutate(newStatus)}
                  disabled={!newStatus || statusMutation.isPending}
                  className="px-4 py-2 bg-primary-600 text-white text-sm rounded-[10px] hover:bg-primary-700 disabled:opacity-50 transition-colors"
                >
                  اعمال
                </button>
              </div>
            </div>

            <div className="mt-4 pt-4 border-t border-gray-100">
              <button
                onClick={() => setCancelOpen(true)}
                className="w-full py-2 border border-red-300 text-red-600 text-sm rounded-[10px] hover:bg-red-50 transition-colors"
              >
                لغو نوبت
              </button>
            </div>
          </div>
        </div>
      ) : (
        <div className="bg-white rounded-2xl border border-gray-100 p-16 text-center text-gray-400">
          نوبتی یافت نشد
        </div>
      )}

      <ConfirmDialog
        open={cancelOpen}
        title="لغو نوبت"
        message="آیا از لغو این نوبت اطمینان دارید؟"
        confirmLabel="لغو نوبت"
        danger
        loading={cancelMutation.isPending}
        onConfirm={() => cancelMutation.mutate()}
        onCancel={() => setCancelOpen(false)}
      />
    </div>
  );
}
