import { useState, useMemo, useEffect, useCallback } from 'react';
import {
  Layout,
  Card,
  Button,
  Table,
  Space,
  Input,
  Select,
  DatePicker,
  TimePicker,
  Form,
  Drawer,
  Modal,
  Tag,
  Radio,
  InputNumber,
  Checkbox,
  List,
  Badge,
  Typography,
  Descriptions,
  Row,
  Col,
  Calendar as AntCalendar,
  Segmented,
  message,
  Grid
} from 'antd';
import {
  PlusOutlined,
  DownloadOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  CalendarOutlined,
  LeftOutlined,
  RightOutlined,
  CheckOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { useApi } from '@/hooks/useApi';
import { AppointmentsService } from '@/services/appointments';
import { DepartmentsService } from '@/services/departments';
import { UsersService } from '@/services/users';
import { PatientsService } from '@/services/patients';
import { parseError } from '@/utils/errorHandler';
import { useNavigate } from 'react-router-dom';
import { ROUTES } from '@/constants/routes';

const { Title } = Typography;
const { useBreakpoint } = Grid;

interface Appointment {
  id: string;
  patient_id: string;
  doctor_id: string;
  department_id?: string;
  appointment_date: string;
  appointment_time: string;
  duration_minutes: number;
  appointment_type: string;
  status: string;
  reason?: string;
  notes?: string;
  created_at: string;
  updated_at: string;
}

interface AppointmentDetail extends Appointment {
  patient?: {
    id: string;
    first_name: string;
    last_name: string;
    patient_number: string;
  };
  doctor?: {
    id: string;
    first_name: string;
    last_name: string;
  };
  department?: {
    id: string;
    name: string;
  };
}

interface Department {
  id: string;
  name: string;
  description?: string;
}

interface Doctor {
  id: string;
  first_name: string;
  last_name: string;
  email: string;
  role: string;
  department_id?: string;
  is_active: boolean;
}

interface Patient {
  id: string;
  patient_number: string;
  first_name: string;
  last_name: string;
  date_of_birth: string;
  gender: string;
  phone?: string;
  email?: string;
}

interface PaginatedAppointmentResponse {
  items: Appointment[];
  total: number;
  limit: number;
  offset: number;
}

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

  const [appointments, setAppointments] = useState<Appointment[]>([]);
  const [appointmentsTotal, setAppointmentsTotal] = useState(0);
  const [departments, setDepartments] = useState<Department[]>([]);
  const [doctors, setDoctors] = useState<Doctor[]>([]);
  const [patients, setPatients] = useState<Patient[]>([]);
  const [activeView, setActiveView] = useState<'calendar' | 'list'>('list');
  const [calendarMode, setCalendarMode] = useState<'month' | 'week' | 'day'>('month');
  const [calendarDate, setCalendarDate] = useState<Dayjs | null>(dayjs());
  const [filterDepartmentId, setFilterDepartmentId] = useState<string | undefined>(undefined);
  const [filterDoctorId, setFilterDoctorId] = useState<string | undefined>(undefined);
  const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
  const [filterAppointmentType, setFilterAppointmentType] = useState<string | undefined>(undefined);
  const [filterDateRange, setFilterDateRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [searchText, setSearchText] = useState('');
  const [quickFilter, setQuickFilter] = useState<'today' | 'this_week' | 'upcoming' | 'all'>('today');
  const [pagination, setPagination] = useState({ limit: 20, offset: 0 });
  const [loading, setLoading] = useState(false);
  const [newAppointmentDrawerVisible, setNewAppointmentDrawerVisible] = useState(false);
  const [appointmentDetailPopoverVisible, setAppointmentDetailPopoverVisible] = useState(false);
  const [selectedAppointmentId, setSelectedAppointmentId] = useState<string | null>(null);
  const [selectedAppointmentDetail, setSelectedAppointmentDetail] = useState<AppointmentDetail | null>(null);
  const [cancelModalVisible, setCancelModalVisible] = useState(false);
  const [rescheduleModalVisible, setRescheduleModalVisible] = useState(false);
  const [checkedInAppointments, setCheckedInAppointments] = useState<Appointment[]>([]);

  const [appointmentForm] = Form.useForm();
  const [cancelForm] = Form.useForm();
  const [rescheduleForm] = Form.useForm();

  const { data: appointmentsData, loading: appointmentsLoading, execute: fetchAppointments } = useApi<PaginatedAppointmentResponse>(
    AppointmentsService.list
  );

  const { data: appointmentDetailData, execute: fetchAppointmentDetail } = useApi<AppointmentDetail>(
    AppointmentsService.getDetails
  );

  const { data: departmentsData, execute: fetchDepartments } = useApi<{ items: Department[] }>(
    DepartmentsService.list
  );

  const { data: doctorsData, execute: fetchDoctors } = useApi<{ items: Doctor[] }>(
    UsersService.list
  );

  const { data: patientsData, execute: fetchPatients } = useApi<{ items: Patient[] }>(
    PatientsService.list
  );

  const { data: checkedInData, execute: fetchCheckedInAppointments } = useApi<PaginatedAppointmentResponse>(
    AppointmentsService.list
  );

  useEffect(() => {
    void fetchAppointments({
      limit: pagination.limit,
      offset: pagination.offset,
      status: filterStatus,
      appointment_type: filterAppointmentType,
      doctor_id: filterDoctorId,
      department_id: filterDepartmentId,
      appointment_date: filterDateRange?.[0]?.format('YYYY-MM-DD')
    });
  }, [fetchAppointments, pagination, filterStatus, filterAppointmentType, filterDoctorId, filterDepartmentId, filterDateRange]);

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

  useEffect(() => {
    void fetchDoctors({ limit: 100, offset: 0, role: 'DOCTOR', is_active: true });
  }, [fetchDoctors]);

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

  useEffect(() => {
    void fetchCheckedInAppointments({ limit: 50, offset: 0, status: 'CHECKED_IN' });
  }, [fetchCheckedInAppointments]);

  useEffect(() => {
    if (appointmentsData) {
      setAppointments(appointmentsData.items ?? []);
      setAppointmentsTotal(appointmentsData.total ?? 0);
    }
  }, [appointmentsData]);

  useEffect(() => {
    if (appointmentDetailData) {
      setSelectedAppointmentDetail(appointmentDetailData);
    }
  }, [appointmentDetailData]);

  useEffect(() => {
    if (departmentsData?.items) {
      setDepartments(departmentsData.items);
    }
  }, [departmentsData]);

  useEffect(() => {
    if (doctorsData?.items) {
      setDoctors(doctorsData.items);
    }
  }, [doctorsData]);

  useEffect(() => {
    if (patientsData?.items) {
      setPatients(patientsData.items);
    }
  }, [patientsData]);

  useEffect(() => {
    if (checkedInData?.items) {
      setCheckedInAppointments(checkedInData.items);
    }
  }, [checkedInData]);

  useEffect(() => {
    if (selectedAppointmentId) {
      void fetchAppointmentDetail(selectedAppointmentId);
    }
  }, [selectedAppointmentId, fetchAppointmentDetail]);

  const filteredDoctors = useMemo(() => {
    return filterDepartmentId
      ? doctors.filter(d => d.department_id === filterDepartmentId)
      : doctors;
  }, [doctors, filterDepartmentId]);

  const queueCount = useMemo(() => checkedInAppointments.length, [checkedInAppointments]);

  const handleOpenNewAppointmentDrawer = useCallback(() => {
    setNewAppointmentDrawerVisible(true);
  }, []);

  const handleCloseNewAppointmentDrawer = useCallback(() => {
    setNewAppointmentDrawerVisible(false);
    appointmentForm.resetFields();
  }, [appointmentForm]);

  const handleSubmitNewAppointment = useCallback(async () => {
    try {
      const values = await appointmentForm.validateFields();
      setLoading(true);
      await AppointmentsService.create({
        patient_id: values.patient_id,
        doctor_id: values.doctor_id,
        department_id: values.department_id,
        appointment_date: values.appointment_date?.format('YYYY-MM-DD'),
        appointment_time: values.appointment_time?.format('HH:mm'),
        duration_minutes: values.duration_minutes ?? 30,
        appointment_type: values.appointment_type,
        status: 'SCHEDULED',
        reason: values.reason,
        notes: values.notes
      });
      messageApi.success('Appointment created successfully');
      setNewAppointmentDrawerVisible(false);
      appointmentForm.resetFields();
      void fetchAppointments({
        limit: pagination.limit,
        offset: pagination.offset,
        status: filterStatus,
        appointment_type: filterAppointmentType,
        doctor_id: filterDoctorId,
        department_id: filterDepartmentId
      });
    } catch (error) {
      const { message: errorMessage } = parseError(error);
      messageApi.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, [appointmentForm, messageApi, fetchAppointments, pagination, filterStatus, filterAppointmentType, filterDoctorId, filterDepartmentId]);

  const handleCheckInAppointment = useCallback(async (id: string) => {
    try {
      setLoading(true);
      await AppointmentsService.createCheckIn(id);
      messageApi.success('Patient checked in successfully');
      void fetchAppointments({
        limit: pagination.limit,
        offset: pagination.offset,
        status: filterStatus,
        appointment_type: filterAppointmentType,
        doctor_id: filterDoctorId,
        department_id: filterDepartmentId
      });
      void fetchCheckedInAppointments({ limit: 50, offset: 0, status: 'CHECKED_IN' });
    } catch (error) {
      const { message: errorMessage } = parseError(error);
      messageApi.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, [messageApi, fetchAppointments, fetchCheckedInAppointments, pagination, filterStatus, filterAppointmentType, filterDoctorId, filterDepartmentId]);

  const handleOpenCancelModal = useCallback((id: string) => {
    setSelectedAppointmentId(id);
    setCancelModalVisible(true);
  }, []);

  const handleConfirmCancelAppointment = useCallback(async () => {
    if (!selectedAppointmentId) return;
    try {
      await cancelForm.validateFields();
      setLoading(true);
      await AppointmentsService.createCancel(selectedAppointmentId);
      messageApi.warning('Appointment cancelled');
      setCancelModalVisible(false);
      setAppointmentDetailPopoverVisible(false);
      cancelForm.resetFields();
      void fetchAppointments({
        limit: pagination.limit,
        offset: pagination.offset,
        status: filterStatus,
        appointment_type: filterAppointmentType,
        doctor_id: filterDoctorId,
        department_id: filterDepartmentId
      });
    } catch (error) {
      const { message: errorMessage } = parseError(error);
      messageApi.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, [selectedAppointmentId, cancelForm, messageApi, fetchAppointments, pagination, filterStatus, filterAppointmentType, filterDoctorId, filterDepartmentId]);

  const handleOpenRescheduleModal = useCallback((id: string) => {
    setSelectedAppointmentId(id);
    setRescheduleModalVisible(true);
  }, []);

  const handleSubmitReschedule = useCallback(async () => {
    if (!selectedAppointmentId) return;
    try {
      const values = await rescheduleForm.validateFields();
      setLoading(true);
      await AppointmentsService.update(selectedAppointmentId, {
        appointment_date: values.appointment_date?.format('YYYY-MM-DD'),
        appointment_time: values.appointment_time?.format('HH:mm')
      });
      messageApi.success('Appointment rescheduled successfully');
      setRescheduleModalVisible(false);
      setAppointmentDetailPopoverVisible(false);
      rescheduleForm.resetFields();
      void fetchAppointments({
        limit: pagination.limit,
        offset: pagination.offset,
        status: filterStatus,
        appointment_type: filterAppointmentType,
        doctor_id: filterDoctorId,
        department_id: filterDepartmentId
      });
    } catch (error) {
      const { message: errorMessage } = parseError(error);
      messageApi.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, [selectedAppointmentId, rescheduleForm, messageApi, fetchAppointments, pagination, filterStatus, filterAppointmentType, filterDoctorId, filterDepartmentId]);

  const handleCompleteAppointment = useCallback(async (id: string) => {
    Modal.confirm({
      title: 'Complete Appointment',
      content: 'Are you sure you want to mark this appointment as completed?',
      onOk: async () => {
        try {
          setLoading(true);
          await AppointmentsService.createComplete(id);
          messageApi.success('Appointment completed');
          setAppointmentDetailPopoverVisible(false);
          void fetchAppointments({
            limit: pagination.limit,
            offset: pagination.offset,
            status: filterStatus,
            appointment_type: filterAppointmentType,
            doctor_id: filterDoctorId,
            department_id: filterDepartmentId
          });
          void fetchCheckedInAppointments({ limit: 50, offset: 0, status: 'CHECKED_IN' });
        } catch (error) {
          const { message: errorMessage } = parseError(error);
          messageApi.error(errorMessage);
        } finally {
          setLoading(false);
        }
      }
    });
  }, [messageApi, fetchAppointments, fetchCheckedInAppointments, pagination, filterStatus, filterAppointmentType, filterDoctorId, filterDepartmentId]);

  const handleSelectAppointment = useCallback((id: string) => {
    setSelectedAppointmentId(id);
    setAppointmentDetailPopoverVisible(true);
  }, []);

  const handleCloseDetailPopover = useCallback(() => {
    setAppointmentDetailPopoverVisible(false);
    setSelectedAppointmentId(null);
    setSelectedAppointmentDetail(null);
  }, []);

  const handleTableChange = useCallback((paginationConfig: any) => {
    setPagination({
      limit: paginationConfig.pageSize ?? 20,
      offset: ((paginationConfig.current ?? 1) - 1) * (paginationConfig.pageSize ?? 20)
    });
  }, []);

  const getStatusColor = useCallback((status: string) => {
    switch (status) {
      case 'SCHEDULED':
      case 'CONFIRMED':
        return 'blue';
      case 'CHECKED_IN':
        return 'green';
      case 'IN_PROGRESS':
        return 'orange';
      case 'COMPLETED':
        return 'default';
      case 'CANCELLED':
      case 'NO_SHOW':
        return 'red';
      default:
        return 'default';
    }
  }, []);

  const columns: ColumnsType<Appointment> = useMemo(
    () => [
      {
        title: 'Appointment ID',
        dataIndex: 'id',
        key: 'id',
        width: 120,
        ellipsis: true,
        responsive: ['lg'] as any
      },
      {
        title: 'Patient',
        dataIndex: 'patient_id',
        key: 'patient_id',
        width: 160,
        render: (patientId: string) => {
          const patient = patients.find(p => p.id === patientId);
          return patient ? `${patient.first_name ?? ''} ${patient.last_name ?? ''}` : '—';
        }
      },
      {
        title: 'Doctor',
        dataIndex: 'doctor_id',
        key: 'doctor_id',
        width: 150,
        render: (doctorId: string) => {
          const doctor = doctors.find(d => d.id === doctorId);
          return doctor ? `${doctor.first_name ?? ''} ${doctor.last_name ?? ''}` : '—';
        }
      },
      {
        title: 'Department',
        dataIndex: 'department_id',
        key: 'department_id',
        width: 130,
        responsive: ['md'] as any,
        render: (deptId?: string) => {
          if (!deptId) return '—';
          const dept = departments.find(d => d.id === deptId);
          return dept?.name ?? '—';
        }
      },
      {
        title: 'Date',
        dataIndex: 'appointment_date',
        key: 'appointment_date',
        width: 110,
        sorter: true
      },
      {
        title: 'Time',
        dataIndex: 'appointment_time',
        key: 'appointment_time',
        width: 90
      },
      {
        title: 'Duration',
        dataIndex: 'duration_minutes',
        key: 'duration_minutes',
        width: 90,
        responsive: ['lg'] as any,
        render: (minutes: number) => `${minutes} min`
      },
      {
        title: 'Type',
        dataIndex: 'appointment_type',
        key: 'appointment_type',
        width: 130,
        render: (type: string) => <Tag>{type}</Tag>
      },
      {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        width: 120,
        render: (status: string) => <Tag color={getStatusColor(status)}>{status}</Tag>
      },
      {
        title: 'Actions',
        key: 'actions',
        width: 200,
        fixed: 'right' as any,
        render: (_: any, record: Appointment) => (
          <Space size="small">
            {record.status === 'SCHEDULED' && (
              <Button type="link" size="small" onClick={() => handleCheckInAppointment(record.id)}>
                Check-in
              </Button>
            )}
            {(record.status === 'SCHEDULED' || record.status === 'CONFIRMED') && (
              <>
                <Button type="link" size="small" onClick={() => handleOpenRescheduleModal(record.id)}>
                  Reschedule
                </Button>
                <Button type="link" size="small" danger onClick={() => handleOpenCancelModal(record.id)}>
                  Cancel
                </Button>
              </>
            )}
            {record.status === 'CHECKED_IN' && (
              <Button type="link" size="small" onClick={() => handleCompleteAppointment(record.id)}>
                Complete
              </Button>
            )}
          </Space>
        )
      }
    ],
    [patients, doctors, departments, getStatusColor, handleCheckInAppointment, handleOpenRescheduleModal, handleOpenCancelModal, handleCompleteAppointment]
  );

  const patientOptions = useMemo(
    () =>
      (patients ?? []).map(p => ({
        label: `${p.first_name ?? ''} ${p.last_name ?? ''} (${p.patient_number ?? ''})`,
        value: p.id
      })),
    [patients]
  );

  const doctorOptions = useMemo(
    () =>
      (filteredDoctors ?? []).map(d => ({
        label: `${d.first_name ?? ''} ${d.last_name ?? ''}`,
        value: d.id
      })),
    [filteredDoctors]
  );

  return (
    <div style={{ padding: (screens.xs ?? false) ? 12 : 24, minHeight: '100%' }}>
      {contextHolder}

      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 24,
          flexWrap: 'wrap',
          gap: 12
        }}
      >
        <Title level={3} style={{ margin: 0 }}>
          Appointments & Scheduling
        </Title>
        <Space size="middle">
          <Button type="primary" icon={<PlusOutlined />} onClick={handleOpenNewAppointmentDrawer}>
            New Appointment
          </Button>
          <Button icon={<DownloadOutlined />}>Export to Excel</Button>
        </Space>
      </div>

      <Row gutter={[16, 16]}>
        <Col xs={24} lg={18}>
          <Card bodyStyle={{ padding: 16 }} style={{ marginBottom: 16 }}>
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                flexWrap: 'wrap',
                gap: 12,
                marginBottom: 12
              }}
            >
              <Radio.Group
                value={activeView}
                onChange={e => setActiveView(e.target.value)}
                optionType="button"
                buttonStyle="solid"
                options={[
                  { label: 'Calendar View', value: 'calendar' },
                  { label: 'List View', value: 'list' }
                ]}
              />
              <Radio.Group
                value={quickFilter}
                onChange={e => setQuickFilter(e.target.value)}
                optionType="button"
                size="small"
                options={[
                  { label: 'Today', value: 'today' },
                  { label: 'This Week', value: 'this_week' },
                  { label: 'Upcoming', value: 'upcoming' },
                  { label: 'All', value: 'all' }
                ]}
              />
            </div>

            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
              <Input.Search
                placeholder="Search patient name or ID..."
                allowClear
                value={searchText}
                onChange={e => setSearchText(e.target.value)}
                style={{ width: (screens.xs ?? false) ? '100%' : 240 }}
              />
              <Select
                placeholder="Department"
                allowClear
                value={filterDepartmentId}
                onChange={value => {
                  setFilterDepartmentId(value);
                  setFilterDoctorId(undefined);
                }}
                style={{ width: (screens.xs ?? false) ? '100%' : 180 }}
                options={(departments ?? []).map(d => ({ label: d.name, value: d.id }))}
              />
              <Select
                placeholder="Doctor"
                allowClear
                showSearch
                optionFilterProp="label"
                value={filterDoctorId}
                onChange={value => setFilterDoctorId(value)}
                style={{ width: (screens.xs ?? false) ? '100%' : 180 }}
                options={doctorOptions}
              />
              <Select
                placeholder="Appointment Type"
                allowClear
                value={filterAppointmentType}
                onChange={value => setFilterAppointmentType(value)}
                style={{ width: (screens.xs ?? false) ? '100%' : 180 }}
                options={[
                  { label: 'Consultation', value: 'CONSULTATION' },
                  { label: 'Follow-up', value: 'FOLLOW_UP' },
                  { label: 'Emergency', value: 'EMERGENCY' },
                  { label: 'Routine Checkup', value: 'ROUTINE_CHECKUP' },
                  { label: 'Procedure', value: 'PROCEDURE' }
                ]}
              />
              <Select
                placeholder="Status"
                allowClear
                value={filterStatus}
                onChange={value => setFilterStatus(value)}
                style={{ width: (screens.xs ?? false) ? '100%' : 160 }}
                options={[
                  { label: 'Scheduled', value: 'SCHEDULED' },
                  { label: 'Confirmed', value: 'CONFIRMED' },
                  { label: 'Checked In', value: 'CHECKED_IN' },
                  { label: 'In Progress', value: 'IN_PROGRESS' },
                  { label: 'Completed', value: 'COMPLETED' },
                  { label: 'Cancelled', value: 'CANCELLED' },
                  { label: 'No Show', value: 'NO_SHOW' }
                ]}
              />
              <DatePicker.RangePicker
                value={filterDateRange}
                onChange={value => setFilterDateRange(value as [Dayjs, Dayjs] | null)}
                style={{ width: (screens.xs ?? false) ? '100%' : 260 }}
              />
            </div>
          </Card>

          {activeView === 'calendar' && (
            <Card bodyStyle={{ padding: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                <Space>
                  <Button icon={<LeftOutlined />} size="small" onClick={() => setCalendarDate(calendarDate?.subtract(1, calendarMode === 'month' ? 'month' : calendarMode === 'week' ? 'week' : 'day') ?? null)} />
                  <Button size="small" onClick={() => setCalendarDate(dayjs())}>
                    Today
                  </Button>
                  <Button icon={<RightOutlined />} size="small" onClick={() => setCalendarDate(calendarDate?.add(1, calendarMode === 'month' ? 'month' : calendarMode === 'week' ? 'week' : 'day') ?? null)} />
                </Space>
                <Segmented
                  value={calendarMode}
                  onChange={value => setCalendarMode(value as 'month' | 'week' | 'day')}
                  options={[
                    { label: 'Month', value: 'month' },
                    { label: 'Week', value: 'week' },
                    { label: 'Day', value: 'day' }
                  ]}
                />
              </div>
              <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', padding: '8px 0' }}>
                <Tag color="blue">Scheduled</Tag>
                <Tag color="green">Checked In</Tag>
                <Tag color="orange">In Progress</Tag>
                <Tag color="default">Completed</Tag>
                <Tag color="red">Cancelled</Tag>
              </div>
              <AntCalendar
                value={calendarDate ?? undefined}
                onChange={setCalendarDate}
                mode={(calendarMode === 'month' ? 'month' : 'month') as any}
                style={{ minHeight: 500 }}
              />
            </Card>
          )}

          {activeView === 'list' && (
            <Card bodyStyle={{ padding: 0 }}>
              <Table
                rowKey="id"
                dataSource={appointments}
                columns={columns}
                loading={(appointmentsLoading ?? false) || loading}
                pagination={{
                  total: appointmentsTotal,
                  pageSize: pagination.limit,
                  current: Math.floor(pagination.offset / pagination.limit) + 1,
                  showSizeChanger: true,
                  showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`
                }}
                onChange={handleTableChange}
                scroll={{ x: 'max-content' }}
                size={(screens.xs ?? false) ? 'small' : 'middle'}
              />
            </Card>
          )}
        </Col>

        <Col xs={24} lg={6}>
          <Card
            title="Doctor's Queue"
            extra={<span style={{ fontSize: 12, fontWeight: 'normal' }}>Checked-in patients</span>}
            size="small"
            style={{ height: '100%' }}
          >
            <Badge count={queueCount} showZero overflowCount={99} style={{ marginBottom: 16 }} />
            <List
              size="small"
              dataSource={checkedInAppointments ?? []}
              locale={{ emptyText: 'No patients in queue' }}
              renderItem={(item: Appointment) => {
                const patient = patients.find(p => p.id === item.patient_id);
                return (
                  <List.Item style={{ padding: '8px 0' }}>
                    <List.Item.Meta
                      title={patient ? `${patient.first_name ?? ''} ${patient.last_name ?? ''}` : '—'}
                      description={`${item.appointment_time ?? '—'} • ${item.appointment_type ?? '—'}`}
                    />
                    <Tag color="orange">Waiting</Tag>
                  </List.Item>
                );
              }}
            />
          </Card>
        </Col>
      </Row>

      <Drawer
        title="Schedule New Appointment"
        width={(screens.xs ?? false) ? '100%' : 520}
        placement="right"
        open={newAppointmentDrawerVisible}
        onClose={handleCloseNewAppointmentDrawer}
        destroyOnClose
      >
        <Form form={appointmentForm} layout="vertical" requiredMark onFinish={handleSubmitNewAppointment}>
          <Form.Item name="patient_id" label="Patient" rules={[{ required: true, message: 'Please select a patient' }]}>
            <Select
              placeholder="Search and select patient..."
              showSearch
              filterOption
              optionFilterProp="label"
              options={patientOptions}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item name="department_id" label="Department">
            <Select
              placeholder="Select department"
              allowClear
              options={(departments ?? []).map(d => ({ label: d.name, value: d.id }))}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item name="doctor_id" label="Doctor" rules={[{ required: true, message: 'Please select a doctor' }]}>
            <Select
              placeholder="Select doctor (filtered by department)"
              showSearch
              optionFilterProp="label"
              options={doctorOptions}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="appointment_date" label="Appointment Date" rules={[{ required: true, message: 'Please select a date' }]}>
                <DatePicker
                  style={{ width: '100%' }}
                  disabledDate={current => current && current.isBefore(dayjs().startOf('day'))}
                  format="YYYY-MM-DD"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="appointment_time" label="Time Slot" rules={[{ required: true, message: 'Please select a time' }]}>
                <TimePicker style={{ width: '100%' }} format="HH:mm" minuteStep={15} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="duration_minutes" label="Duration (minutes)" initialValue={30}>
                <InputNumber min={15} max={240} step={15} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="appointment_type" label="Appointment Type" rules={[{ required: true, message: 'Please select appointment type' }]}>
                <Select
                  placeholder="Select type"
                  options={[
                    { label: 'New Consultation', value: 'CONSULTATION' },
                    { label: 'Follow-up', value: 'FOLLOW_UP' },
                    { label: 'Emergency', value: 'EMERGENCY' },
                    { label: 'Routine Checkup', value: 'ROUTINE_CHECKUP' },
                    { label: 'Procedure', value: 'PROCEDURE' }
                  ]}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="reason" label="Reason for Visit / Chief Complaint">
            <Input.TextArea placeholder="Enter reason for visit..." rows={3} maxLength={500} showCount />
          </Form.Item>

          <Form.Item name="notes" label="Internal Notes (Staff Only)">
            <Input.TextArea placeholder="Internal notes..." rows={2} maxLength={300} showCount />
          </Form.Item>

          <Row gutter={16} style={{ marginBottom: 16 }}>
            <Col span={12}>
              <Form.Item name="priority" label="Priority" initialValue="normal">
                <Radio.Group options={[{ label: 'Normal', value: 'normal' }, { label: 'Urgent', value: 'urgent' }]} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="send_confirmation" valuePropName="checked" initialValue={true} style={{ marginTop: 28 }}>
                <Checkbox>Send Confirmation to Patient</Checkbox>
              </Form.Item>
            </Col>
          </Row>

          <div
            style={{
              display: 'flex',
              justifyContent: 'flex-end',
              gap: 12,
              paddingTop: 16,
              borderTop: '1px solid #f0f0f0'
            }}
          >
            <Button onClick={handleCloseNewAppointmentDrawer}>Cancel</Button>
            <Button type="primary" htmlType="submit" icon={<CalendarOutlined />} loading={loading}>
              Schedule Appointment
            </Button>
          </div>
        </Form>
      </Drawer>

      <Modal
        title="Cancel Appointment"
        open={cancelModalVisible}
        onCancel={() => setCancelModalVisible(false)}
        onOk={handleConfirmCancelAppointment}
        okText="Confirm Cancellation"
        okButtonProps={{ danger: true }}
        destroyOnClose
      >
        <Form form={cancelForm} layout="vertical">
          <Form.Item name="cancel_reason" label="Reason for Cancellation" rules={[{ required: true, message: 'Please provide a reason' }]}>
            <Input.TextArea placeholder="Enter cancellation reason..." rows={3} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Reschedule Appointment"
        open={rescheduleModalVisible}
        onCancel={() => setRescheduleModalVisible(false)}
        onOk={handleSubmitReschedule}
        okText="Reschedule"
        destroyOnClose
      >
        <Form form={rescheduleForm} layout="vertical">
          <Form.Item name="appointment_date" label="New Date" rules={[{ required: true, message: 'Please select a new date' }]}>
            <DatePicker
              style={{ width: '100%' }}
              disabledDate={current => current && current.isBefore(dayjs().startOf('day'))}
            />
          </Form.Item>
          <Form.Item name="appointment_time" label="New Time" rules={[{ required: true, message: 'Please select a new time' }]}>
            <TimePicker style={{ width: '100%' }} format="HH:mm" minuteStep={15} />
          </Form.Item>
        </Form>
      </Modal>

      <Drawer
        title="Appointment Details"
        width={(screens.xs ?? false) ? '100%' : 480}
        placement="right"
        open={appointmentDetailPopoverVisible}
        onClose={handleCloseDetailPopover}
        destroyOnClose
      >
        {selectedAppointmentDetail && (
          <>
            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="Patient">
                {selectedAppointmentDetail.patient
                  ? `${selectedAppointmentDetail.patient.first_name ?? ''} ${selectedAppointmentDetail.patient.last_name ?? ''}`
                  : '—'}
              </Descriptions.Item>
              <Descriptions.Item label="Doctor">
                {selectedAppointmentDetail.doctor
                  ? `${selectedAppointmentDetail.doctor.first_name ?? ''} ${selectedAppointmentDetail.doctor.last_name ?? ''}`
                  : '—'}
              </Descriptions.Item>
              <Descriptions.Item label="Department">{selectedAppointmentDetail.department?.name ?? '—'}</Descriptions.Item>
              <Descriptions.Item label="Date">{selectedAppointmentDetail.appointment_date ?? '—'}</Descriptions.Item>
              <Descriptions.Item label="Time">{selectedAppointmentDetail.appointment_time ?? '—'}</Descriptions.Item>
              <Descriptions.Item label="Duration">{`${selectedAppointmentDetail.duration_minutes ?? 0} min`}</Descriptions.Item>
              <Descriptions.Item label="Type">{selectedAppointmentDetail.appointment_type ?? '—'}</Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={getStatusColor(selectedAppointmentDetail.status ?? '')}>{selectedAppointmentDetail.status ?? '—'}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Reason">{selectedAppointmentDetail.reason ?? '—'}</Descriptions.Item>
              <Descriptions.Item label="Notes">{selectedAppointmentDetail.notes ?? '—'}</Descriptions.Item>
            </Descriptions>
            <Space size="small" wrap style={{ marginTop: 16 }}>
              {selectedAppointmentDetail.status === 'SCHEDULED' && (
                <Button
                  type="primary"
                  icon={<CheckCircleOutlined />}
                  size="small"
                  onClick={() => handleCheckInAppointment(selectedAppointmentDetail.id)}
                >
                  Check-in
                </Button>
              )}
              {(selectedAppointmentDetail.status === 'SCHEDULED' || selectedAppointmentDetail.status === 'CONFIRMED') && (
                <>
                  <Button size="small" onClick={() => handleOpenRescheduleModal(selectedAppointmentDetail.id)}>
                    Reschedule
                  </Button>
                  <Button danger icon={<CloseCircleOutlined />} size="small" onClick={() => handleOpenCancelModal(selectedAppointmentDetail.id)}>
                    Cancel
                  </Button>
                </>
              )}
              {selectedAppointmentDetail.status === 'CHECKED_IN' && (
                <Button
                  type="primary"
                  ghost
                  icon={<CheckOutlined />}
                  size="small"
                  onClick={() => handleCompleteAppointment(selectedAppointmentDetail.id)}
                >
                  Complete
                </Button>
              )}
            </Space>
          </>
        )}
      </Drawer>
    </div>
  );
};

export default AppointmentsPage;