import { useState, useMemo, useEffect, useCallback } from 'react';
import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Button,
  Table,
  Space,
  Drawer,
  Modal,
  Form,
  DatePicker,
  Radio,
  Divider,
  Typography,
  Breadcrumb,
  Descriptions,
  Tabs,
  message,
  Grid,
  Tag,
  Alert
} from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import {
  PlusOutlined,
  DownloadOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  SaveOutlined,
  CalendarOutlined,
  PrinterOutlined
} from '@ant-design/icons';
import { useApi } from '@/hooks/useApi';
import { PatientsService } from '@/services/patients';
import { InsuranceProvidersService } from '@/services/insuranceProviders';
import { DepartmentsService } from '@/services/departments';
import { UsersService } from '@/services/users';
import { ClinicalService } from '@/services/clinical';
import { BillingService } from '@/services/billing';
import { parseError } from '@/utils/errorHandler';
import { useNavigate } from 'react-router-dom';
import { ROUTES } from '@/constants/routes';
import dayjs from 'dayjs';

interface Patient {
  id: string;
  patient_number: string;
  first_name: string;
  last_name: string;
  date_of_birth: string;
  gender: string;
  phone: string;
  email?: string;
  address?: string;
  city?: string;
  state?: string;
  postal_code?: string;
  country?: string;
  emergency_contact_name?: string;
  emergency_contact_phone?: string;
  emergency_contact_relationship?: string;
  insurance_provider_id?: string;
  insurance_policy_number?: string;
  created_at: string;
  updated_at: string;
}

interface PatientDetail extends Patient {
  insurance_provider?: {
    id: string;
    name: string;
  };
  medical_record?: {
    id: string;
    blood_type?: string;
    allergies?: string;
    chronic_conditions?: string;
    family_medical_history?: string;
    surgical_history?: string;
    immunization_history?: string;
    notes?: string;
  };
  appointments?: Array<{
    id: string;
    appointment_date: string;
    appointment_time: string;
    appointment_type: string;
    status: string;
  }>;
}

interface InsuranceProvider {
  id: string;
  name: string;
}

interface VitalSign {
  id: string;
  recorded_at: string;
  systolic_bp?: number;
  diastolic_bp?: number;
  pulse_rate?: number;
  temperature_celsius?: number;
  respiratory_rate?: number;
  weight_kg?: number;
  height_cm?: number;
  oxygen_saturation?: number;
}

interface Consultation {
  id: string;
  consultation_date: string;
  chief_complaint?: string;
  diagnosis?: string;
  treatment_plan?: string;
}

interface Prescription {
  id: string;
  medication_name: string;
  dosage: string;
  frequency: string;
  duration: string;
  prescribed_date: string;
  is_active: boolean;
}

interface LabTest {
  id: string;
  test_name: string;
  test_type?: string;
  ordered_date: string;
  result_date?: string;
  result_value?: string;
  result_unit?: string;
  reference_range?: string;
  status: string;
}

interface Invoice {
  id: string;
  invoice_number: string;
  invoice_date: string;
  total_amount: number;
  amount_paid: number;
  balance_due: number;
  status: string;
}

