'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { 
  ArrowLeft, 
  Edit, 
  Users, 
  Phone, 
  Mail, 
  Calendar,
  MapPin,
  User,
  Pill,
  Camera,
  Eye,
  Trash2,
  CreditCard,
  AlertCircle,
  ExternalLink,
  DollarSign,
  Clock,
  Glasses,
  Scissors,
  Activity,
  Scan,
  Target,
  Plus,
  ChevronRight,
  FileText
} from 'lucide-react';
import ProtectedRoute from '../../protected-route';
import SidebarLayout from '../../components/sidebar-layout';
import { useTranslations } from '@/app/hooks/useTranslations';
import { useFormatCurrency } from '@/app/hooks/useFormatCurrency';

export default function PatientViewPage() {
  const { t } = useTranslations();
  const formatCurrency = useFormatCurrency();
  const params = useParams();
  const router = useRouter();
  const [patient, setPatient] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [activeTab, setActiveTab] = useState('details');
  
  // Eye clinic specific states
  const [eyeExams, setEyeExams] = useState<any[]>([]);
  const [prescriptions, setPrescriptions] = useState<any[]>([]);
  const [glaucomaRecords, setGlaucomaRecords] = useState<any[]>([]);
  const [drRecords, setDrRecords] = useState<any[]>([]);
  const [surgeries, setSurgeries] = useState<any[]>([]);
  const [octScans, setOctScans] = useState<any[]>([]);
  const [fundusPhotos, setFundusPhotos] = useState<any[]>([]);
  const [appointments, setAppointments] = useState<any[]>([]);
  const [invoices, setInvoices] = useState<any[]>([]);
  
  const [loadingData, setLoadingData] = useState(true);

  useEffect(() => {
    const fetchPatient = async () => {
      try {
        const response = await fetch(`/api/patients/${params.id}`);
        if (response.ok) {
          const data = await response.json();
          setPatient(data);
        } else {
          setError(t('patients.detailPage.patientNotFound'));
        }
      } catch (error) {
        console.error('Error fetching patient:', error);
        setError(t('patients.detailPage.patientNotFound'));
      } finally {
        setLoading(false);
      }
    };

    if (params.id) {
      fetchPatient();
    }
  }, [params.id]);

  // Fetch all eye clinic data
  useEffect(() => {
    const fetchEyeClinicData = async () => {
      if (!params.id) return;
      
      setLoadingData(true);
      try {
        const [
          examsRes,
          rxRes,
          glaucomaRes,
          drRes,
          surgeryRes,
          octRes,
          fundusRes,
          appointmentsRes,
          invoicesRes
        ] = await Promise.all([
          fetch(`/api/eye-exam?patientId=${params.id}`).catch(() => null),
          fetch(`/api/prescriptions?patientId=${params.id}`).catch(() => null),
          fetch(`/api/glaucoma?patientId=${params.id}`).catch(() => null),
          fetch(`/api/dr-screening?patientId=${params.id}`).catch(() => null),
          fetch(`/api/surgery?patientId=${params.id}`).catch(() => null),
          fetch(`/api/imaging/oct?patientId=${params.id}`).catch(() => null),
          fetch(`/api/imaging/fundus?patientId=${params.id}`).catch(() => null),
          fetch(`/api/appointments?patientId=${params.id}`).catch(() => null),
          fetch(`/api/billing/invoices?patientId=${params.id}`).catch(() => null)
        ]);

        if (examsRes?.ok) {
          const data = await examsRes.json();
          setEyeExams(data.examinations || []);
        }
        if (rxRes?.ok) {
          const data = await rxRes.json();
          setPrescriptions(data.prescriptions || []);
        }
        if (glaucomaRes?.ok) {
          const data = await glaucomaRes.json();
          setGlaucomaRecords(data.records || []);
        }
        if (drRes?.ok) {
          const data = await drRes.json();
          setDrRecords(data.records || []);
        }
        if (surgeryRes?.ok) {
          const data = await surgeryRes.json();
          setSurgeries(data.surgeries || []);
        }
        if (octRes?.ok) {
          const data = await octRes.json();
          setOctScans(data.scans || []);
        }
        if (fundusRes?.ok) {
          const data = await fundusRes.json();
          setFundusPhotos(data.photos || []);
        }
        if (appointmentsRes?.ok) {
          const data = await appointmentsRes.json();
          setAppointments(Array.isArray(data) ? data : data.appointments || []);
        }
        if (invoicesRes?.ok) {
          const data = await invoicesRes.json();
          setInvoices(data.invoices || []);
        }
      } catch (error) {
        console.error('Error fetching eye clinic data:', error);
      } finally {
        setLoadingData(false);
      }
    };

    if (params.id) {
      fetchEyeClinicData();
    }
  }, [params.id]);

  if (loading) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('patients.detailPage.title')} description={t('patients.detailPage.description')}>
          <div className="flex items-center justify-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-teal-600"></div>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  if (error || !patient) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('patients.detailPage.patientNotFound')} description={t('patients.detailPage.patientNotFoundDesc')}>
          <div className="text-center py-12">
            <Users className="mx-auto h-12 w-12 text-gray-400" />
            <h3 className="mt-2 text-sm font-medium text-gray-900">{t('patients.detailPage.patientNotFound')}</h3>
            <div className="mt-6">
              <Link href="/patients" className="inline-flex items-center space-x-2 bg-teal-600 text-white px-4 py-2 rounded-lg hover:bg-teal-700">
                <ArrowLeft className="h-4 w-4" />
                <span>{t('patients.detailPage.backToPatients')}</span>
              </Link>
            </div>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  const getStatusColor = (status: string) => {
    switch (status?.toLowerCase()) {
      case 'confirmed': case 'completed': case 'issued':
        return 'bg-green-100 text-green-800';
      case 'pending': case 'scheduled':
        return 'bg-yellow-100 text-yellow-800';
      case 'cancelled': case 'expired':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const tabs = [
    { id: 'details', label: t('patients.detailPage.tabs.patientInfo'), icon: User },
    { id: 'eye-exams', label: t('patients.detailPage.tabs.eyeExams'), icon: Eye, count: eyeExams.length },
    { id: 'prescriptions', label: t('patients.detailPage.tabs.opticalRx'), icon: Glasses, count: prescriptions.length },
    { id: 'glaucoma', label: t('patients.detailPage.tabs.glaucoma'), icon: Activity, count: glaucomaRecords.length },
    { id: 'dr-screening', label: t('patients.detailPage.tabs.drScreening'), icon: Target, count: drRecords.length },
    { id: 'surgeries', label: t('patients.detailPage.tabs.surgeries'), icon: Scissors, count: surgeries.length },
    { id: 'imaging', label: t('patients.detailPage.tabs.imaging'), icon: Scan, count: octScans.length + fundusPhotos.length },
    { id: 'appointments', label: t('patients.detailPage.tabs.appointments'), icon: Calendar, count: appointments.length },
    { id: 'billing', label: t('patients.detailPage.tabs.billing'), icon: CreditCard, count: invoices.length },
  ];

  return (
    <ProtectedRoute>
      <SidebarLayout title={t('patients.detailPage.title')} description={t('patients.detailPage.description')}>
        <div className="max-w-7xl mx-auto">
          {/* Header */}
          <div className="mb-6">
            <Link href="/patients" className="inline-flex items-center text-sm text-teal-600 hover:text-teal-800 mb-4">
              <ArrowLeft className="h-4 w-4 mr-2" />
              {t('patients.detailPage.backToPatients')}
            </Link>
            <div className="flex justify-between items-center">
              <div>
                <h1 className="text-2xl font-bold text-gray-900">{patient.name}</h1>
                <p className="text-sm text-gray-500">ID: {patient.patientId || patient._id}</p>
              </div>
              <div className="flex gap-3">
                <Link
                  href={`/eye-exam/new?patientId=${patient._id}`}
                  className="inline-flex items-center gap-2 px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700"
                >
                  <Plus className="h-4 w-4" />
                  {t('patients.detailPage.newEyeExam')}
                </Link>
                <Link
                  href={`/patients/${patient._id}/edit`}
                  className="inline-flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
                >
                  <Edit className="h-4 w-4" />
                  {t('patients.detailPage.edit')}
                </Link>
              </div>
            </div>
          </div>

          {/* Main Content */}
          <div className="flex gap-6">
            {/* Vertical Tabs */}
            <div className="w-56 flex-shrink-0">
              <div className="bg-white rounded-xl shadow-sm sticky top-6">
                <nav className="p-2">
                  {tabs.map((tab) => {
                    const Icon = tab.icon;
                    return (
                      <button
                        key={tab.id}
                        onClick={() => setActiveTab(tab.id)}
                        className={`w-full py-3 px-4 mb-1 rounded-lg font-medium text-sm flex items-center justify-between transition-colors ${
                          activeTab === tab.id
                            ? 'bg-teal-50 text-teal-700 border-l-4 border-teal-600'
                            : 'text-gray-600 hover:bg-gray-50'
                        }`}
                      >
                        <div className="flex items-center gap-3">
                          <Icon className="h-5 w-5" />
                          <span>{tab.label}</span>
                        </div>
                        {tab.count !== undefined && tab.count > 0 && (
                          <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${
                            activeTab === tab.id ? 'bg-teal-100 text-teal-700' : 'bg-gray-200 text-gray-600'
                          }`}>
                            {tab.count}
                          </span>
                        )}
                      </button>
                    );
                  })}
                </nav>
              </div>
            </div>

            {/* Tab Content */}
            <div className="flex-1">
              <div className="bg-white rounded-xl shadow-sm">
                {/* Patient Details Tab */}
                {activeTab === 'details' && (
                  <div className="p-6 space-y-6">
                    <div>
                      <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('patients.detailPage.personalInformation')}</h2>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div className="space-y-4">
                          <div className="flex items-center gap-3">
                            <User className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="text-sm text-gray-500">{t('patients.detailPage.fullName')}</p>
                              <p className="font-medium">{patient.name}</p>
                            </div>
                          </div>
                          <div className="flex items-center gap-3">
                            <Mail className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="text-sm text-gray-500">{t('patients.detailPage.email')}</p>
                              <p className="font-medium">{patient.email || t('patients.detailPage.notSpecified')}</p>
                            </div>
                          </div>
                          <div className="flex items-center gap-3">
                            <Phone className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="text-sm text-gray-500">{t('patients.detailPage.phone')}</p>
                              <p className="font-medium">{patient.phone || t('patients.detailPage.notSpecified')}</p>
                            </div>
                          </div>
                          <div className="flex items-center gap-3">
                            <Calendar className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="text-sm text-gray-500">{t('patients.detailPage.dateOfBirth')}</p>
                              <p className="font-medium">
                                {patient.dateOfBirth ? new Date(patient.dateOfBirth).toLocaleDateString() : t('patients.detailPage.notSpecified')}
                              </p>
                            </div>
                          </div>
                        </div>
                        <div className="space-y-4">
                          <div className="flex items-center gap-3">
                            <MapPin className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="text-sm text-gray-500">{t('patients.detailPage.address')}</p>
                              <p className="font-medium">{patient.address || t('patients.detailPage.notSpecified')}</p>
                            </div>
                          </div>
                          <div className="flex items-center gap-3">
                            <Users className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="text-sm text-gray-500">{t('patients.detailPage.assignedDoctor')}</p>
                              <p className="font-medium">{patient.assignedDoctor || t('patients.detailPage.notAssigned')}</p>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* Ocular History Summary */}
                    <div className="border-t pt-6">
                      <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('patients.detailPage.ocularHistorySummary')}</h2>
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div className="bg-teal-50 rounded-lg p-4">
                          <Eye className="h-6 w-6 text-teal-600 mb-2" />
                          <p className="text-2xl font-bold text-teal-900">{eyeExams.length}</p>
                          <p className="text-sm text-teal-600">{t('patients.detailPage.eyeExams')}</p>
                        </div>
                        <div className="bg-blue-50 rounded-lg p-4">
                          <Glasses className="h-6 w-6 text-blue-600 mb-2" />
                          <p className="text-2xl font-bold text-blue-900">{prescriptions.length}</p>
                          <p className="text-sm text-blue-600">{t('patients.detailPage.prescriptions')}</p>
                        </div>
                        <div className="bg-purple-50 rounded-lg p-4">
                          <Scissors className="h-6 w-6 text-purple-600 mb-2" />
                          <p className="text-2xl font-bold text-purple-900">{surgeries.length}</p>
                          <p className="text-sm text-purple-600">{t('patients.detailPage.surgeries')}</p>
                        </div>
                        <div className="bg-amber-50 rounded-lg p-4">
                          <Scan className="h-6 w-6 text-amber-600 mb-2" />
                          <p className="text-2xl font-bold text-amber-900">{octScans.length + fundusPhotos.length}</p>
                          <p className="text-sm text-amber-600">{t('patients.detailPage.imaging')}</p>
                        </div>
                      </div>
                    </div>

                    {patient.medicalHistory && (
                      <div className="border-t pt-6">
                        <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('patients.detailPage.medicalHistory')}</h2>
                        <p className="text-gray-700">{patient.medicalHistory}</p>
                      </div>
                    )}

                    {patient.emergencyContact && (
                      <div className="border-t pt-6">
                        <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('patients.detailPage.emergencyContact')}</h2>
                        <div className="grid grid-cols-3 gap-4">
                          <div>
                            <p className="text-sm text-gray-500">{t('patients.detailPage.name')}</p>
                            <p className="font-medium">{patient.emergencyContact.name}</p>
                          </div>
                          <div>
                            <p className="text-sm text-gray-500">{t('patients.detailPage.relationship')}</p>
                            <p className="font-medium">{patient.emergencyContact.relationship}</p>
                          </div>
                          <div>
                            <p className="text-sm text-gray-500">{t('patients.detailPage.phone')}</p>
                            <p className="font-medium">{patient.emergencyContact.phone}</p>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Eye Exams Tab */}
                {activeTab === 'eye-exams' && (
                  <div className="p-6">
                    <div className="flex justify-between items-center mb-4">
                      <h2 className="text-lg font-semibold text-gray-900">{t('patients.detailPage.eyeExaminations')}</h2>
                      <Link href={`/eye-exam/new?patientId=${patient._id}`} className="text-teal-600 hover:text-teal-700 text-sm font-medium flex items-center gap-1">
                        <Plus className="h-4 w-4" /> {t('patients.detailPage.newExam')}
                      </Link>
                    </div>
                    {loadingData ? (
                      <div className="flex justify-center py-8"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div></div>
                    ) : eyeExams.length === 0 ? (
                      <div className="text-center py-12">
                        <Eye className="mx-auto h-12 w-12 text-gray-300" />
                        <p className="mt-2 text-gray-500">{t('patients.detailPage.noEyeExaminations')}</p>
                        <Link href={`/eye-exam/new?patientId=${patient._id}`} className="text-teal-600 hover:text-teal-700 mt-2 inline-block">{t('patients.detailPage.createFirstExam')}</Link>
                      </div>
                    ) : (
                      <div className="space-y-3">
                        {eyeExams.map((exam: any) => (
                          <Link key={exam._id} href={`/eye-exam/${exam._id}`} className="block p-4 border rounded-lg hover:bg-gray-50">
                            <div className="flex justify-between items-start">
                              <div>
                                <p className="font-medium text-gray-900">{exam.chiefComplaint || t('patients.detailPage.eyeExamination')}</p>
                                <p className="text-sm text-gray-500">{new Date(exam.examDate).toLocaleDateString()}</p>
                                {exam.visualAcuity && (
                                  <p className="text-sm text-gray-600 mt-1">
                                    VA: OD {exam.visualAcuity.corrected?.distance?.OD || '-'} | OS {exam.visualAcuity.corrected?.distance?.OS || '-'}
                                  </p>
                                )}
                              </div>
                              <ChevronRight className="h-5 w-5 text-gray-400" />
                            </div>
                          </Link>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {/* Prescriptions Tab */}
                {activeTab === 'prescriptions' && (
                  <div className="p-6">
                    <div className="flex justify-between items-center mb-4">
                      <h2 className="text-lg font-semibold text-gray-900">{t('patients.detailPage.opticalPrescriptions')}</h2>
                      <Link href={`/prescriptions/new?patientId=${patient._id}`} className="text-teal-600 hover:text-teal-700 text-sm font-medium flex items-center gap-1">
                        <Plus className="h-4 w-4" /> {t('patients.detailPage.newRx')}
                      </Link>
                    </div>
                    {loadingData ? (
                      <div className="flex justify-center py-8"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div></div>
                    ) : prescriptions.length === 0 ? (
                      <div className="text-center py-12">
                        <Glasses className="mx-auto h-12 w-12 text-gray-300" />
                        <p className="mt-2 text-gray-500">{t('patients.detailPage.noPrescriptions')}</p>
                      </div>
                    ) : (
                      <div className="overflow-x-auto">
                        <table className="min-w-full divide-y divide-gray-200">
                          <thead className="bg-gray-50">
                            <tr>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.date')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.type')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.od')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.os')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.status')}</th>
                              <th className="px-4 py-3"></th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-gray-200">
                            {prescriptions.map((rx: any) => (
                              <tr key={rx._id} className="hover:bg-gray-50">
                                <td className="px-4 py-3 text-sm">{new Date(rx.prescriptionDate).toLocaleDateString()}</td>
                                <td className="px-4 py-3 text-sm capitalize">{rx.prescriptionType?.replace('_', ' ')}</td>
                                <td className="px-4 py-3 text-sm font-mono">
                                  {rx.rightEye?.sphere >= 0 ? '+' : ''}{rx.rightEye?.sphere?.toFixed(2)} / {rx.rightEye?.cylinder?.toFixed(2)}
                                </td>
                                <td className="px-4 py-3 text-sm font-mono">
                                  {rx.leftEye?.sphere >= 0 ? '+' : ''}{rx.leftEye?.sphere?.toFixed(2)} / {rx.leftEye?.cylinder?.toFixed(2)}
                                </td>
                                <td className="px-4 py-3">
                                  <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(rx.status)}`}>
                                    {rx.status}
                                  </span>
                                </td>
                                <td className="px-4 py-3">
                                  <Link href={`/prescriptions/${rx._id}`} className="text-teal-600 hover:text-teal-700 text-sm">{t('patients.detailPage.view')}</Link>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </div>
                )}

                {/* Glaucoma Tab */}
                {activeTab === 'glaucoma' && (
                  <div className="p-6">
                    <div className="flex justify-between items-center mb-4">
                      <h2 className="text-lg font-semibold text-gray-900">{t('patients.detailPage.glaucomaRecords')}</h2>
                      <Link href={`/glaucoma/new?patientId=${patient._id}`} className="text-teal-600 hover:text-teal-700 text-sm font-medium flex items-center gap-1">
                        <Plus className="h-4 w-4" /> {t('patients.detailPage.addRecord')}
                      </Link>
                    </div>
                    {loadingData ? (
                      <div className="flex justify-center py-8"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div></div>
                    ) : glaucomaRecords.length === 0 ? (
                      <div className="text-center py-12">
                        <Activity className="mx-auto h-12 w-12 text-gray-300" />
                        <p className="mt-2 text-gray-500">{t('patients.detailPage.noGlaucomaRecords')}</p>
                      </div>
                    ) : (
                      <div className="space-y-3">
                        {glaucomaRecords.map((record: any) => (
                          <Link key={record._id} href={`/glaucoma/${record._id}`} className="block p-4 border rounded-lg hover:bg-gray-50">
                            <div className="flex justify-between">
                              <div>
                                <p className="font-medium text-gray-900 uppercase">{record.glaucomaType}</p>
                                <p className="text-sm text-gray-500">{t('patients.detailPage.targetIOP')}: OD ≤{record.targetIOP?.OD} | OS ≤{record.targetIOP?.OS}</p>
                                {record.iopHistory && record.iopHistory.length > 0 && (
                                  <p className="text-sm text-gray-600 mt-1">
                                    {t('patients.detailPage.lastIOP')}: OD {record.iopHistory[record.iopHistory.length - 1]?.OD} | OS {record.iopHistory[record.iopHistory.length - 1]?.OS}
                                  </p>
                                )}
                              </div>
                              <span className={`px-2 py-1 h-fit rounded-full text-xs font-medium ${
                                record.progressionAnalysis?.iopControl === 'controlled' ? 'bg-green-100 text-green-700' :
                                record.progressionAnalysis?.iopControl === 'uncontrolled' ? 'bg-red-100 text-red-700' :
                                'bg-gray-100 text-gray-700'
                              }`}>
                                {record.progressionAnalysis?.iopControl || record.severity}
                              </span>
                            </div>
                          </Link>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {/* DR Screening Tab */}
                {activeTab === 'dr-screening' && (
                  <div className="p-6">
                    <div className="flex justify-between items-center mb-4">
                      <h2 className="text-lg font-semibold text-gray-900">{t('patients.detailPage.diabeticRetinopathyScreening')}</h2>
                      <Link href={`/dr-screening/new?patientId=${patient._id}`} className="text-teal-600 hover:text-teal-700 text-sm font-medium flex items-center gap-1">
                        <Plus className="h-4 w-4" /> {t('patients.detailPage.newScreening')}
                      </Link>
                    </div>
                    {loadingData ? (
                      <div className="flex justify-center py-8"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div></div>
                    ) : drRecords.length === 0 ? (
                      <div className="text-center py-12">
                        <Target className="mx-auto h-12 w-12 text-gray-300" />
                        <p className="mt-2 text-gray-500">{t('patients.detailPage.noDRScreeningRecords')}</p>
                      </div>
                    ) : (
                      <div className="space-y-3">
                        {drRecords.map((record: any) => (
                          <Link key={record._id} href={`/dr-screening/${record._id}`} className="block p-4 border rounded-lg hover:bg-gray-50">
                            <div className="flex justify-between">
                              <div>
                                <p className="font-medium text-gray-900">{t('patients.detailPage.type')} {record.diabetesType} - {record.diabetesDuration} {t('patients.detailPage.years')}</p>
                                <p className="text-sm text-gray-500">HbA1c: {record.metabolicControl?.hba1c}%</p>
                                <div className="flex gap-4 mt-1 text-sm">
                                  <span>OD: {record.currentStatus?.OD?.drLevel?.replace('_', ' ')}</span>
                                  <span>OS: {record.currentStatus?.OS?.drLevel?.replace('_', ' ')}</span>
                                </div>
                              </div>
                              <ChevronRight className="h-5 w-5 text-gray-400" />
                            </div>
                          </Link>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {/* Surgeries Tab */}
                {activeTab === 'surgeries' && (
                  <div className="p-6">
                    <div className="flex justify-between items-center mb-4">
                      <h2 className="text-lg font-semibold text-gray-900">{t('patients.detailPage.eyeSurgeries')}</h2>
                      <Link href={`/surgery/new?patientId=${patient._id}`} className="text-teal-600 hover:text-teal-700 text-sm font-medium flex items-center gap-1">
                        <Plus className="h-4 w-4" /> {t('patients.detailPage.scheduleSurgery')}
                      </Link>
                    </div>
                    {loadingData ? (
                      <div className="flex justify-center py-8"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div></div>
                    ) : surgeries.length === 0 ? (
                      <div className="text-center py-12">
                        <Scissors className="mx-auto h-12 w-12 text-gray-300" />
                        <p className="mt-2 text-gray-500">{t('patients.detailPage.noSurgeriesRecorded')}</p>
                      </div>
                    ) : (
                      <div className="overflow-x-auto">
                        <table className="min-w-full divide-y divide-gray-200">
                          <thead className="bg-gray-50">
                            <tr>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.date')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.type')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.eye')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.procedure')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.status')}</th>
                              <th className="px-4 py-3"></th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-gray-200">
                            {surgeries.map((surgery: any) => (
                              <tr key={surgery._id} className="hover:bg-gray-50">
                                <td className="px-4 py-3 text-sm">{new Date(surgery.surgeryDate).toLocaleDateString()}</td>
                                <td className="px-4 py-3 text-sm capitalize">{surgery.surgeryType}</td>
                                <td className="px-4 py-3 text-sm font-medium">{surgery.eye}</td>
                                <td className="px-4 py-3 text-sm">{surgery.procedure}</td>
                                <td className="px-4 py-3">
                                  <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(surgery.status)}`}>
                                    {surgery.status}
                                  </span>
                                </td>
                                <td className="px-4 py-3">
                                  <Link href={`/surgery/${surgery._id}`} className="text-teal-600 hover:text-teal-700 text-sm">{t('patients.detailPage.view')}</Link>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </div>
                )}

                {/* Imaging Tab */}
                {activeTab === 'imaging' && (
                  <div className="p-6">
                    <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('patients.detailPage.ocularImaging')}</h2>
                    {loadingData ? (
                      <div className="flex justify-center py-8"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div></div>
                    ) : (
                      <div className="space-y-6">
                        {/* OCT Scans */}
                        <div>
                          <div className="flex justify-between items-center mb-3">
                            <h3 className="font-medium text-gray-700 flex items-center gap-2">
                              <Scan className="h-4 w-4" /> {t('patients.detailPage.octScans')} ({octScans.length})
                            </h3>
                            <Link href={`/imaging/oct/new?patientId=${patient._id}`} className="text-teal-600 text-sm">+ {t('patients.detailPage.add')}</Link>
                          </div>
                          {octScans.length === 0 ? (
                            <p className="text-sm text-gray-500">{t('patients.detailPage.noOCTScans')}</p>
                          ) : (
                            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                              {octScans.slice(0, 4).map((scan: any) => (
                                <Link key={scan._id} href={`/imaging/oct/${scan._id}`} className="p-3 border rounded-lg hover:bg-gray-50">
                                  <p className="text-sm font-medium">{scan.eye} - {scan.scanType}</p>
                                  <p className="text-xs text-gray-500">{new Date(scan.scanDate).toLocaleDateString()}</p>
                                </Link>
                              ))}
                            </div>
                          )}
                        </div>

                        {/* Fundus Photos */}
                        <div>
                          <div className="flex justify-between items-center mb-3">
                            <h3 className="font-medium text-gray-700 flex items-center gap-2">
                              <Camera className="h-4 w-4" /> {t('patients.detailPage.fundusPhotos')} ({fundusPhotos.length})
                            </h3>
                            <Link href={`/imaging/fundus/new?patientId=${patient._id}`} className="text-teal-600 text-sm">+ {t('patients.detailPage.add')}</Link>
                          </div>
                          {fundusPhotos.length === 0 ? (
                            <p className="text-sm text-gray-500">{t('patients.detailPage.noFundusPhotos')}</p>
                          ) : (
                            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                              {fundusPhotos.slice(0, 4).map((photo: any) => (
                                <Link key={photo._id} href={`/imaging/fundus/${photo._id}`} className="p-3 border rounded-lg hover:bg-gray-50">
                                  <p className="text-sm font-medium">{photo.eye} - {photo.imageType}</p>
                                  <p className="text-xs text-gray-500">{new Date(photo.captureDate).toLocaleDateString()}</p>
                                </Link>
                              ))}
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Appointments Tab */}
                {activeTab === 'appointments' && (
                  <div className="p-6">
                    <div className="flex justify-between items-center mb-4">
                      <h2 className="text-lg font-semibold text-gray-900">{t('patients.detailPage.appointments')}</h2>
                      <Link href={`/appointments/new?patientId=${patient._id}`} className="text-teal-600 hover:text-teal-700 text-sm font-medium flex items-center gap-1">
                        <Plus className="h-4 w-4" /> {t('patients.detailPage.newAppointment')}
                      </Link>
                    </div>
                    {loadingData ? (
                      <div className="flex justify-center py-8"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div></div>
                    ) : appointments.length === 0 ? (
                      <div className="text-center py-12">
                        <Calendar className="mx-auto h-12 w-12 text-gray-300" />
                        <p className="mt-2 text-gray-500">{t('patients.detailPage.noAppointmentsFound')}</p>
                      </div>
                    ) : (
                      <div className="overflow-x-auto">
                        <table className="min-w-full divide-y divide-gray-200">
                          <thead className="bg-gray-50">
                            <tr>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.date')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.time')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.doctor')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.type')}</th>
                              <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.status')}</th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-gray-200">
                            {appointments.map((apt: any) => (
                              <tr key={apt._id} className="hover:bg-gray-50">
                                <td className="px-4 py-3 text-sm">{apt.appointmentDate ? new Date(apt.appointmentDate).toLocaleDateString() : '-'}</td>
                                <td className="px-4 py-3 text-sm">{apt.appointmentTime || '-'}</td>
                                <td className="px-4 py-3 text-sm">{apt.doctorName || '-'}</td>
                                <td className="px-4 py-3 text-sm">{apt.appointmentType || '-'}</td>
                                <td className="px-4 py-3">
                                  <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(apt.status)}`}>
                                    {apt.status}
                                  </span>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </div>
                )}

                {/* Billing Tab */}
                {activeTab === 'billing' && (
                  <div className="p-6">
                    <div className="flex justify-between items-center mb-4">
                      <h2 className="text-lg font-semibold text-gray-900">{t('patients.detailPage.billingInvoices')}</h2>
                      <Link href="/billing" className="text-teal-600 hover:text-teal-700 text-sm font-medium flex items-center gap-1">
                        <ExternalLink className="h-4 w-4" /> {t('patients.detailPage.viewAll')}
                      </Link>
                    </div>
                    {loadingData ? (
                      <div className="flex justify-center py-8"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div></div>
                    ) : invoices.length === 0 ? (
                      <div className="text-center py-12">
                        <CreditCard className="mx-auto h-12 w-12 text-gray-300" />
                        <p className="mt-2 text-gray-500">{t('patients.detailPage.noInvoicesFound')}</p>
                      </div>
                    ) : (
                      <>
                        <div className="grid grid-cols-3 gap-4 mb-6">
                          <div className="bg-blue-50 rounded-lg p-4">
                            <p className="text-sm text-blue-600">{t('patients.detailPage.totalBilled')}</p>
                            <p className="text-2xl font-bold text-blue-900">
                              {formatCurrency(invoices.reduce((sum: number, inv: any) => sum + (inv.total || 0), 0))}
                            </p>
                          </div>
                          <div className="bg-green-50 rounded-lg p-4">
                            <p className="text-sm text-green-600">{t('patients.detailPage.paid')}</p>
                            <p className="text-2xl font-bold text-green-900">
                              {formatCurrency(invoices.filter((inv: any) => inv.status === 'paid').reduce((sum: number, inv: any) => sum + (inv.total || 0), 0))}
                            </p>
                          </div>
                          <div className="bg-amber-50 rounded-lg p-4">
                            <p className="text-sm text-amber-600">{t('patients.detailPage.pending')}</p>
                            <p className="text-2xl font-bold text-amber-900">
                              {formatCurrency(invoices.filter((inv: any) => inv.status === 'pending').reduce((sum: number, inv: any) => sum + (inv.total || 0), 0))}
                            </p>
                          </div>
                        </div>
                        <div className="overflow-x-auto">
                          <table className="min-w-full divide-y divide-gray-200">
                            <thead className="bg-gray-50">
                              <tr>
                                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.invoiceNumber')}</th>
                                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.date')}</th>
                                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.total')}</th>
                                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('patients.detailPage.status')}</th>
                                <th className="px-4 py-3"></th>
                              </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-200">
                              {invoices.map((inv: any) => (
                                <tr key={inv._id} className="hover:bg-gray-50">
                                  <td className="px-4 py-3 text-sm font-medium">{inv.invoiceNumber}</td>
                                  <td className="px-4 py-3 text-sm">{inv.createdAt ? new Date(inv.createdAt).toLocaleDateString() : '-'}</td>
                                  <td className="px-4 py-3 text-sm font-semibold">{formatCurrency(inv.total ?? 0)}</td>
                                  <td className="px-4 py-3">
                                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(inv.status)}`}>
                                      {inv.status}
                                    </span>
                                  </td>
                                  <td className="px-4 py-3">
                                    <Link href={`/billing/invoices/${inv._id}`} className="text-teal-600 hover:text-teal-700 text-sm">{t('patients.detailPage.view')}</Link>
                                  </td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      </>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