const PatientManagementPage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const { useBreakpoint } = Grid;
  const screens = useBreakpoint();

  const [registerForm] = Form.useForm();
  const [editForm] = Form.useForm();

  const [patients, setPatients] = useState<Patient[]>([]);
  const [patientsTotal, setPatientsTotal] = useState(0);
  const [patientsOffset, setPatientsOffset] = useState(0);
  const [patientsLimit, setPatientsLimit] = useState(20);
  const [searchText, setSearchText] = useState('');
  const [filterInsuranceProvider, setFilterInsuranceProvider] = useState('');
  const [loading, setLoading] = useState(false);
  const [registerDrawerVisible, setRegisterDrawerVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [profileDrawerVisible, setProfileDrawerVisible] = useState(false);
  const [selectedPatientId, setSelectedPatientId] = useState<string | null>(null);
  const [patientDetail, setPatientDetail] = useState<PatientDetail | null>(null);
  const [insuranceProviders, setInsuranceProviders] = useState<InsuranceProvider[]>([]);
  const [patientVitalSigns, setPatientVitalSigns] = useState<VitalSign[]>([]);
  const [patientConsultations, setPatientConsultations] = useState<Consultation[]>([]);
  const [patientPrescriptions, setPatientPrescriptions] = useState<Prescription[]>([]);
  const [patientLabTests, setPatientLabTests] = useState<LabTest[]>([]);
  const [patientInvoices, setPatientInvoices] = useState<Invoice[]>([]);
  const [sortField, setSortField] = useState('created_at');
  const [sortOrder, setSortOrder] = useState<'ascend' | 'descend'>('descend');
  const [profileActiveTab, setProfileActiveTab] = useState('demographics');

  const currentPage = useMemo(() => Math.floor(patientsOffset / patientsLimit) + 1, [patientsOffset, patientsLimit]);

  const {
    data: patientsResponse,
    loading: patientsLoading,
    error: patientsError,
    execute: fetchPatients
  } = useApi<{ items: Patient[]; total: number; limit: number; offset: number }>(PatientsService.list);

  const {
    execute: fetchPatientDetail
  } = useApi<PatientDetail>(PatientsService.getDetails);

  const {
    data: insuranceProvidersResponse,
    execute: fetchInsuranceProviders
  } = useApi<{ items: InsuranceProvider[] }>(InsuranceProvidersService.list);

  const {
    execute: fetchVitalSigns
  } = useApi<{ items: VitalSign[] }>(ClinicalService.getVitalSigns);

  const {
    execute: fetchConsultations
  } = useApi<{ items: Consultation[] }>(ClinicalService.getConsultations);

  const {
    execute: fetchPrescriptions
  } = useApi<{ items: Prescription[] }>(ClinicalService.getPrescriptions);

  const {
    execute: fetchLabTests
  } = useApi<{ items: LabTest[] }>(ClinicalService.getLabTests);

  const {
    execute: fetchInvoices
  } = useApi<{ items: Invoice[] }>(BillingService.getInvoices);

  useEffect(() => {
    void fetchPatients({ limit: patientsLimit, offset: patientsOffset, search: searchText });
  }, [fetchPatients, patientsLimit, patientsOffset, searchText]);

  useEffect(() => {
    void fetchInsuranceProviders({ limit: 100, offset: 0 });
  }, [fetchInsuranceProviders]);

  useEffect(() => {
    if (patientsResponse) {
      setPatients(patientsResponse.items ?? []);
      setPatientsTotal(patientsResponse.total ?? 0);
      setLoading(false);
    }
  }, [patientsResponse]);

  useEffect(() => {
    if (insuranceProvidersResponse) {
      setInsuranceProviders(insuranceProvidersResponse.items ?? []);
    }
  }, [insuranceProvidersResponse]);

  useEffect(() => {
    if (patientsError) {
      const { message: errMsg } = parseError(patientsError);
      messageApi.error(errMsg);
      setLoading(false);
    }
  }, [patientsError, messageApi]);

  const calculateAge = useCallback((dateOfBirth: string) => {
    if (!dateOfBirth) return '—';
    const today = dayjs();
    const birthDate = dayjs(dateOfBirth);
    return today.diff(birthDate, 'year').toString();
  }, []);

  const lookupInsuranceProvider = useCallback((insuranceProviderId?: string) => {
    if (!insuranceProviderId) return '—';
    const provider = insuranceProviders.find(p => p.id === insuranceProviderId);
    return provider?.name ?? '—';
  }, [insuranceProviders]);

  const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchText(e.target.value);
    setPatientsOffset(0);
  }, []);

  const handleFilterInsuranceChange = useCallback((value: string) => {
    setFilterInsuranceProvider(value ?? '');
    setPatientsOffset(0);
  }, []);

  const handleTableChange = useCallback((pagination: TablePaginationConfig) => {
    const newPage = pagination.current ?? 1;
    const newPageSize = pagination.pageSize ?? patientsLimit;
    setPatientsLimit(newPageSize);
    setPatientsOffset((newPage - 1) * newPageSize);
  }, [patientsLimit]);

  const handleOpenRegisterDrawer = useCallback(() => {
    setRegisterDrawerVisible(true);
  }, []);

  const handleCloseRegisterDrawer = useCallback(() => {
    setRegisterDrawerVisible(false);
    registerForm.resetFields();
  }, [registerForm]);

  const handleOpenEditModal = useCallback((record: Patient) => {
    setSelectedPatientId(record.id);
    setEditModalVisible(true);
    editForm.setFieldsValue({
      first_name: record.first_name,
      last_name: record.last_name,
      date_of_birth: record.date_of_birth ? dayjs(record.date_of_birth) : null,
      gender: record.gender,
      phone: record.phone,
      email: record.email,
      address: record.address,
      city: record.city,
      state: record.state,
      postal_code: record.postal_code,
      country: record.country,
      emergency_contact_name: record.emergency_contact_name,
      emergency_contact_phone: record.emergency_contact_phone,
      emergency_contact_relationship: record.emergency_contact_relationship,
      insurance_provider_id: record.insurance_provider_id,
      insurance_policy_number: record.insurance_policy_number
    });
  }, [editForm]);

  const handleCloseEditModal = useCallback(() => {
    setEditModalVisible(false);
    editForm.resetFields();
  }, [editForm]);

  const handleOpenProfileDrawer = useCallback(async (record: Patient) => {
    setSelectedPatientId(record.id);
    setProfileDrawerVisible(true);
    setProfileActiveTab('demographics');
    try {
      const detail = await fetchPatientDetail(record.id);
      setPatientDetail(detail ?? null);
    } catch (e) {
      const { message: errMsg } = parseError(e);
      messageApi.error(errMsg);
    }
  }, [fetchPatientDetail, messageApi]);

  const handleCloseProfileDrawer = useCallback(() => {
    setProfileDrawerVisible(false);
    setPatientDetail(null);
    setPatientVitalSigns([]);
    setPatientLabTests([]);
    setPatientConsultations([]);
    setPatientPrescriptions([]);
    setPatientInvoices([]);
  }, []);

  const handleRegisterPatient = useCallback(async () => {
    try {
      const values = await registerForm.validateFields();
      setLoading(true);
      await PatientsService.create({
        patient_number: values.patient_number,
        first_name: values.first_name,
        last_name: values.last_name,
        date_of_birth: values.date_of_birth ? dayjs(values.date_of_birth).format('YYYY-MM-DD') : undefined,
        gender: values.gender,
        phone: values.phone,
        email: values.email,
        address: values.address,
        city: values.city,
        state: values.state,
        postal_code: values.postal_code,
        country: values.country,
        emergency_contact_name: values.emergency_contact_name,
        emergency_contact_phone: values.emergency_contact_phone,
        emergency_contact_relationship: values.emergency_contact_relationship,
        insurance_provider_id: values.insurance_provider_id,
        insurance_policy_number: values.insurance_policy_number
      });
      messageApi.success('Patient registered successfully!');
      handleCloseRegisterDrawer();
      await fetchPatients({ limit: patientsLimit, offset: patientsOffset, search: searchText });
      setLoading(false);
    } catch (e) {
      const { message: errMsg } = parseError(e);
      messageApi.error(errMsg);
      setLoading(false);
    }
  }, [registerForm, messageApi, handleCloseRegisterDrawer, fetchPatients, patientsLimit, patientsOffset, searchText]);

  const handleUpdatePatient = useCallback(async () => {
    if (!selectedPatientId) return;
    try {
      const values = await editForm.validateFields();
      setLoading(true);
      await PatientsService.update(selectedPatientId, {
        first_name: values.first_name,
        last_name: values.last_name,
        date_of_birth: values.date_of_birth ? dayjs(values.date_of_birth).format('YYYY-MM-DD') : undefined,
        gender: values.gender,
        phone: values.phone,
        email: values.email,
        address: values.address,
        city: values.city,
        state: values.state,
        postal_code: values.postal_code,
        country: values.country,
        emergency_contact_name: values.emergency_contact_name,
        emergency_contact_phone: values.emergency_contact_phone,
        emergency_contact_relationship: values.emergency_contact_relationship,
        insurance_provider_id: values.insurance_provider_id,
        insurance_policy_number: values.insurance_policy_number
      });
      messageApi.success('Patient updated successfully!');
      handleCloseEditModal();
      await fetchPatients({ limit: patientsLimit, offset: patientsOffset, search: searchText });
      setLoading(false);
    } catch (e) {
      const { message: errMsg } = parseError(e);
      messageApi.error(errMsg);
      setLoading(false);
    }
  }, [selectedPatientId, editForm, messageApi, handleCloseEditModal, fetchPatients, patientsLimit, patientsOffset, searchText]);

  const handleDeletePatient = useCallback((record: Patient) => {
    Modal.confirm({
      title: 'Delete Patient',
      content: `Are you sure you want to delete ${record.first_name} ${record.last_name}?`,
      okText: 'Delete',
      okType: 'danger',
      cancelText: 'Cancel',
      onOk: async () => {
        try {
          setLoading(true);
          await PatientsService.delete(record.id);
          messageApi.success('Patient deleted successfully');
          await fetchPatients({ limit: patientsLimit, offset: patientsOffset, search: searchText });
          setLoading(false);
        } catch (e) {
          const { message: errMsg } = parseError(e);
          messageApi.error(errMsg);
          setLoading(false);
        }
      }
    });
  }, [messageApi, fetchPatients, patientsLimit, patientsOffset, searchText]);

  const handleExportPatientList = useCallback(() => {
    messageApi.info('Export functionality would download patient list as CSV');
  }, [messageApi]);

  const handleScheduleAppointment = useCallback(() => {
    navigate(ROUTES.APPOINTMENTS);
  }, [navigate]);

  const handlePrintSummary = useCallback(() => {
    window.print();
  }, []);

  const handleProfileTabChange = useCallback(async (key: string) => {
    setProfileActiveTab(key);
    if (!selectedPatientId) return;

    try {
      if (key === 'vitals' && patientVitalSigns.length === 0) {
        const vitalsData = await fetchVitalSigns({ patient_id: selectedPatientId, limit: 20 });
        setPatientVitalSigns(vitalsData?.items ?? []);
      } else if (key === 'consultations' && patientConsultations.length === 0) {
        const consultationsData = await fetchConsultations({ patient_id: selectedPatientId, limit: 20 });
        setPatientConsultations(consultationsData?.items ?? []);
      } else if (key === 'prescriptions' && patientPrescriptions.length === 0) {
        const prescriptionsData = await fetchPrescriptions({ patient_id: selectedPatientId, limit: 50 });
        setPatientPrescriptions(prescriptionsData?.items ?? []);
      } else if (key === 'lab_tests' && patientLabTests.length === 0) {
        const labTestsData = await fetchLabTests({ patient_id: selectedPatientId, limit: 50 });
        setPatientLabTests(labTestsData?.items ?? []);
      } else if (key === 'billing' && patientInvoices.length === 0) {
        const invoicesData = await fetchInvoices({ patient_id: selectedPatientId, limit: 50 });
        setPatientInvoices(invoicesData?.items ?? []);
      }
    } catch (e) {
      const { message: errMsg } = parseError(e);
      messageApi.error(errMsg);
    }
  }, [selectedPatientId, patientVitalSigns, patientConsultations, patientPrescriptions, patientLabTests, patientInvoices, fetchVitalSigns, fetchConsultations, fetchPrescriptions, fetchLabTests, fetchInvoices, messageApi]);

  const patientColumns = useMemo<ColumnsType<Patient>>(() => [
    {
      title: 'Patient ID',
      dataIndex: 'patient_number',
      key: 'patient_number',
      width: 120,
      sorter: true,
      fixed: screens.lg ? 'left' : undefined
    },
    {
      title: 'Name',
      key: 'name',
      width: 180,
      sorter: true,
      render: (_, record) => `${record.first_name} ${record.last_name}`
    },
    {
      title: 'Age',
      key: 'age',
      width: 70,
      render: (_, record) => calculateAge(record.date_of_birth)
    },
    {
      title: 'Gender',
      dataIndex: 'gender',
      key: 'gender',
      width: 90,
      render: (gender: string) => <Tag>{gender}</Tag>
    },
    {
      title: 'Contact',
      dataIndex: 'phone',
      key: 'phone',
      width: 140
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
      width: 200,
      ellipsis: true,
      render: (email?: string) => email ?? '—'
    },
    {
      title: 'Insurance',
      dataIndex: 'insurance_provider_id',
      key: 'insurance_provider_id',
      width: 160,
      render: (providerId?: string) => lookupInsuranceProvider(providerId)
    },
    {
      title: 'Registered',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 120,
      sorter: true,
      render: (date: string) => dayjs(date).format('YYYY-MM-DD')
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 250,
      fixed: screens.lg ? 'right' : undefined,
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => handleOpenProfileDrawer(record)}>
            View
          </Button>
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleOpenEditModal(record)}>
            Edit
          </Button>
          <Button type="link" danger size="small" icon={<DeleteOutlined />} onClick={() => handleDeletePatient(record)}>
            Delete
          </Button>
        </Space>
      )
    }
  ], [screens.lg, calculateAge, lookupInsuranceProvider, handleOpenProfileDrawer, handleOpenEditModal, handleDeletePatient]);

  const vitalSignsColumns = useMemo<ColumnsType<VitalSign>>(() => [
    {
      title: 'Recorded At',
      dataIndex: 'recorded_at',
      key: 'recorded_at',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm')
    },
    {
      title: 'BP (Sys/Dia)',
      key: 'bp',
      render: (_, record) => `${record.systolic_bp ?? '—'}/${record.diastolic_bp ?? '—'}`
    },
    {
      title: 'Pulse',
      dataIndex: 'pulse_rate',
      key: 'pulse_rate',
      render: (val?: number) => val ?? '—'
    },
    {
      title: 'Temp (°C)',
      dataIndex: 'temperature_celsius',
      key: 'temperature_celsius',
      render: (val?: number) => val ?? '—'
    },
    {
      title: 'SpO2 (%)',
      dataIndex: 'oxygen_saturation',
      key: 'oxygen_saturation',
      render: (val?: number) => val ?? '—'
    },
    {
      title: 'Weight (kg)',
      dataIndex: 'weight_kg',
      key: 'weight_kg',
      render: (val?: number) => val ?? '—'
    },
    {
      title: 'Height (cm)',
      dataIndex: 'height_cm',
      key: 'height_cm',
      render: (val?: number) => val ?? '—'
    }
  ], []);

  const consultationsColumns = useMemo<ColumnsType<Consultation>>(() => [
    {
      title: 'Date',
      dataIndex: 'consultation_date',
      key: 'consultation_date',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD')
    },
    {
      title: 'Chief Complaint',
      dataIndex: 'chief_complaint',
      key: 'chief_complaint',
      ellipsis: true,
      render: (val?: string) => val ?? '—'
    },
    {
      title: 'Diagnosis',
      dataIndex: 'diagnosis',
      key: 'diagnosis',
      ellipsis: true,
      render: (val?: string) => val ?? '—'
    },
    {
      title: 'Treatment Plan',
      dataIndex: 'treatment_plan',
      key: 'treatment_plan',
      ellipsis: true,
      render: (val?: string) => val ?? '—'
    }
  ], []);

  const prescriptionsColumns = useMemo<ColumnsType<Prescription>>(() => [
    {
      title: 'Medication',
      dataIndex: 'medication_name',
      key: 'medication_name'
    },
    {
      title: 'Dosage',
      dataIndex: 'dosage',
      key: 'dosage'
    },
    {
      title: 'Frequency',
      dataIndex: 'frequency',
      key: 'frequency'
    },
    {
      title: 'Duration',
      dataIndex: 'duration',
      key: 'duration'
    },
    {
      title: 'Prescribed Date',
      dataIndex: 'prescribed_date',
      key: 'prescribed_date',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD')
    },
    {
      title: 'Active',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (active: boolean) => <Tag color={active ? 'green' : 'red'}>{active ? 'Yes' : 'No'}</Tag>
    }
  ], []);

  const labTestsColumns = useMemo<ColumnsType<LabTest>>(() => [
    {
      title: 'Test Name',
      dataIndex: 'test_name',
      key: 'test_name'
    },
    {
      title: 'Type',
      dataIndex: 'test_type',
      key: 'test_type',
      render: (val?: string) => val ?? '—'
    },
    {
      title: 'Ordered',
      dataIndex: 'ordered_date',
      key: 'ordered_date',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD')
    },
    {
      title: 'Result',
      dataIndex: 'result_value',
      key: 'result_value',
      render: (val?: string) => val ?? '—'
    },
    {
      title: 'Unit',
      dataIndex: 'result_unit',
      key: 'result_unit',
      render: (val?: string) => val ?? '—'
    },
    {
      title: 'Reference',
      dataIndex: 'reference_range',
      key: 'reference_range',
      render: (val?: string) => val ?? '—'
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => <Tag>{status}</Tag>
    }
  ], []);

  const invoicesColumns = useMemo<ColumnsType<Invoice>>(() => [
    {
      title: 'Invoice #',
      dataIndex: 'invoice_number',
      key: 'invoice_number'
    },
    {
      title: 'Date',
      dataIndex: 'invoice_date',
      key: 'invoice_date',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD')
    },
    {
      title: 'Total',
      dataIndex: 'total_amount',
      key: 'total_amount',
      render: (amount: number) => `$${amount.toFixed(2)}`
    },
    {
      title: 'Paid',
      dataIndex: 'amount_paid',
      key: 'amount_paid',
      render: (amount: number) => `$${amount.toFixed(2)}`
    },
    {
      title: 'Balance',
      dataIndex: 'balance_due',
      key: 'balance_due',
      render: (amount: number) => `$${amount.toFixed(2)}`
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => <Tag color={status === 'PAID' ? 'green' : 'orange'}>{status}</Tag>
    }
  ], []);

  const profileTabItems = useMemo(() => [
    {
      key: 'demographics',
      label: 'Demographics',
      children: (
        <Descriptions bordered column={2} size="small">
          <Descriptions.Item label="Full Name">
            {patientDetail ? `${patientDetail.first_name} ${patientDetail.last_name}` : '—'}
          </Descriptions.Item>
          <Descriptions.Item label="Patient ID">{patientDetail?.patient_number ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Date of Birth">
            {patientDetail?.date_of_birth ? dayjs(patientDetail.date_of_birth).format('YYYY-MM-DD') : '—'}
          </Descriptions.Item>
          <Descriptions.Item label="Gender">{patientDetail?.gender ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Phone">{patientDetail?.phone ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Email">{patientDetail?.email ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Address">{patientDetail?.address ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="City">{patientDetail?.city ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="State">{patientDetail?.state ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Postal Code">{patientDetail?.postal_code ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Country">{patientDetail?.country ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Emergency Contact">{patientDetail?.emergency_contact_name ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Emergency Phone">{patientDetail?.emergency_contact_phone ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Relationship">{patientDetail?.emergency_contact_relationship ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Insurance Provider">{patientDetail?.insurance_provider?.name ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Policy Number">{patientDetail?.insurance_policy_number ?? '—'}</Descriptions.Item>
        </Descriptions>
      )
    },
    {
      key: 'medical_record',
      label: 'Medical Record',
      children: (
        <Descriptions bordered column={1} size="small">
          <Descriptions.Item label="Blood Type">{patientDetail?.medical_record?.blood_type ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Allergies">{patientDetail?.medical_record?.allergies ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Chronic Conditions">{patientDetail?.medical_record?.chronic_conditions ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Family Medical History">{patientDetail?.medical_record?.family_medical_history ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Surgical History">{patientDetail?.medical_record?.surgical_history ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Immunization History">{patientDetail?.medical_record?.immunization_history ?? '—'}</Descriptions.Item>
          <Descriptions.Item label="Notes">{patientDetail?.medical_record?.notes ?? '—'}</Descriptions.Item>
        </Descriptions>
      )
    },
    {
      key: 'appointments',
      label: 'Appointments',
      children: (
        <Table
          dataSource={patientDetail?.appointments ?? []}
          columns={[
            {
              title: 'Date',
              dataIndex: 'appointment_date',
              key: 'appointment_date',
              render: (date: string) => dayjs(date).format('YYYY-MM-DD')
            },
            {
              title: 'Time',
              dataIndex: 'appointment_time',
              key: 'appointment_time'
            },
            {
              title: 'Type',
              dataIndex: 'appointment_type',
              key: 'appointment_type',
              render: (type: string) => <Tag>{type}</Tag>
            },
            {
              title: 'Status',
              dataIndex: 'status',
              key: 'status',
              render: (status: string) => <Tag color={status === 'COMPLETED' ? 'green' : 'blue'}>{status}</Tag>
            }
          ]}
          rowKey="id"
          size="small"
          pagination={{ pageSize: 5 }}
        />
      )
    },
    {
      key: 'consultations',
      label: 'Consultations',
      children: (
        <Table
          dataSource={patientConsultations}
          columns={consultationsColumns}
          rowKey="id"
          size="small"
          pagination={{ pageSize: 5 }}
        />
      )
    },
    {
      key: 'prescriptions',
      label: 'Prescriptions',
      children: (
        <Table
          dataSource={patientPrescriptions}
          columns={prescriptionsColumns}
          rowKey="id"
          size="small"
          pagination={{ pageSize: 5 }}
        />
      )
    },
    {
      key: 'vitals',
      label: 'Vital Signs',
      children: (
        <Table
          dataSource={patientVitalSigns}
          columns={vitalSignsColumns}
          rowKey="id"
          size="small"
          pagination={{ pageSize: 5 }}
          scroll={{ x: 'max-content' }}
        />
      )
    },
    {
      key: 'lab_tests',
      label: 'Lab Tests',
      children: (
        <Table
          dataSource={patientLabTests}
          columns={labTestsColumns}
          rowKey="id"
          size="small"
          pagination={{ pageSize: 5 }}
          scroll={{ x: 'max-content' }}
        />
      )
    },
    {
      key: 'billing',
      label: 'Billing',
      children: (
        <Table
          dataSource={patientInvoices}
          columns={invoicesColumns}
          rowKey="id"
          size="small"
          pagination={{ pageSize: 5 }}
        />
      )
    }
  ], [patientDetail, patientConsultations, consultationsColumns, patientPrescriptions, prescriptionsColumns, patientVitalSigns, vitalSignsColumns, patientLabTests, labTestsColumns, patientInvoices, invoicesColumns]);

  return (
    <div style={{ padding: screens.xs ? 12 : 24, minHeight: '100%', background: '#f5f5f5' }}>
      {contextHolder}
      <div style={{ padding: screens.xs ? '12px 12px 0 12px' : '24px 24px 0 24px' }}>
        <Breadcrumb
          items={[
            { title: 'Dashboard' },
            { title: 'Patient Management' }
          ]}
          style={{ marginBottom: 16 }}
        />
        <Typography.Title level={2} style={{ marginBottom: 0 }}>
          Patient Management
        </Typography.Title>
        <Typography.Text type="secondary">
          Register, search, and manage patient profiles and medical records
        </Typography.Text>
      </div>

      <Card bordered={false} style={{ margin: screens.xs ? '12px 12px' : '16px 24px' }}>
        <Row gutter={[16, 16]} align="middle" justify="space-between">
          <Col xs={24} sm={24} md={8} lg={8}>
            <Input.Search
              placeholder="Search by name, patient ID, phone, email..."
              allowClear
              enterButton
              value={searchText}
              onChange={handleSearchChange}
              style={{ width: '100%' }}
            />
          </Col>
          <Col xs={24} sm={12} md={6} lg={5}>
            <Select
              placeholder="Filter by Insurance"
              allowClear
              showSearch
              optionFilterProp="label"
              value={filterInsuranceProvider || undefined}
              onChange={handleFilterInsuranceChange}
              style={{ width: '100%' }}
              options={(insuranceProviders ?? []).map(ip => ({ label: ip.name, value: ip.id }))}
            />
          </Col>
          <Col xs={24} sm={12} md={10} lg={11}>
            <Space wrap style={{ display: 'flex', justifyContent: 'flex-end', width: '100%' }}>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleOpenRegisterDrawer}>
                Register New Patient
              </Button>
              {!screens.xs && (
                <Button icon={<DownloadOutlined />} onClick={handleExportPatientList}>
                  Export
                </Button>
              )}
            </Space>
          </Col>
        </Row>
      </Card>

      <Card bordered={false} style={{ margin: screens.xs ? '0 12px 12px 12px' : '0 24px 24px 24px' }}>
        {patientsError && (
          <Alert
            message="Error Loading Patients"
            description="Failed to load patients. Please try again."
            type="error"
            showIcon
            closable
            style={{ marginBottom: 16 }}
          />
        )}
        <Table
          dataSource={patients}
          columns={patientColumns}
          rowKey="id"
          loading={patientsLoading || loading}
          pagination={{
            current: currentPage,
            pageSize: patientsLimit,
            total: patientsTotal,
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} patients`
          }}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
          size={screens.xs ? 'small' : 'middle'}
        />
      </Card>

      <Drawer
        title="Register New Patient"
        open={registerDrawerVisible}
        onClose={handleCloseRegisterDrawer}
        width={screens.xs ? '100%' : 720}
        placement="right"
        destroyOnClose
        maskClosable={false}
      >
        <Form form={registerForm} layout="vertical" onFinish={handleRegisterPatient}>
          <Divider orientation="left">Personal Information</Divider>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="first_name" label="First Name" rules={[{ required: true, message: 'First name is required' }]}>
                <Input placeholder="Enter first name" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="last_name" label="Last Name" rules={[{ required: true, message: 'Last name is required' }]}>
                <Input placeholder="Enter last name" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="date_of_birth"
                label="Date of Birth"
                rules={[{ required: true, message: 'Date of birth is required' }]}
                extra="Age will be auto-calculated"
              >
                <DatePicker
                  format="YYYY-MM-DD"
                  disabledDate={(current) => current && current > dayjs()}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="gender" label="Gender" rules={[{ required: true, message: 'Gender is required' }]}>
                <Radio.Group
                  options={[
                    { label: 'Male', value: 'MALE' },
                    { label: 'Female', value: 'FEMALE' },
                    { label: 'Other', value: 'OTHER' }
                  ]}
                  optionType="button"
                  buttonStyle="solid"
                />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">Contact Information</Divider>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="phone" label="Mobile Number" rules={[{ required: true, message: 'Mobile number is required' }]}>
                <Input placeholder="Enter mobile number" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="email" label="Email" rules={[{ type: 'email', message: 'Please enter a valid email' }]}>
                <Input placeholder="Enter email address" />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">Address</Divider>
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item name="address" label="Street Address">
                <Input placeholder="Enter street address" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="city" label="City">
                <Input placeholder="City" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="state" label="State">
                <Input placeholder="State" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="postal_code" label="Postal Code">
                <Input placeholder="Zip" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="country" label="Country">
                <Input placeholder="Country" />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">Emergency Contact</Divider>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="emergency_contact_name" label="Contact Name">
                <Input placeholder="Emergency contact name" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="emergency_contact_relationship" label="Relationship">
                <Select
                  placeholder="Select relationship"
                  options={[
                    { label: 'Spouse', value: 'Spouse' },
                    { label: 'Parent', value: 'Parent' },
                    { label: 'Sibling', value: 'Sibling' },
                    { label: 'Child', value: 'Child' },
                    { label: 'Friend', value: 'Friend' },
                    { label: 'Other', value: 'Other' }
                  ]}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="emergency_contact_phone"
                label="Contact Phone"
                rules={[{ required: true, message: 'Emergency contact phone is required' }]}
              >
                <Input placeholder="Emergency contact phone" />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">Insurance Information</Divider>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="insurance_provider_id" label="Insurance Provider">
                <Select
                  placeholder="Select insurance provider"
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  options={(insuranceProviders ?? []).map(ip => ({ label: ip.name, value: ip.id }))}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="insurance_policy_number" label="Policy Number">
                <Input placeholder="Enter policy number" />
              </Form.Item>
            </Col>
          </Row>

          <Space style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 24 }}>
            <Button onClick={handleCloseRegisterDrawer}>Cancel</Button>
            <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
              Register Patient
            </Button>
          </Space>
        </Form>
      </Drawer>

      <Modal
        title="Edit Patient"
        open={editModalVisible}
        onCancel={handleCloseEditModal}
        width={screens.xs ? '100%' : 720}
        destroyOnClose
        maskClosable={false}
        footer={null}
      >
        <Form form={editForm} layout="vertical" onFinish={handleUpdatePatient}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="first_name" label="First Name" rules={[{ required: true, message: 'First name is required' }]}>
                <Input placeholder="Enter first name" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="last_name" label="Last Name" rules={[{ required: true, message: 'Last name is required' }]}>
                <Input placeholder="Enter last name" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="date_of_birth" label="Date of Birth" rules={[{ required: true, message: 'Date of birth is required' }]}>
                <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="gender" label="Gender" rules={[{ required: true, message: 'Gender is required' }]}>
                <Radio.Group
                  options={[
                    { label: 'Male', value: 'MALE' },
                    { label: 'Female', value: 'FEMALE' },
                    { label: 'Other', value: 'OTHER' }
                  ]}
                  optionType="button"
                  buttonStyle="solid"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="phone" label="Mobile Number" rules={[{ required: true, message: 'Mobile number is required' }]}>
                <Input placeholder="Enter mobile number" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="email" label="Email" rules={[{ type: 'email', message: 'Please enter a valid email' }]}>
                <Input placeholder="Enter email address" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item name="address" label="Street Address">
                <Input placeholder="Enter street address" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="city" label="City">
                <Input placeholder="City" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="state" label="State">
                <Input placeholder="State" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="postal_code" label="Postal Code">
                <Input placeholder="Zip" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="country" label="Country">
                <Input placeholder="Country" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="emergency_contact_name" label="Emergency Contact Name">
                <Input placeholder="Contact name" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="emergency_contact_relationship" label="Relationship">
                <Select
                  placeholder="Select relationship"
                  options={[
                    { label: 'Spouse', value: 'Spouse' },
                    { label: 'Parent', value: 'Parent' },
                    { label: 'Sibling', value: 'Sibling' },
                    { label: 'Child', value: 'Child' },
                    { label: 'Friend', value: 'Friend' },
                    { label: 'Other', value: 'Other' }
                  ]}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="emergency_contact_phone"
                label="Emergency Phone"
                rules={[{ required: true, message: 'Emergency contact phone is required' }]}
              >
                <Input placeholder="Emergency phone" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="insurance_provider_id" label="Insurance Provider">
                <Select
                  placeholder="Select insurance provider"
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  options={(insuranceProviders ?? []).map(ip => ({ label: ip.name, value: ip.id }))}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="insurance_policy_number" label="Policy Number">
                <Input placeholder="Enter policy number" />
              </Form.Item>
            </Col>
          </Row>
          <Space style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
            <Button onClick={handleCloseEditModal}>Cancel</Button>
            <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
              Update Patient
            </Button>
          </Space>
        </Form>
      </Modal>

      <Drawer
        title="Patient Profile"
        open={profileDrawerVisible}
        onClose={handleCloseProfileDrawer}
        width={screens.xs ? '100%' : 900}
        placement="right"
        destroyOnClose
      >
        <div>
          <Row gutter={[16, 16]} align="middle" justify="space-between" style={{ marginBottom: 16 }}>
            <Col span={16}>
              <Typography.Title level={3} style={{ marginBottom: 4 }}>
                {patientDetail ? `${patientDetail.first_name} ${patientDetail.last_name}` : ''}
              </Typography.Title>
              <Typography.Text type="secondary">
                {patientDetail ? `ID: ${patientDetail.patient_number}` : ''}
              </Typography.Text>
            </Col>
            <Col span={8}>
              <Space wrap style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Button type="primary" icon={<CalendarOutlined />} size="small" onClick={handleScheduleAppointment}>
                  Schedule Appointment
                </Button>
                <Button icon={<PrinterOutlined />} size="small" onClick={handlePrintSummary}>
                  Print Summary
                </Button>
              </Space>
            </Col>
          </Row>
          <Tabs activeKey={profileActiveTab} onChange={handleProfileTabChange} type="card" items={profileTabItems} />
        </div>
      </Drawer>
    </div>
  );
};

export default PatientManagementPage;