'use client'

import PaginationControls from '@/components/common/PaginationControls';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { api, http } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { buildOdontogramHtml, formatGenderForPrint, getDoctorPrintData, printRecord } from '@/lib/print-service';
import { toReachableAbsoluteUrl } from '@/lib/url-utils';
import { ChevronLeft, ChevronRight, Edit, Eye, Printer, Trash2 } from 'lucide-react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import PrescriptionForm from '../Prescription/PrescriptionForm';
import ClinicalRecordForm from './ClinicalRecordForm';
import DentalRecordForm from './DentalRecordForm';
import InteractiveOdontogram, { ToothState } from './InteractiveOdontogram';
import PatientForm from './PatientForm';
// import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"

interface PatientData {
    _id: string;
    userId: {
        _id: string;
        firstName: string;
        lastName: string;
        email: string;
        phone?: string;
    };
    gender?: string;
    dateOfBirth?: string;
    address?: string;
    medicalHistory?: string;
    vitalSigns?: any[];
    testResults?: any[];
    diagnoses?: any[];
    clinicalRecords?: any[];
    dentalRecords?: any[];
    documents?: any[];
    [key: string]: any;
}

interface TestResultItem {
    _id?: string;
    date: string;
    type: string;
    name: string;
    result: string;
    fileUrl?: string;
    notes?: string;
}

interface DocumentItem {
    _id?: string;
    date: string;
    name: string;
    type: string;
    url: string;
    category?: string;
}

export default function PatientDetails({ patient: initialPatient }: { patient: PatientData }) {
    const { t, language } = useLanguage();
    const { user } = useAuthStore();
    const router = useRouter();
    const searchParams = useSearchParams();
    const activeTab = searchParams.get('tab') || 'overview';
    const [patient, setPatient] = useState<PatientData>(initialPatient);
    const [prescriptions, setPrescriptions] = useState<any[]>([]);
    const [prescriptionPage, setPrescriptionPage] = useState(1);
    const [openClinicalForm, setOpenClinicalForm] = useState(false);
    const [openDentalForm, setOpenDentalForm] = useState(false);
    const [chartRecordIndex, setChartRecordIndex] = useState(0); // which dental record to show in the chart tab
    const [openEditProfile, setOpenEditProfile] = useState(false);
    const [openPrescriptionNew, setOpenPrescriptionNew] = useState(false);
    const [newDocumentType, setNewDocumentType] = useState<string | undefined>(undefined);
    const [viewPrescription, setViewPrescription] = useState<any>(null);
    const [editPrescription, setEditPrescription] = useState<any>(null);
    const [selectedRecord, setSelectedRecord] = useState<any>(null);
    const [formMode, setFormMode] = useState<'view' | 'edit' | 'new'>('new');
    const [openAddExam, setOpenAddExam] = useState(false);
    const [openAddDocument, setOpenAddDocument] = useState(false);
    const [editingExamId, setEditingExamId] = useState<string | null>(null);
    const [editingDocumentId, setEditingDocumentId] = useState<string | null>(null);
    const [savingExam, setSavingExam] = useState(false);
    const [savingDocument, setSavingDocument] = useState(false);
    const [examFile, setExamFile] = useState<File | null>(null);
    const [documentFile, setDocumentFile] = useState<File | null>(null);
    const [examForm, setExamForm] = useState<TestResultItem>({
        date: new Date().toISOString().split('T')[0],
        type: '',
        name: '',
        result: '',
        notes: '',
    });
    const [documentForm, setDocumentForm] = useState<DocumentItem>({
        date: new Date().toISOString().split('T')[0],
        name: '',
        type: '',
        url: '',
        category: '',
    });
    const prescriptionsPerPage = 10;

    const isDentist = user?.isDentist === true || user?.userType === 'dentist';
    const isEditingExam = Boolean(editingExamId);
    const isEditingDocument = Boolean(editingDocumentId);
    const printLabels = {
        patient: t('common.patient'),
        phone: t('common.phone'),
        gender: t('common.gender'),
        dob: t('common.dob'),
        id: t('common.id'),
        insurance: t('patients.insurance'),
        doctor: t('common.doctor'),
        licenseNumber: t('common.licenseNumber'),
    };

    const getLocalizedGender = (gender?: string) => {
        if (!gender) return t('common.na');
        const normalized = gender.trim().toLowerCase();
        if (normalized === 'male') return t('common.male');
        if (normalized === 'female') return t('common.female');
        if (normalized === 'other') return t('common.other');
        return gender;
    };

    const getAbsoluteFileUrl = (value?: string) => {
        return toReachableAbsoluteUrl(value, API_BASE_URL);
    };

    const refreshPatient = async () => {
        try {
            const res = await api.patients.getById(patient._id);
            if (res.success && res.data) setPatient(res.data);
        } catch (e) {
            console.error('Failed to refresh patient:', e);
        }
    };

    const handleViewRecord = (record: any) => {
        setSelectedRecord(record);
        setFormMode('view');
        setOpenClinicalForm(true);
    };

    const handleEditRecord = (record: any) => {
        setSelectedRecord(record);
        setFormMode('edit');
        setOpenClinicalForm(true);
    };

    const handlePrintRecord = (record: any) => {
        const { doctor, clinic } = getDoctorPrintData(record, user, {
            doctor: t('common.doctor'),
        });
        const getRecordFieldLabel = (key: string) => {
            const normalizedKey = String(key || '').trim();
            const camelLikeKey = normalizedKey
                .replace(/[_-\s]+(.)/g, (_, c: string) => c.toUpperCase())
                .replace(/^[A-Z]/, (c) => c.toLowerCase());
            const lookupKeys = [normalizedKey, camelLikeKey];

            for (const lookupKey of lookupKeys) {
                const translated = t(`clinicalRecord.${lookupKey}`);
                if (translated !== `clinicalRecord.${lookupKey}`) return translated;
            }

            return key.replace(/([A-Z])/g, ' $1').trim();
        };

        const vitals = record.vitalSigns ? `
            <div class="section">
                <div class="section-title">${t('clinicalRecord.vitalSigns')}</div>
                <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; background: #f8fafc; padding: 15px; border-radius: 8px;">
                    <div><div style="font-size: 11px; color: #64748b;">${t('patientDetails.bloodPressure')}</div><div style="font-weight: 600;">${record.vitalSigns.bp || '-'}</div></div>
                    <div><div style="font-size: 11px; color: #64748b;">${t('patientDetails.heartRate')}</div><div style="font-weight: 600;">${record.vitalSigns.hr || '-'}</div></div>
                    <div><div style="font-size: 11px; color: #64748b;">${t('patientDetails.respiratoryRate')}</div><div style="font-weight: 600;">${record.vitalSigns.rr || '-'}</div></div>
                    <div><div style="font-size: 11px; color: #64748b;">${t('patientDetails.temperature')}</div><div style="font-weight: 600;">${record.vitalSigns.temp || '-'}</div></div>
                    <div><div style="font-size: 11px; color: #64748b;">${t('patientDetails.spo2')}</div><div style="font-weight: 600;">${record.vitalSigns.spo2 || '-'}</div></div>
                </div>
            </div>` : '';

        const historyContent = record.pastMedicalHistory ? Object.entries(record.pastMedicalHistory)
            .filter(([_, v]) => v && typeof v === 'string' && (v as string).trim() !== '')
            .map(([key, value]) => `<div style="margin-bottom:8px;"><span style="font-weight:600;text-transform:capitalize;color:#475569;">${getRecordFieldLabel(key)}:</span> <span style="color:#334155;">${value}</span></div>`)
            .join('') : '';

        const historySection = historyContent ? `
            <div class="section">
                <div class="section-title">${t('clinicalRecord.pastMedicalHistory')}</div>
                ${historyContent}
            </div>` : '';

        const examContent = record.physicalExamination ? Object.entries(record.physicalExamination)
            .filter(([_, v]) => v && typeof v === 'string' && (v as string).trim() !== '')
            .map(([key, value]) => `<div style="margin-bottom:8px;"><span style="font-weight:600;text-transform:capitalize;color:#475569;">${getRecordFieldLabel(key)}:</span> <span style="color:#334155;">${value}</span></div>`)
            .join('') : '';

        const examSection = examContent ? `
            <div class="section">
                <div class="section-title">${t('clinicalRecord.physicalExamination')}</div>
                ${examContent}
            </div>` : '';

        const diagnosesSection = record.diagnoses?.length > 0 ? `
            <div class="section">
                <div class="section-title">${t('patientDetails.diagnoses')}</div>
                <ul style="padding-left:20px;margin:0;">
                    ${record.diagnoses.map((d: string) => `<li style="margin-bottom:4px;">${d}</li>`).join('')}
                </ul>
            </div>` : '';

        const bodyHtml = `
            <div class="section">
                <div class="section-title">${t('clinicalRecord.chiefComplaint')}</div>
                <div style="background:#f1f5f9;padding:10px;border-radius:6px;">${record.chiefComplaint || record.reasonForConsultation || t('common.na')}</div>
                ${record.historyOfPresentIllness ? `<div style="margin-top:12px;"><div style="font-weight:600;color:#475569;margin-bottom:4px;">${t('clinicalRecord.hpi')}</div><div class="section-text">${record.historyOfPresentIllness}</div></div>` : ''}
            </div>
            ${vitals}
            ${historySection}
            ${examSection}
            ${diagnosesSection}
            <div class="section">
                <div class="section-title">${t('clinicalRecord.plan')}</div>
                <div class="notes">${record.plan || record.comments || t('patientDetails.none')}</div>
            </div>
        `;

        const patientName = `${patient.userId?.firstName || ''} ${patient.userId?.lastName || ''}`;
        const insuranceStr = patient.insurance?.provider
            ? `${patient.insurance.provider}${patient.insurance.policyNumber ? ` (#${patient.insurance.policyNumber})` : ''}`
            : undefined;

        printRecord({
            doctor,
            clinic,
            patient: {
                name: patientName,
                phone: patient.userId?.phone,
                gender: formatGenderForPrint(patient.gender, {
                    male: t('common.male'),
                    female: t('common.female'),
                    other: t('common.other'),
                }),
                dob: patient.dateOfBirth ? formatDate(patient.dateOfBirth) : undefined,
                id: patient.nationalId,
                insurance: insuranceStr,
            },
            record: {
                date: formatDate(record.date || record.createdAt),
                type: t('patientDetails.activities.consultation'),
                title: record.title || t('patientDetails.medicalConsultationRecord'),
            },
            labels: printLabels,
            content: bodyHtml,
        });
    };

    const handleViewDentalRecord = (record: any) => {
        setSelectedRecord(record);
        setFormMode('view');
        setOpenDentalForm(true);
    };

    const handleEditDentalRecord = (record: any) => {
        setSelectedRecord(record);
        setFormMode('edit');
        setOpenDentalForm(true);
    };

    const handlePrintDentalRecord = (record: any) => {
        const { doctor, clinic } = getDoctorPrintData(record, user, {
            doctor: t('common.doctor'),
        });
        const patientName = `${patient.userId?.firstName || ''} ${patient.userId?.lastName || ''}`;
        const insuranceStr = patient.insurance?.provider
            ? `${patient.insurance.provider}${patient.insurance.policyNumber ? ` (#${patient.insurance.policyNumber})` : ''}`
            : undefined;

        const dh = record.dentalHistory || {};
        const yesText = t('common.yes');
        const getDentalFieldLabel = (key: string) => {
            const translated = t(`dentalRecord.${key}`);
            if (translated !== `dentalRecord.${key}`) return translated;
            return key;
        };
        // Dental history boolean flags
        const dhFlags = [
            [t('dentalRecord.bleedingGums'), dh.bleedingGums],
            [t('dentalRecord.badBreath'), dh.badBreath],
            [t('dentalRecord.foodImpaction'), dh.foodImpaction],
            [t('dentalRecord.mouthRinse'), dh.mouthRinse],
            [t('dentalRecord.dentalFloss'), dh.dentalFloss],
            [t('dentalRecord.anesthesiaProblems'), dh.anesthesiaProblems],
        ].filter(([, v]) => v).map(([label]) => `<span class="badge">${label}</span>`).join(' ');

        const renderKvSection = (title: string, obj: Record<string, string>) => {
            const rows = Object.entries(obj).filter(([, v]) => v);
            if (!rows.length) return '';
            return `
              <div class="section">
                <div class="section-title">${title}</div>
                <table><tbody>
                  ${rows.map(([k, v]) => `
                    <tr>
                      <td style="width:40%;color:#64748b;font-weight:600;text-transform:capitalize;">${getDentalFieldLabel(k)}</td>
                      <td>${v}</td>
                    </tr>`).join('')}
                </tbody></table>
              </div>`;
        };

        const odontogramHtml = buildOdontogramHtml(record.odontogram, {
            healthy: t('patientDetails.healthy'),
            caries: t('patientDetails.decay'),
            filled: t('patientDetails.filled'),
            missing: t('patientDetails.missing'),
            exodontia: t('patientDetails.exodontia'),
            crown: t('patientDetails.crown'),
            rootCanal: t('patientDetails.rootCanal'),
            implant: t('patientDetails.implant'),
        });
        const dentalNotes = record.odontogramNotes || record.odontogram?.General?.notes || '';
        const procedures = Array.isArray(record.procedures)
            ? record.procedures.filter((p: any) => p?.procedure || p?.date || p?.totalPaid)
            : [];

        printRecord({
            doctor,
            clinic,
            patient: {
                name: patientName,
                phone: patient.userId?.phone,
                gender: formatGenderForPrint(patient.gender, {
                    male: t('common.male'),
                    female: t('common.female'),
                    other: t('common.other'),
                }),
                dob: patient.dateOfBirth ? formatDate(patient.dateOfBirth) : undefined,
                id: patient.nationalId,
                insurance: insuranceStr,
            },
            record: {
                date: formatDate(record.date || record.createdAt),
                type: t('dentalRecord.title'),
                title: t('dentalRecord.title'),
            },
            labels: printLabels,
            content: `
                <div class="section">
                    <div class="section-title">${t('dentalRecord.dentalHistory')}</div>
                    <table><tbody>
                        ${dh.lossOfTeeth ? `<tr><td style="width:40%;color:#64748b;font-weight:600;">${t('dentalRecord.lossOfTeeth')}</td><td>${yesText}${dh.causeOfLoss ? ' — ' + dh.causeOfLoss : ''}</td></tr>` : ''}
                        ${dh.previousDentalTreatment ? `<tr><td style="width:40%;color:#64748b;font-weight:600;">${t('dentalRecord.previousDentalTreatment')}</td><td>${yesText}${dh.treatmentExplanation ? ' — ' + dh.treatmentExplanation : ''}</td></tr>` : ''}
                        ${dh.brushingFrequency ? `<tr><td style="width:40%;color:#64748b;font-weight:600;">${t('dentalRecord.brushingFrequency')}</td><td>${dh.brushingFrequency}</td></tr>` : ''}
                        ${dh.dentalTrauma ? `<tr><td style="width:40%;color:#64748b;font-weight:600;">${t('dentalRecord.dentalTrauma')}</td><td>${dh.dentalTrauma}</td></tr>` : ''}
                    </tbody></table>
                    ${dhFlags ? `<div style="margin-top:8px;display:flex;flex-wrap:wrap;gap:6px;">${dhFlags}</div>` : ''}
                </div>

                ${renderKvSection(t('dentalRecord.extraoralExamination'), record.extraoralExamination || {})}

                ${renderKvSection(t('dentalRecord.intraoralExamination'), record.intraoralExamination || {})}

                <div class="section">
                    <div class="section-title">${t('dentalRecord.odontogram')}</div>
                    ${odontogramHtml}
                    ${procedures.length > 0 ? `
                    <div style="margin-top:10px;display:grid;gap:10px;">
                        ${procedures.map((p: any, idx: number) => `
                            <div style="border:1px solid #e2e8f0;border-radius:8px;padding:10px;">
                                <div style="font-size:11px;color:#64748b;font-weight:600;margin-bottom:6px;">${t('dentalRecord.procedureEntry')} ${idx + 1}</div>
                                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;">
                                    <div><div style="font-size:11px;color:#64748b;">${t('dentalRecord.procedurePerformed')}</div><div style="font-size:13px;color:#0f172a;">${p.procedure || '-'}</div></div>
                                    <div><div style="font-size:11px;color:#64748b;">${t('dentalRecord.procedureDate')}</div><div style="font-size:13px;color:#0f172a;">${p.date ? new Date(p.date).toLocaleDateString() : '-'}</div></div>
                                    <div><div style="font-size:11px;color:#64748b;">${t('dentalRecord.totalPaid')}</div><div style="font-size:13px;color:#0f172a;">${p.totalPaid || '-'}</div></div>
                                </div>
                            </div>
                        `).join('')}
                    </div>` : ''}
                    ${dentalNotes ? `<div class="notes" style="margin-top:10px;">${dentalNotes}</div>` : ''}
                </div>

                ${record.radiographicAnalysis ? `
                <div class="section">
                    <div class="section-title">${t('dentalRecord.radiographicAnalysis')}</div>
                    <div class="section-text">${record.radiographicAnalysis}</div>
                </div>` : ''}

                ${record.treatmentPlan ? `
                <div class="section">
                    <div class="section-title">${t('dentalRecord.treatmentPlan')}</div>
                    <div class="section-text">${record.treatmentPlan}</div>
                </div>` : ''}
            `,
        });
    };

    // Dental Chart tab: print only the odontogram chart
    const handlePrintDentalChart = (record: any) => {
        const { doctor, clinic } = getDoctorPrintData(record, user, {
            doctor: t('common.doctor'),
        });
        const patientName = `${patient.userId?.firstName || ''} ${patient.userId?.lastName || ''}`;
        const insuranceStr = patient.insurance?.provider
            ? `${patient.insurance.provider}${patient.insurance.policyNumber ? ` (#${patient.insurance.policyNumber})` : ''}`
            : undefined;

        const odontogramHtml = buildOdontogramHtml(record.odontogram, {
            healthy: t('patientDetails.healthy'),
            caries: t('patientDetails.decay'),
            filled: t('patientDetails.filled'),
            missing: t('patientDetails.missing'),
            exodontia: t('patientDetails.exodontia'),
            crown: t('patientDetails.crown'),
            rootCanal: t('patientDetails.rootCanal'),
            implant: t('patientDetails.implant'),
        });
        const dentalNotes = record.odontogramNotes || record.odontogram?.General?.notes || '';
        const procedures = Array.isArray(record.procedures)
            ? record.procedures.filter((p: any) => p?.procedure || p?.date || p?.totalPaid)
            : [];

        printRecord({
            doctor,
            clinic,
            patient: {
                name: patientName,
                phone: patient.userId?.phone,
                gender: formatGenderForPrint(patient.gender, {
                    male: t('common.male'),
                    female: t('common.female'),
                    other: t('common.other'),
                }),
                dob: patient.dateOfBirth ? formatDate(patient.dateOfBirth) : undefined,
                id: patient.nationalId,
                insurance: insuranceStr,
            },
            record: {
                date: formatDate(record.date || record.createdAt),
                type: t('dentalRecord.title'),
                title: t('patientDetails.dentalChart'),
            },
            labels: printLabels,
            content: `
                <div class="section">
                    <div class="section-title">${t('dentalRecord.odontogram')}</div>
                    ${odontogramHtml}
                    ${procedures.length > 0 ? `
                    <div style="margin-top:10px;display:grid;gap:10px;">
                        ${procedures.map((p: any, idx: number) => `
                            <div style="border:1px solid #e2e8f0;border-radius:8px;padding:10px;">
                                <div style="font-size:11px;color:#64748b;font-weight:600;margin-bottom:6px;">${t('dentalRecord.procedureEntry')} ${idx + 1}</div>
                                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;">
                                    <div><div style="font-size:11px;color:#64748b;">${t('dentalRecord.procedurePerformed')}</div><div style="font-size:13px;color:#0f172a;">${p.procedure || '-'}</div></div>
                                    <div><div style="font-size:11px;color:#64748b;">${t('dentalRecord.procedureDate')}</div><div style="font-size:13px;color:#0f172a;">${p.date ? new Date(p.date).toLocaleDateString() : '-'}</div></div>
                                    <div><div style="font-size:11px;color:#64748b;">${t('dentalRecord.totalPaid')}</div><div style="font-size:13px;color:#0f172a;">${p.totalPaid || '-'}</div></div>
                                </div>
                            </div>
                        `).join('')}
                    </div>` : ''}
                    ${dentalNotes ? `<div class="notes" style="margin-top:10px;">${dentalNotes}</div>` : ''}
                </div>
            `,
        });
    };

    const uploadPatientImage = async (file: File) => {
        const formData = new FormData();
        formData.append('image', file);

        const response = await fetch(`${API_BASE_URL}/api/upload/patient-image`, {
            method: 'POST',
            body: formData,
        });

        const result = await response.json();
        if (!response.ok || !result?.success || !result?.filePath) {
            throw new Error(result?.error || t('patientDetails.imageUploadFailed'));
        }

        return result.filePath as string;
    };

    const handleAddExam = async (e: React.SyntheticEvent<HTMLFormElement>) => {
        e.preventDefault();
        setSavingExam(true);
        try {
            if (!examFile && !isEditingExam) {
                throw new Error(t('patientDetails.selectExamImage'));
            }

            const uploadedImagePath = examFile ? await uploadPatientImage(examFile) : examForm.fileUrl;
            const examToSave = {
                ...examForm,
                date: examForm.date || new Date().toISOString(),
                fileUrl: uploadedImagePath,
                notes: examForm.notes?.trim() || undefined,
            };

            const response = isEditingExam
                ? await http.put<{ success: boolean; error?: string }>(`/patients/${patient._id}/test-results/${editingExamId}`, examToSave)
                : await http.post<{ success: boolean; error?: string }>(`/patients/${patient._id}/test-results`, examToSave);
            if (!response.ok || !response.data?.success) {
                throw new Error(response.data?.error || t('patientDetails.examSaveFailed'));
            }

            await refreshPatient();
            toast.success(isEditingExam ? t('patientDetails.examUpdatedSuccess') : t('patientDetails.examAddedSuccess'));
            setOpenAddExam(false);
            resetExamForm();
        } catch (error: any) {
            toast.error(error?.message || t('patientDetails.examSaveFailed'));
        } finally {
            setSavingExam(false);
        }
    };

    const handleAddDocument = async (e: React.SyntheticEvent<HTMLFormElement>) => {
        e.preventDefault();
        setSavingDocument(true);
        try {
            if (!documentFile && !isEditingDocument) {
                throw new Error(t('patientDetails.selectDocumentImage'));
            }

            const uploadedImagePath = documentFile ? await uploadPatientImage(documentFile) : documentForm.url;
            const detectedType = documentFile
                ? (documentFile.type
                    ? documentFile.type.split('/').pop()?.toUpperCase() || 'IMAGE'
                    : (documentFile.name.split('.').pop()?.toUpperCase() || 'IMAGE'))
                : (documentForm.type || 'IMAGE');
            const documentToSave = {
                ...documentForm,
                type: detectedType,
                date: documentForm.date || new Date().toISOString(),
                url: uploadedImagePath,
                category: documentForm.category?.trim() || undefined,
            };

            const response = isEditingDocument
                ? await http.put<{ success: boolean; error?: string }>(`/patients/${patient._id}/documents/${editingDocumentId}`, documentToSave)
                : await http.post<{ success: boolean; error?: string }>(`/patients/${patient._id}/documents`, documentToSave);
            if (!response.ok || !response.data?.success) {
                throw new Error(response.data?.error || t('patientDetails.documentSaveFailed'));
            }

            await refreshPatient();
            toast.success(isEditingDocument ? t('patientDetails.documentUpdatedSuccess') : t('patientDetails.documentAddedSuccess'));
            setOpenAddDocument(false);
            resetDocumentForm();
        } catch (error: any) {
            toast.error(error?.message || t('patientDetails.documentSaveFailed'));
        } finally {
            setSavingDocument(false);
        }
    };

    const resetExamForm = () => {
        setEditingExamId(null);
        setExamFile(null);
        setExamForm({
            date: new Date().toISOString().split('T')[0],
            type: '',
            name: '',
            result: '',
            notes: '',
        });
    };

    const resetDocumentForm = () => {
        setEditingDocumentId(null);
        setDocumentFile(null);
        setDocumentForm({
            date: new Date().toISOString().split('T')[0],
            name: '',
            type: '',
            url: '',
            category: '',
        });
    };

    const toInputDate = (value?: string) => (value ? value.split('T')[0] : new Date().toISOString().split('T')[0]);

    const handleEditExam = (exam: TestResultItem) => {
        if (!exam._id) return;
        setEditingExamId(exam._id);
        setExamFile(null);
        setExamForm({
            ...exam,
            date: toInputDate(exam.date),
            type: exam.type || '',
            name: exam.name || '',
            result: exam.result || '',
            notes: exam.notes || '',
            fileUrl: exam.fileUrl || '',
        });
        setOpenAddExam(true);
    };

    const handleEditDocument = (doc: DocumentItem) => {
        if (!doc._id) return;
        setEditingDocumentId(doc._id);
        setDocumentFile(null);
        setDocumentForm({
            ...doc,
            date: toInputDate(doc.date),
            name: doc.name || '',
            type: doc.type || '',
            url: doc.url || '',
            category: doc.category || '',
        });
        setOpenAddDocument(true);
    };

    const handleDeleteExam = async (examId?: string) => {
        if (!examId) return;
        if (!window.confirm(t('patientDetails.confirmDeleteExam'))) return;
        try {
            const response = await http.delete<{ success: boolean; error?: string }>(`/patients/${patient._id}/test-results/${examId}`);
            if (!response.ok || !response.data?.success) {
                throw new Error(response.data?.error || t('patientDetails.examDeleteFailed'));
            }
            await refreshPatient();
            toast.success(t('patientDetails.examDeletedSuccess'));
        } catch (error: any) {
            toast.error(error?.message || t('patientDetails.examDeleteFailed'));
        }
    };

    const handleDeleteDocument = async (documentId?: string) => {
        if (!documentId) return;
        if (!window.confirm(t('patientDetails.confirmDeleteDocument'))) return;
        try {
            const response = await http.delete<{ success: boolean; error?: string }>(`/patients/${patient._id}/documents/${documentId}`);
            if (!response.ok || !response.data?.success) {
                throw new Error(response.data?.error || t('patientDetails.documentDeleteFailed'));
            }
            await refreshPatient();
            toast.success(t('patientDetails.documentDeletedSuccess'));
        } catch (error: any) {
            toast.error(error?.message || t('patientDetails.documentDeleteFailed'));
        }
    };

    useEffect(() => {
        if (patient?._id) {
            api.prescriptions.getByPatientId(patient._id).then(res => {
                if (res.success && res.data) setPrescriptions(res.data);
            }).catch(e => console.error(t('patientDetails.fetchPrescriptionsFailed'), e));
        }
    }, [patient]);

    const formatDate = (d?: string) => {
        if (!d) return '-';
        // Parse as UTC parts to avoid timezone shift (e.g. 3/31 becoming 4/1)
        const date = new Date(d);
        const locale = language === 'es' ? 'es-ES' : 'en-US';
        return date.toLocaleDateString(locale, { timeZone: 'UTC' });
    };

    const handlePrintPrescription = (prescription: any) => {
        const { doctor, clinic } = getDoctorPrintData(prescription, user, {
            doctor: t('common.doctor'),
        });

        const isPrescription = !prescription.documentType || prescription.documentType === 'Prescription';

        const meds = prescription.medications?.map((m: any, i: number) =>
            `<tr>
                <td>${i + 1}</td>
                <td style="font-weight:600;">${m.name || '-'}</td>
                <td>${m.dosage || '-'}</td>
                <td>${m.frequency || '-'}</td>
                <td>${m.duration || '-'}</td>
                <td>${m.instructions || '-'}</td>
            </tr>`
        ).join('') || `<tr><td colspan="6" style="text-align:center;color:#94a3b8;">${t('patientDetails.noMedicationsListed')}</td></tr>`;

        const docTypeLabel = (() => {
            switch (prescription.documentType) {
                case 'Referral': return t('prescriptions.documentTypeReferral');
                case 'Certification': return t('prescriptions.documentTypeCertification');
                case 'Medical Leave': return t('prescriptions.documentTypeMedicalLeave');
                case 'Laboratory': return t('prescriptions.documentTypeLaboratory');
                case 'Imaging': return t('prescriptions.documentTypeImaging');
                default: return t('prescriptions.documentTypePrescription');
            }
        })();

        const patientName = `${patient.userId?.firstName || ''} ${patient.userId?.lastName || ''}`;
        const insuranceStr = patient.insurance?.provider
            ? `${patient.insurance.provider}${patient.insurance.policyNumber ? ` (#${patient.insurance.policyNumber})` : ''}`
            : undefined;

        let content: string;

        if (isPrescription) {
            content = `
                ${prescription.diagnosis ? `
                    <div class="section">
                        <div class="section-title">${t('prescriptions.diagnosis')}</div>
                        <div class="diagnosis-text">${prescription.diagnosis}</div>
                    </div>
                ` : ''}
                <div class="section">
                    <table>
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>${t('prescriptions.medication')}</th>
                                <th>${t('prescriptions.dosage')}</th>
                                <th>${t('prescriptions.frequency')}</th>
                                <th>${t('prescriptions.duration')}</th>
                                <th>${t('prescriptions.instructions')}</th>
                            </tr>
                        </thead>
                        <tbody>${meds}</tbody>
                    </table>
                </div>
                ${prescription.notes ? `
                    <div class="section">
                        <div class="section-title">${t('prescriptions.notes')}</div>
                        <div class="notes">${prescription.notes}</div>
                    </div>
                ` : ''}
            `;
        } else {
            // Certification / Referral / Medical Leave / Laboratory / Imaging — formal document layout
            content = `
                <div style="text-align:center;margin:24px 0 32px;">
                    <h2 style="font-size:22px;font-weight:800;color:#0891b2;text-transform:uppercase;letter-spacing:2px;margin-bottom:4px;">${docTypeLabel}</h2>
                    <div style="width:60px;height:3px;background:#0891b2;margin:0 auto;border-radius:2px;"></div>
                </div>

                <div style="font-size:15px;line-height:2;text-align:justify;padding:0 8px;min-height:200px;word-break:break-all;overflow-wrap:anywhere;">
                    ${prescription.diagnosis ? `
                        <p style="margin-bottom:16px;"><strong style="color:#475569;">${t('prescriptions.diagnosis')}:</strong> ${prescription.diagnosis}</p>
                    ` : ''}
                    ${prescription.freeText ? `
                        <div style="white-space:pre-wrap;word-break:break-all;overflow-wrap:anywhere;">${prescription.freeText}</div>
                    ` : ''}
                </div>

                ${prescription.notes ? `
                    <div style="margin-top:24px;padding:12px 16px;background:#f8fafc;border-left:3px solid #0891b2;border-radius:0 6px 6px 0;font-size:13px;color:#475569;line-height:1.6;word-break:break-all;overflow-wrap:anywhere;">
                        <strong>${t('prescriptions.notes')}:</strong> ${prescription.notes}
                    </div>
                ` : ''}
            `;
        }

        printRecord({
            doctor,
            clinic,
            patient: {
                name: patientName,
                phone: patient.userId?.phone,
                gender: formatGenderForPrint(patient.gender, {
                    male: t('common.male'),
                    female: t('common.female'),
                    other: t('common.other'),
                }),
                dob: patient.dateOfBirth ? formatDate(patient.dateOfBirth) : undefined,
                id: patient.nationalId,
                insurance: insuranceStr,
            },
            record: {
                date: formatDate(prescription.createdAt),
                type: docTypeLabel,
                title: isPrescription ? t('prescriptions.medicalPrescription') : undefined,
            },
            labels: printLabels,
            content,
        });
    };

    const totalPrescriptionPages = Math.max(1, Math.ceil(prescriptions.length / prescriptionsPerPage));
    const currentPrescriptionPage = Math.min(prescriptionPage, totalPrescriptionPages);
    const paginatedPrescriptions = prescriptions.slice(
        (currentPrescriptionPage - 1) * prescriptionsPerPage,
        currentPrescriptionPage * prescriptionsPerPage
    );
    const prescriptionShowingFrom = prescriptions.length > 0
        ? (currentPrescriptionPage - 1) * prescriptionsPerPage + 1
        : 0;
    const prescriptionShowingTo = Math.min(currentPrescriptionPage * prescriptionsPerPage, prescriptions.length);

    // Group paginated prescriptions by date
    const groupedPrescriptions = paginatedPrescriptions.reduce((groups: Record<string, any[]>, p) => {
        const dateKey = formatDate(p.createdAt);
        if (!groups[dateKey]) groups[dateKey] = [];
        groups[dateKey].push(p);
        return groups;
    }, {});

    return (
        <div className="p-6 space-y-6 bg-slate-50/50 min-h-screen">
            {/* Header */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div className="flex items-center gap-4">
                    <div className="h-16 w-16 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 text-2xl font-bold">
                        {patient.userId?.firstName?.[0]}{patient.userId?.lastName?.[0]}
                    </div>
                    <div>
                        <h1 className="text-3xl font-bold tracking-tight text-slate-900">{patient.userId?.firstName} {patient.userId?.lastName}</h1>
                        <div className="flex gap-2 text-sm text-gray-500 mt-1">
                            <span>{getLocalizedGender(patient.gender)}</span>
                            <span>•</span>
                            <span>{formatDate(patient.dateOfBirth)}</span>
                            <span>•</span>
                            <span>{patient.userId?.phone}</span>
                        </div>
                        <div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-gray-500 mt-1">
                            {patient.nationalId && (
                                <span className="flex items-center gap-1">
                                    <span className="font-semibold">{t('common.id')}:</span> {patient.nationalId}
                                </span>
                            )}
                            {(patient.insurance?.provider || patient.insurance?.policyNumber) && (
                                <span className="flex items-center gap-1">
                                    <span className="font-semibold">{t('medicalRecord.insurance')}:</span>
                                    {patient.insurance?.provider || '-'}
                                    {patient.insurance?.policyNumber && <span className="text-gray-400">#{patient.insurance.policyNumber}</span>}
                                </span>
                            )}
                        </div>
                    </div>
                </div>
                <div className="flex gap-2 whitespace-nowrap overflow-x-auto">
                    <Button variant="outline" onClick={() => setOpenEditProfile(true)}>{t('patientDetails.editProfile')}</Button>
                    <Button onClick={() => router.push(`/appointments?book=true&patientId=${patient._id}`)}>{t('patientDetails.newAppointment')}</Button>
                </div>
            </div>

            {/* Main Content */}
            <Tabs value={activeTab} onValueChange={(val) => router.replace(`?tab=${val}`, { scroll: false })} className="w-full">
                <TabsList className="w-full justify-start rounded-none border-b bg-transparent p-0 overflow-x-auto overflow-y-hidden whitespace-nowrap [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
                    <TabsTrigger value="overview" className="shrink-0 relative h-9 rounded-none border-b-2 border-transparent bg-transparent px-4 pb-3 pt-2 font-semibold text-muted-foreground shadow-none transition-none data-[state=active]:rounded-t-md data-[state=active]:border-primary data-[state=active]:text-foreground data-[state=active]:shadow-none">{t('patientDetails.overview')}</TabsTrigger>
                    <TabsTrigger value="history" className="shrink-0 relative h-9 rounded-none border-b-2 border-transparent bg-transparent px-4 pb-3 pt-2 font-semibold text-muted-foreground shadow-none transition-none data-[state=active]:rounded-t-md data-[state=active]:border-primary data-[state=active]:text-foreground data-[state=active]:shadow-none">
                        {isDentist ? t('patientDetails.dentalReports') : t('patientDetails.medicalHistory')}
                    </TabsTrigger>
                    <TabsTrigger value="prescriptions" className="shrink-0 relative h-9 rounded-none border-b-2 border-transparent bg-transparent px-4 pb-3 pt-2 font-semibold text-muted-foreground shadow-none transition-none data-[state=active]:rounded-t-md data-[state=active]:border-primary data-[state=active]:text-foreground data-[state=active]:shadow-none">{t('patientDetails.prescriptions')}</TabsTrigger>
                    <TabsTrigger value="exams" className="shrink-0 relative h-9 rounded-none border-b-2 border-transparent bg-transparent px-4 pb-3 pt-2 font-semibold text-muted-foreground shadow-none transition-none data-[state=active]:rounded-t-md data-[state=active]:border-primary data-[state=active]:text-foreground data-[state=active]:shadow-none">{t('patientDetails.examsDocuments')}</TabsTrigger>
                    {isDentist && (
                        <TabsTrigger value="dental" className="shrink-0 relative h-9 rounded-none border-b-2 border-transparent bg-transparent px-4 pb-3 pt-2 font-semibold text-muted-foreground shadow-none transition-none data-[state=active]:rounded-t-md data-[state=active]:border-primary data-[state=active]:text-foreground data-[state=active]:shadow-none">{t('patientDetails.dentalChart')}</TabsTrigger>
                    )}
                </TabsList>

                {/* Overview: Vitals + Basic Info */}
                <TabsContent value="overview" className="mt-6 space-y-6">
                    {!isDentist && (() => {
                        // Get latest vital signs: prefer from patient.vitalSigns[0], fallback to latest clinical record
                        const patientVs = patient.vitalSigns?.[0];
                        const latestRecord = patient.clinicalRecords?.length
                            ? patient.clinicalRecords[patient.clinicalRecords.length - 1]
                            : null;
                        const recordVs = latestRecord?.vitalSigns;

                        const bp = patientVs?.bloodPressure || recordVs?.bp || '-';
                        const hr = patientVs?.heartRate || recordVs?.hr || '-';
                        const temp = patientVs?.temperature || recordVs?.temp || '-';
                        const rr = patientVs?.respiratoryRate || recordVs?.rr || '-';
                        const spo2 = patientVs?.oxygenSaturation || recordVs?.spo2 || '-';

                        return (
                            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
                                <Card>
                                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                                        <CardTitle className="text-sm font-medium">{t('patientDetails.bloodPressure')}</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <div className="text-2xl font-bold">{bp}{bp !== '-' ? ' mmHg' : ''}</div>
                                    </CardContent>
                                </Card>
                                <Card>
                                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                                        <CardTitle className="text-sm font-medium">{t('patientDetails.heartRate')}</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <div className="text-2xl font-bold">{hr}{hr !== '-' ? ' bpm' : ''}</div>
                                    </CardContent>
                                </Card>
                                <Card>
                                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                                        <CardTitle className="text-sm font-medium">{t('patientDetails.temperature')}</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <div className="text-2xl font-bold">{temp}{temp !== '-' ? ' °C' : ''}</div>
                                    </CardContent>
                                </Card>
                                <Card>
                                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                                        <CardTitle className="text-sm font-medium">{t('patientDetails.respiratoryRate')}</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <div className="text-2xl font-bold">{rr}{rr !== '-' ? ' /min' : ''}</div>
                                    </CardContent>
                                </Card>
                                <Card>
                                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                                        <CardTitle className="text-sm font-medium">{t('patientDetails.spo2')}</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <div className="text-2xl font-bold">{spo2}{spo2 !== '-' ? ' %' : ''}</div>
                                    </CardContent>
                                </Card>
                            </div>
                        );
                    })()}

                    <Card>
                        <CardHeader>
                            <CardTitle>{t('patientDetails.recentActivity')}</CardTitle>
                        </CardHeader>
                        <CardContent>
                            {(() => {
                                const activities: { type: string; title: string; description: string; date: string }[] = [];

                                // Clinical records
                                (patient.clinicalRecords || []).forEach((r: any) => {
                                    activities.push({
                                        type: 'consultation',
                                        title: t('patientDetails.activities.consultation'),
                                        description: r.chiefComplaint || r.reasonForConsultation || t('patientDetails.activities.generalConsultation'),
                                        date: r.date || r.createdAt,
                                    });
                                });

                                // Prescriptions
                                prescriptions.forEach((p: any) => {
                                    const medCount = p.medications?.length || 0;
                                    activities.push({
                                        type: 'prescription',
                                        title: t('patientDetails.activities.prescription'),
                                        description: t('patientDetails.activities.medicationPrescribed').replace('{count}', String(medCount)),
                                        date: p.date || p.createdAt,
                                    });
                                });

                                // Dental records
                                (patient.dentalRecords || []).forEach((d: any) => {
                                    activities.push({
                                        type: 'dental',
                                        title: t('patientDetails.activities.dentalRecord'),
                                        description: d.procedure || d.notes || t('patientDetails.activities.dentalExamination'),
                                        date: d.date || d.createdAt,
                                    });
                                });

                                // Sort by date descending, take latest 5
                                activities.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
                                const recent = activities.slice(0, 5);

                                if (recent.length === 0) {
                                    return <p className="text-gray-500 text-sm">{t('patientDetails.noRecentActivity')}</p>;
                                }

                                const typeColors: Record<string, string> = {
                                    consultation: 'bg-blue-100 text-blue-700',
                                    prescription: 'bg-green-100 text-green-700',
                                    dental: 'bg-purple-100 text-purple-700',
                                };

                                return (
                                    <div className="space-y-3">
                                        {recent.map((activity, idx) => (
                                            <div key={idx} className="flex items-start gap-3 p-3 rounded-lg border">
                                                <Badge className={`${typeColors[activity.type] || 'bg-gray-100 text-gray-700'} text-xs shrink-0`}>
                                                    {activity.title}
                                                </Badge>
                                                <div className="flex-1 min-w-0">
                                                    <p className="text-sm text-foreground truncate">{activity.description}</p>
                                                    <p className="text-xs text-muted-foreground mt-0.5">{formatDate(activity.date)}</p>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                );
                            })()}
                        </CardContent>
                    </Card>
                </TabsContent>

                {/* History */}
                <TabsContent value="history" className="mt-6">
                    {!isDentist ? (
                        <Card>
                            <CardHeader className="flex flex-col items-stretch gap-3 sm:flex-row sm:items-center sm:justify-between">
                                <div className="space-y-1.5">
                                    <CardTitle>{t('patientDetails.medicalHistory')}</CardTitle>
                                    <CardDescription>{t('patientDetails.comprehensiveHistory')}</CardDescription>
                                </div>
                                <Button size="sm" className="w-full sm:w-auto" onClick={() => router.push(`/patients/${patient._id}/clinical-record/new`)}>
                                    {t('patientDetails.newMedicalConsultation')}
                                </Button>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                <div>
                                    <h4 className="font-semibold mb-1">{t('patientDetails.generalNotes')}</h4>
                                    <p className="text-sm text-gray-700 whitespace-pre-wrap">{patient.medicalHistory || t('patientDetails.noHistory')}</p>
                                </div>

                                <div>
                                    <h4 className="font-semibold mb-1">{t('patientDetails.medicalConsultations')}</h4>
                                    {(patient.clinicalRecords?.length ?? 0) > 0 ? (
                                        <ul className="space-y-2 mt-2">
                                            {patient.clinicalRecords?.map((record: any, i: number) => (
                                                <li key={i} className="border p-3 rounded bg-white text-sm hover:shadow-md transition-shadow">
                                                    <div className="flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-start">
                                                        <div className="flex-1 min-w-0">
                                                            <div className="font-semibold line-clamp-1">{record.title || t('clinicalRecord.title')}</div>
                                                            <div className="font-medium">{t('patientDetails.examDate')}: {formatDate(record.date)}</div>
                                                            <div className="text-gray-600 line-clamp-2">{record.chiefComplaint || record.reasonForConsultation || t('common.na')}</div>
                                                        </div>
                                                        <div className="grid grid-cols-1 gap-2 w-full sm:w-auto sm:flex sm:gap-2 shrink-0">
                                                            <Button
                                                                variant="outline"
                                                                size="sm"
                                                                className="w-full sm:w-auto justify-start sm:justify-center"
                                                                onClick={() => handleViewRecord(record)}
                                                            >
                                                                <Eye className="h-4 w-4 mr-1" /> {t('common.view')}
                                                            </Button>
                                                            <Button
                                                                variant="outline"
                                                                size="sm"
                                                                className="w-full sm:w-auto justify-start sm:justify-center"
                                                                onClick={() => handleEditRecord(record)}
                                                            >
                                                                <Edit className="h-4 w-4 mr-1" /> {t('common.edit')}
                                                            </Button>
                                                            <Button
                                                                variant="outline"
                                                                size="sm"
                                                                className="w-full sm:w-auto justify-start sm:justify-center"
                                                                onClick={() => handlePrintRecord(record)}
                                                            >
                                                                <Printer className="h-4 w-4 mr-1" /> {t('common.print')}
                                                            </Button>
                                                        </div>
                                                    </div>
                                                </li>
                                            ))}
                                        </ul>
                                    ) : <p className="text-sm text-gray-500">{t('patientDetails.noMedicalRecords')}</p>}
                                </div>

                                <div>
                                    <h4 className="font-semibold mb-1">{t('patientDetails.diagnoses')}</h4>
                                    {(patient.diagnoses?.length ?? 0) > 0 ? (
                                        <ul className="list-disc ml-4 text-sm text-gray-700">
                                            {patient.diagnoses?.map((d: { code: string; description: string; status: string }, i: number) => (
                                                <li key={i}>
                                                    <span className="font-medium">{d.code}</span>: {d.description} ({d.status})
                                                </li>
                                            ))}
                                        </ul>
                                    ) : <p className="text-sm text-gray-500">{t('patientDetails.noDiagnoses')}</p>}
                                </div>
                            </CardContent>
                        </Card>
                    ) : (
                        <Card>
                            <CardHeader className="flex flex-col items-stretch gap-3 sm:flex-row sm:items-center sm:justify-between">
                                <div className="space-y-1.5">
                                    <CardTitle>{t('patientDetails.dentalReports')}</CardTitle>
                                    <CardDescription>{t('patientDetails.dentalHistory')}</CardDescription>
                                </div>
                                <Button size="sm" className="w-full sm:w-auto" onClick={() => router.push(`/patients/${patient._id}/dental-record/new`)}>
                                    {t('patientDetails.newDentalRecord')}
                                </Button>
                            </CardHeader>
                            <CardContent>
                                {(patient.dentalRecords?.length ?? 0) > 0 ? (
                                    <ul className="space-y-2 mt-2">
                                        {patient.dentalRecords?.map((record: any, i: number) => (
                                            <li key={i} className="border p-3 rounded bg-white text-sm hover:shadow-md transition-shadow">
                                                <div className="flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-start">
                                                    <div className="flex-1 min-w-0">
                                                        <div className="font-medium">{t('patientDetails.examDate')}: {formatDate(record.date)}</div>
                                                        <div className="text-gray-600 line-clamp-2 break-all [overflow-wrap:anywhere] mt-1">
                                                            {record.treatmentPlan || record.odontogram?.notes || t('patientDetails.activities.dentalExamination')}
                                                        </div>
                                                    </div>
                                                    <div className="grid grid-cols-1 gap-2 w-full sm:w-auto sm:flex sm:gap-2 shrink-0">
                                                        <Button
                                                            variant="outline"
                                                            size="sm"
                                                            className="w-full sm:w-auto justify-start sm:justify-center"
                                                            onClick={() => handleViewDentalRecord(record)}
                                                        >
                                                            <Eye className="h-4 w-4 mr-1" /> {t('common.view')}
                                                        </Button>
                                                        <Button
                                                            variant="outline"
                                                            size="sm"
                                                            className="w-full sm:w-auto justify-start sm:justify-center"
                                                            onClick={() => handleEditDentalRecord(record)}
                                                        >
                                                            <Edit className="h-4 w-4 mr-1" /> {t('common.edit')}
                                                        </Button>
                                                        <Button
                                                            variant="outline"
                                                            size="sm"
                                                            className="w-full sm:w-auto justify-start sm:justify-center"
                                                            onClick={() => handlePrintDentalRecord(record)}
                                                        >
                                                            <Printer className="h-4 w-4 mr-1" /> {t('common.print')}
                                                        </Button>
                                                    </div>
                                                </div>
                                            </li>
                                        ))}
                                    </ul>
                                ) : <p className="text-sm text-gray-500">{t('patientDetails.noDentalReports')}</p>}
                            </CardContent>
                        </Card>
                    )}
                </TabsContent>

                {/* Prescriptions - Date-wise list with view/edit/print */}
                <TabsContent value="prescriptions" className="mt-6">
                    <Card>
                        <CardHeader>
                            <div className="flex justify-between items-center gap-2">
                                <CardTitle>{t('patientDetails.prescriptions')}</CardTitle>
                                <div className="flex gap-2">
                                    <Button size="sm" onClick={() => { setNewDocumentType(undefined); setOpenPrescriptionNew(true); }}>
                                        {t('patientDetails.newPrescription')}
                                    </Button>
                                    <Button size="sm" variant="outline" onClick={() => { setNewDocumentType('Certification'); setOpenPrescriptionNew(true); }}>
                                        {t('patientDetails.newCertification')}
                                    </Button>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent>
                            {prescriptions.length === 0 ? (
                                <p className="text-sm text-gray-500">{t('patientDetails.noPrescriptions')}</p>
                            ) : (
                                <div className="space-y-6">
                                    {Object.entries(groupedPrescriptions).map(([date, items]) => (
                                        <div key={date}>
                                            <h4 className="text-sm font-semibold text-gray-500 mb-3 border-b pb-2">{date}</h4>
                                            <div className="space-y-3">
                                                {items.map((p: any) => (
                                                    <div key={p._id} className="border rounded-lg p-4 bg-white shadow-sm flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-center">
                                                        <div className="flex-1 min-w-0">
                                                            <div className="flex items-center gap-2">
                                                                <p className="font-semibold truncate">{p.diagnosis || t('patientDetails.noDiagnosis')}</p>
                                                                {p.documentType && p.documentType !== 'Prescription' && (
                                                                    <Badge variant="secondary" className="text-xs shrink-0">
                                                                        {(() => {
                                                                            switch (p.documentType) {
                                                                                case 'Referral': return t('prescriptions.documentTypeReferral');
                                                                                case 'Certification': return t('prescriptions.documentTypeCertification');
                                                                                case 'Medical Leave': return t('prescriptions.documentTypeMedicalLeave');
                                                                                case 'Laboratory': return t('prescriptions.documentTypeLaboratory');
                                                                                case 'Imaging': return t('prescriptions.documentTypeImaging');
                                                                                default: return p.documentType;
                                                                            }
                                                                        })()}
                                                                    </Badge>
                                                                )}
                                                            </div>
                                                            <p className="text-sm text-gray-500 truncate">
                                                                {(!p.documentType || p.documentType === 'Prescription')
                                                                    ? (p.medications?.map((m: any) => m.name).join(', ') || t('patientDetails.noMedications'))
                                                                    : (p.freeText ? p.freeText.substring(0, 80) + (p.freeText.length > 80 ? '...' : '') : '-')
                                                                }
                                                            </p>
                                                            {p.status && (
                                                                <Badge variant="outline" className="mt-1 text-xs">
                                                                    {p.status}
                                                                </Badge>
                                                            )}
                                                        </div>
                                                        <div className="grid grid-cols-1 gap-2 w-full sm:w-auto sm:flex sm:gap-2 shrink-0">
                                                            <Button
                                                                variant="outline"
                                                                size="sm"
                                                                className="w-full sm:w-auto justify-start sm:justify-center"
                                                                onClick={() => setViewPrescription(p)}
                                                            >
                                                                <Eye className="h-4 w-4 mr-1" /> {t('common.view')}
                                                            </Button>
                                                            <Button
                                                                variant="outline"
                                                                size="sm"
                                                                className="w-full sm:w-auto justify-start sm:justify-center"
                                                                onClick={() => setEditPrescription(p)}
                                                            >
                                                                <Edit className="h-4 w-4 mr-1" /> {t('common.edit')}
                                                            </Button>
                                                            <Button
                                                                variant="outline"
                                                                size="sm"
                                                                className="w-full sm:w-auto justify-start sm:justify-center"
                                                                onClick={() => handlePrintPrescription(p)}
                                                            >
                                                                <Printer className="h-4 w-4 mr-1" /> {t('common.print')}
                                                            </Button>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    ))}

                                    {totalPrescriptionPages > 1 && (
                                        <PaginationControls
                                            currentPage={currentPrescriptionPage}
                                            totalPages={totalPrescriptionPages}
                                            onPageChange={setPrescriptionPage}
                                            maxPageButtons={5}
                                            alignment="between"
                                            showSummary
                                            showPageSize={false}
                                            showingFrom={prescriptionShowingFrom}
                                            showingTo={prescriptionShowingTo}
                                            totalItems={prescriptions.length}
                                            labels={{
                                                showing: t('common.showing'),
                                                to: t('common.to'),
                                                of: t('common.of'),
                                                perPage: t('common.perPage'),
                                                previous: t('common.previous'),
                                                next: t('common.next'),
                                            }}
                                            className="px-0"
                                        />
                                    )}
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>

                {/* Documents - Exams */}
                <TabsContent value="exams" className="mt-6">
                    <div className="grid gap-6 lg:grid-cols-2">
                        <Card>
                            <CardHeader>
                                <div className="flex flex-col items-stretch gap-3 sm:flex-row sm:items-center sm:justify-between">
                                    <div>
                                        <CardTitle>{t('patientDetails.exams')}</CardTitle>
                                        <CardDescription>{t('patientDetails.examsDescription')}</CardDescription>
                                    </div>
                                    <Button
                                        size="sm"
                                        className="w-full sm:w-auto"
                                        onClick={() => {
                                            resetExamForm();
                                            setOpenAddExam(true);
                                        }}
                                    >
                                        {t('patientDetails.addExam')}
                                    </Button>
                                </div>
                            </CardHeader>
                            <CardContent className="space-y-3">
                                {(patient.testResults?.length ?? 0) > 0 ? (
                                    patient.testResults?.map((exam: TestResultItem, i: number) => (
                                        <div key={i} className="rounded-md border p-3 bg-white">
                                            <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-3">
                                                <div className="min-w-0">
                                                    <p className="font-semibold text-sm break-words">{exam.name || t('patientDetails.unnamedExam')}</p>
                                                    <p className="text-xs text-gray-500 break-words">{exam.type || t('patientDetails.defaultExamType')} • {formatDate(exam.date)}</p>
                                                </div>
                                                <Badge variant="outline" className="self-start">{t('patientDetails.exams')}</Badge>
                                            </div>
                                            <p className="text-sm text-slate-700 mt-2">{exam.result || t('patientDetails.noExamResult')}</p>
                                            {exam.notes && <p className="text-xs text-gray-500 mt-1">{exam.notes}</p>}
                                            {exam.fileUrl && (
                                                <Button type="button" variant="link" className="px-0 h-auto mt-1" asChild>
                                                    <a href={getAbsoluteFileUrl(exam.fileUrl)} target="_blank" rel="noopener noreferrer">
                                                        {t('patientDetails.openAttachment')}
                                                    </a>
                                                </Button>
                                            )}
                                            <div className="mt-3 flex flex-wrap gap-2">
                                                <Button type="button" size="sm" variant="outline" onClick={() => handleEditExam(exam)}>
                                                    <Edit className="h-4 w-4 mr-1" /> {t('common.edit')}
                                                </Button>
                                                <Button type="button" size="sm" variant="outline" onClick={() => handleDeleteExam(exam._id)}>
                                                    <Trash2 className="h-4 w-4 mr-1" /> {t('common.delete')}
                                                </Button>
                                            </div>
                                        </div>
                                    ))
                                ) : (
                                    <p className="text-sm text-gray-500">{t('patientDetails.noExams')}</p>
                                )}
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <div className="flex flex-col items-stretch gap-3 sm:flex-row sm:items-center sm:justify-between">
                                    <div>
                                        <CardTitle>{t('patientDetails.documents')}</CardTitle>
                                        <CardDescription>{t('patientDetails.documentsDescription')}</CardDescription>
                                    </div>
                                    <Button
                                        size="sm"
                                        className="w-full sm:w-auto"
                                        onClick={() => {
                                            resetDocumentForm();
                                            setOpenAddDocument(true);
                                        }}
                                    >
                                        {t('patientDetails.addDocument')}
                                    </Button>
                                </div>
                            </CardHeader>
                            <CardContent className="space-y-3">
                                {(patient.documents?.length ?? 0) > 0 ? (
                                    patient.documents?.map((doc: DocumentItem, i: number) => (
                                        <div key={i} className="rounded-md border p-3 bg-white">
                                            <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-3">
                                                <div className="min-w-0">
                                                    <p className="font-semibold text-sm break-words">{doc.name || t('patientDetails.unnamedDocument')}</p>
                                                    <p className="text-xs text-gray-500 break-words">{doc.type || t('patientDetails.defaultDocumentType')} • {formatDate(doc.date)}</p>
                                                </div>
                                                {doc.category && <Badge variant="outline" className="self-start">{doc.category}</Badge>}
                                            </div>
                                            {doc.url && (
                                                <Button type="button" variant="link" className="px-0 h-auto mt-2" asChild>
                                                    <a href={getAbsoluteFileUrl(doc.url)} target="_blank" rel="noopener noreferrer">
                                                        {t('patientDetails.openDocument')}
                                                    </a>
                                                </Button>
                                            )}
                                            <div className="mt-3 flex flex-wrap gap-2">
                                                <Button type="button" size="sm" variant="outline" onClick={() => handleEditDocument(doc)}>
                                                    <Edit className="h-4 w-4 mr-1" /> {t('common.edit')}
                                                </Button>
                                                <Button type="button" size="sm" variant="outline" onClick={() => handleDeleteDocument(doc._id)}>
                                                    <Trash2 className="h-4 w-4 mr-1" /> {t('common.delete')}
                                                </Button>
                                            </div>
                                        </div>
                                    ))
                                ) : (
                                    <p className="text-sm text-gray-500">{t('patientDetails.noDocuments')}</p>
                                )}
                            </CardContent>
                        </Card>
                    </div>
                </TabsContent>

                {/* Dental Chart - Only visible to dentists */}
                {isDentist && (
                    <TabsContent value="dental" className="mt-6 space-y-4">
                        {(() => {
                            const records = patient.dentalRecords ?? [];
                            const total = records.length;
                            // clamp index in case records changed
                            const safeIndex = total > 0 ? Math.min(chartRecordIndex, total - 1) : 0;
                            const chartRecord = records[safeIndex];

                            // Parse the odontogram map into ToothState[]
                            const chartTeeth: ToothState[] = chartRecord?.odontogram
                                ? Object.entries(chartRecord.odontogram)
                                    .filter(([key]) => key !== 'General')
                                    .map(([key, value]: [string, any]) => ({
                                        id: parseInt(key),
                                        status: value.status ?? 'healthy',
                                        surfaces: value.surfaces ?? { top: 'healthy', bottom: 'healthy', left: 'healthy', right: 'healthy', center: 'healthy' },
                                        notes: value.notes ?? ''
                                    }))
                                : [];

                            return (
                                <Card>
                                    <CardHeader>
                                        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                                            <div>
                                                <CardTitle>{t('patientDetails.interactiveOdontogram')}</CardTitle>
                                                {total > 0 && (
                                                    <p className="text-sm text-muted-foreground mt-1">
                                                        Record {safeIndex + 1} of {total} — {formatDate(chartRecord?.date || chartRecord?.createdAt)}
                                                    </p>
                                                )}
                                            </div>
                                            <div className="flex items-center gap-2 flex-wrap">
                                                {/* Record navigator */}
                                                {total > 1 && (
                                                    <div className="flex items-center gap-1 border rounded-md">
                                                        <Button
                                                            variant="ghost" size="sm"
                                                            disabled={safeIndex === 0}
                                                            onClick={() => setChartRecordIndex(i => Math.max(0, i - 1))}
                                                        >
                                                            <ChevronLeft className="h-4 w-4" />
                                                        </Button>
                                                        <span className="text-xs px-1 text-muted-foreground">{safeIndex + 1}/{total}</span>
                                                        <Button
                                                            variant="ghost" size="sm"
                                                            disabled={safeIndex === total - 1}
                                                            onClick={() => setChartRecordIndex(i => Math.min(total - 1, i + 1))}
                                                        >
                                                            <ChevronRight className="h-4 w-4" />
                                                        </Button>
                                                    </div>
                                                )}
                                                {total > 0 && (
                                                    <>
                                                        <Button variant="outline" size="sm" onClick={() => handleEditDentalRecord(chartRecord)}>
                                                            <Edit className="h-4 w-4 mr-1" /> {t('common.edit')}
                                                        </Button>
                                                        <Button variant="outline" size="sm" onClick={() => handlePrintDentalChart(chartRecord)}>
                                                            <Printer className="h-4 w-4 mr-1" /> {t('common.print')}
                                                        </Button>
                                                    </>
                                                )}
                                                <Button size="sm" onClick={() => { setFormMode('new'); setSelectedRecord(null); setOpenDentalForm(true); }}>
                                                    + {t('patientDetails.newDentalRecord')}
                                                </Button>
                                            </div>
                                        </div>
                                    </CardHeader>
                                    <CardContent>
                                        {total === 0 ? (
                                            <div className="text-center py-16 text-muted-foreground space-y-3">
                                                <p className="text-base">{t('patientDetails.noDentalRecordsYet')}</p>
                                                <Button onClick={() => { setFormMode('new'); setSelectedRecord(null); setOpenDentalForm(true); }}>
                                                    {t('patientDetails.createFirstDentalRecord')}
                                                </Button>
                                            </div>
                                        ) : (
                                            <div className="space-y-6">
                                                {/* Legend */}
                                                <div className="flex flex-wrap gap-3 text-xs text-slate-600">
                                                    {[
                                                        { label: t('patientDetails.healthy'), dot: 'bg-white border-slate-400' },
                                                        { label: t('patientDetails.decay'), dot: 'bg-red-400' },
                                                        { label: t('patientDetails.filled'), dot: 'bg-blue-400' },
                                                        { label: t('patientDetails.missing'), dot: 'bg-slate-800' },
                                                        { label: t('patientDetails.exodontia'), dot: 'bg-red-600' },
                                                        { label: t('patientDetails.crown'), dot: 'bg-yellow-400' },
                                                        { label: t('patientDetails.rootCanal'), dot: 'bg-purple-400' },
                                                        { label: t('patientDetails.implant'), dot: 'bg-emerald-500' },
                                                    ].map(({ label, dot }) => (
                                                        <span key={label} className="flex items-center gap-1.5">
                                                            <span className={`inline-block w-3 h-3 rounded-full border ${dot}`} />
                                                            {label}
                                                        </span>
                                                    ))}
                                                </div>

                                                {/* Readonly odontogram */}
                                                <InteractiveOdontogram
                                                    key={`chart-${safeIndex}`}
                                                    initialData={chartTeeth}
                                                    readonly
                                                />

                                                {/* Record details */}
                                                {(chartRecord?.treatmentPlan || chartRecord?.odontogramNotes || chartRecord?.radiographicAnalysis || (Array.isArray(chartRecord?.procedures) && chartRecord.procedures.some((p: any) => p?.procedure || p?.date || p?.totalPaid))) && (
                                                    <div className="border-t pt-4 grid sm:grid-cols-2 gap-4 text-sm overflow-hidden">
                                                        {Array.isArray(chartRecord?.procedures) && chartRecord.procedures.some((p: any) => p?.procedure || p?.date || p?.totalPaid) && (
                                                            <div className="sm:col-span-2 min-w-0">
                                                                <p className="font-semibold text-slate-700 mb-2">{t('dentalRecord.proceduresPerformed')}</p>
                                                                <div className="space-y-2">
                                                                    {chartRecord.procedures
                                                                        .filter((p: any) => p?.procedure || p?.date || p?.totalPaid)
                                                                        .map((p: any, i: number) => (
                                                                            <div key={`procedure-${i}`} className="border rounded-md p-3 bg-slate-50 min-w-0">
                                                                                <p className="font-medium text-slate-700 mb-1">{t('dentalRecord.procedureEntry')} {i + 1}</p>
                                                                                <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-slate-600 min-w-0">
                                                                                    <p className="break-all [overflow-wrap:anywhere]"><span className="font-medium text-slate-700">{t('dentalRecord.procedurePerformed')}:</span> {p.procedure || '-'}</p>
                                                                                    <p><span className="font-medium text-slate-700">{t('dentalRecord.procedureDate')}:</span> {p.date ? formatDate(p.date) : '-'}</p>
                                                                                    <p className="break-all [overflow-wrap:anywhere]"><span className="font-medium text-slate-700">{t('dentalRecord.totalPaid')}:</span> {p.totalPaid || '-'}</p>
                                                                                </div>
                                                                            </div>
                                                                        ))}
                                                                </div>
                                                            </div>
                                                        )}
                                                        {chartRecord.treatmentPlan && (
                                                            <div className="sm:col-span-2 min-w-0">
                                                                <p className="font-semibold text-slate-700 mb-1">{t('dentalRecord.treatmentPlan')}</p>
                                                                <p className="text-slate-600 whitespace-pre-line break-all [overflow-wrap:anywhere]">{chartRecord.treatmentPlan}</p>
                                                            </div>
                                                        )}
                                                        {chartRecord.odontogramNotes && (
                                                            <div className="sm:col-span-2 min-w-0">
                                                                <p className="font-semibold text-slate-700 mb-1">{t('patientDetails.odontogramNotes')}</p>
                                                                <p className="text-slate-600 whitespace-pre-line break-all [overflow-wrap:anywhere]">{chartRecord.odontogramNotes}</p>
                                                            </div>
                                                        )}
                                                        {chartRecord.radiographicAnalysis && (
                                                            <div className="sm:col-span-2 min-w-0">
                                                                <p className="font-semibold text-slate-700 mb-1">{t('patientDetails.radiographicAnalysis')}</p>
                                                                <p className="text-slate-600 whitespace-pre-line break-all [overflow-wrap:anywhere]">{chartRecord.radiographicAnalysis}</p>
                                                            </div>
                                                        )}
                                                    </div>
                                                )}
                                            </div>
                                        )}
                                    </CardContent>
                                </Card>
                            );
                        })()}
                    </TabsContent>
                )}
            </Tabs >

            <Dialog open={openClinicalForm} onOpenChange={setOpenClinicalForm}>
                <DialogContent className="h-[100dvh] w-screen max-w-none rounded-none p-3 sm:h-auto sm:w-full sm:max-w-6xl sm:rounded-lg sm:p-6 max-h-[100dvh] sm:max-h-[90vh] overflow-y-auto overflow-x-hidden">
                    <DialogHeader className="pr-8 text-left">
                        <DialogTitle>
                            {formMode === 'view' ? t('patientDetails.viewMedicalConsultation') : formMode === 'edit' ? t('patientDetails.editMedicalConsultation') : t('patientDetails.newMedicalConsultation')}
                        </DialogTitle>
                        <DialogDescription>
                            {formMode === 'view'
                                ? t('patientDetails.viewMedicalConsultationDesc')
                                : formMode === 'edit'
                                    ? t('patientDetails.editMedicalConsultationDesc')
                                    : t('patientDetails.createMedicalConsultationDesc')}
                        </DialogDescription>
                    </DialogHeader>
                    {patient._id && (
                        <ClinicalRecordForm
                            patientId={patient._id}
                            patient={patient}
                            initialData={formMode !== 'new' ? selectedRecord : undefined}
                            viewOnly={formMode === 'view'}
                            recordId={formMode !== 'new' ? selectedRecord?._id : undefined}
                            onSuccess={() => {
                                setOpenClinicalForm(false);
                                setSelectedRecord(null);
                                setFormMode('new');
                                refreshPatient();
                            }}
                            onCancel={() => {
                                setOpenClinicalForm(false);
                                setSelectedRecord(null);
                                setFormMode('new');
                            }}
                        />
                    )}
                </DialogContent>
            </Dialog>

            <Dialog open={openDentalForm} onOpenChange={setOpenDentalForm}>
                <DialogContent className="w-[98vw] sm:max-w-7xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>
                            {formMode === 'view' ? t('patientDetails.viewDentalRecord') : formMode === 'edit' ? t('patientDetails.editDentalRecord') : t('patientDetails.newDentalRecord')}
                        </DialogTitle>
                        <DialogDescription>
                            {formMode === 'view'
                                ? t('patientDetails.viewDentalRecordDesc')
                                : formMode === 'edit'
                                    ? t('patientDetails.editDentalRecordDesc')
                                    : t('patientDetails.createDentalRecordDesc')}
                        </DialogDescription>
                    </DialogHeader>
                    {patient._id && (
                        <DentalRecordForm
                            patientId={patient._id}
                            patient={patient}
                            initialData={formMode !== 'new' ? selectedRecord : undefined}
                            viewOnly={formMode === 'view'}
                            recordId={formMode !== 'new' ? selectedRecord?._id : undefined}
                            onSuccess={() => {
                                setOpenDentalForm(false);
                                setSelectedRecord(null);
                                setFormMode('new');
                                refreshPatient();
                            }}
                            onCancel={() => {
                                setOpenDentalForm(false);
                                setSelectedRecord(null);
                                setFormMode('new');
                            }}
                        />
                    )}
                </DialogContent>
            </Dialog>

            {/* New Prescription / Certification Modal */}
            <Dialog open={openPrescriptionNew} onOpenChange={setOpenPrescriptionNew}>
                <DialogContent className="sm:max-w-3xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>{newDocumentType === 'Certification' ? t('patientDetails.newCertification') : t('patientDetails.newPrescription')}</DialogTitle>
                        <DialogDescription>
                            {newDocumentType === 'Certification' ? t('patientDetails.createCertificationDesc') : t('patientDetails.createPrescriptionDesc')}
                        </DialogDescription>
                    </DialogHeader>
                    {patient._id && (
                        <PrescriptionForm
                            patientId={patient._id}
                            initialData={newDocumentType ? { documentType: newDocumentType } : undefined}
                            onSuccess={() => {
                                setOpenPrescriptionNew(false);
                                api.prescriptions.getByPatientId(patient._id).then(res => {
                                    if (res.success && res.data) setPrescriptions(res.data);
                                });
                            }}
                            onCancel={() => setOpenPrescriptionNew(false)}
                        />
                    )}
                </DialogContent>
            </Dialog>

            {/* View Prescription Modal */}
            <Dialog open={!!viewPrescription} onOpenChange={(open) => { if (!open) setViewPrescription(null); }}>
                <DialogContent className="sm:max-w-3xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            {t('patientDetails.prescriptionDetails')}
                            {viewPrescription?.documentType && viewPrescription.documentType !== 'Prescription' && (
                                <Badge variant="secondary" className="text-xs">
                                    {(() => {
                                        switch (viewPrescription.documentType) {
                                            case 'Referral': return t('prescriptions.documentTypeReferral');
                                            case 'Certification': return t('prescriptions.documentTypeCertification');
                                            case 'Medical Leave': return t('prescriptions.documentTypeMedicalLeave');
                                            case 'Laboratory': return t('prescriptions.documentTypeLaboratory');
                                            case 'Imaging': return t('prescriptions.documentTypeImaging');
                                            default: return viewPrescription.documentType;
                                        }
                                    })()}
                                </Badge>
                            )}
                        </DialogTitle>
                        <DialogDescription>
                            {viewPrescription?.createdAt ? formatDate(viewPrescription.createdAt) : ''}
                        </DialogDescription>
                    </DialogHeader>
                    {viewPrescription && (
                        <div className="space-y-6">
                            {viewPrescription.diagnosis && (
                                <div className="space-y-2">
                                    <h3 className="text-lg font-bold text-slate-800 border-b border-slate-100 pb-2">{t('patientDetails.diagnosisLabel')}</h3>
                                    <p className="text-base">{viewPrescription.diagnosis}</p>
                                </div>
                            )}

                            {(!viewPrescription.documentType || viewPrescription.documentType === 'Prescription') && (
                                <div className="space-y-2">
                                    <h3 className="text-lg font-bold text-slate-800 border-b border-slate-100 pb-2">{t('patientDetails.medicationsLabel')}</h3>
                                    {viewPrescription.medications?.length > 0 ? (
                                        <div className="space-y-3">
                                            {viewPrescription.medications.map((med: any, i: number) => (
                                                <div key={i} className="border rounded-lg p-4 bg-slate-50">
                                                    <p className="text-base font-semibold text-slate-700">{med.name}</p>
                                                    <div className="flex gap-4 text-sm text-slate-500 mt-1">
                                                        {med.dosage && <span>{t('prescriptions.dosage')}: {med.dosage}</span>}
                                                        {med.frequency && <span>{t('prescriptions.frequency')}: {med.frequency}</span>}
                                                        {med.duration && <span>{t('prescriptions.duration')}: {med.duration}</span>}
                                                    </div>
                                                    {med.instructions && (
                                                        <p className="text-sm text-slate-400 mt-1">{med.instructions}</p>
                                                    )}
                                                </div>
                                            ))}
                                        </div>
                                    ) : (
                                        <p className="text-slate-500">{t('patientDetails.noMedicationsListed')}</p>
                                    )}
                                </div>
                            )}

                            {viewPrescription.documentType && viewPrescription.documentType !== 'Prescription' && viewPrescription.freeText && (
                                <div className="space-y-2">
                                    <h3 className="text-lg font-bold text-slate-800 border-b border-slate-100 pb-2">{t('prescriptions.freeText')}</h3>
                                    <p className="whitespace-pre-wrap break-words overflow-hidden text-base bg-slate-50 rounded-lg p-4 border">{viewPrescription.freeText}</p>
                                </div>
                            )}

                            {viewPrescription.notes && (
                                <div className="space-y-2">
                                    <h3 className="text-lg font-bold text-slate-800 border-b border-slate-100 pb-2">{t('patientDetails.notes')}</h3>
                                    <p className="whitespace-pre-wrap break-words text-base">{viewPrescription.notes}</p>
                                </div>
                            )}

                            {(viewPrescription.doctorId?.userId?.firstName || user?.firstName) && (
                                <div className="space-y-2">
                                    <h3 className="text-lg font-bold text-slate-800 border-b border-slate-100 pb-2">{t('patientDetails.prescribedBy')}</h3>
                                    <p className="text-base font-semibold text-slate-700">
                                        {viewPrescription.doctorId?.userId?.firstName
                                            ? `${viewPrescription.doctorId.userId.firstName} ${viewPrescription.doctorId.userId.lastName}`
                                            : `${user?.firstName} ${user?.lastName || ''}`}
                                    </p>
                                </div>
                            )}

                            <div className="flex justify-end gap-3 pt-4 border-t border-slate-100">
                                <Button variant="outline" onClick={() => { setViewPrescription(null); setEditPrescription(viewPrescription); }}>
                                    <Edit className="h-4 w-4 mr-1" /> {t('common.edit')}
                                </Button>
                                <Button variant="outline" onClick={() => handlePrintPrescription(viewPrescription)}>
                                    <Printer className="h-4 w-4 mr-1" /> {t('common.print')}
                                </Button>
                            </div>
                        </div>
                    )}
                </DialogContent>
            </Dialog>

            {/* Edit Prescription Modal */}
            <Dialog open={!!editPrescription} onOpenChange={(open) => { if (!open) setEditPrescription(null); }}>
                <DialogContent className="sm:max-w-3xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>{t('patientDetails.editPrescription')}</DialogTitle>
                        <DialogDescription>
                            {t('patientDetails.editPrescriptionDesc')}
                        </DialogDescription>
                    </DialogHeader>
                    {editPrescription && (
                        <PrescriptionForm
                            patientId={patient._id}
                            initialData={{
                                _id: editPrescription._id,
                                documentType: editPrescription.documentType || 'Prescription',
                                medications: Array.isArray(editPrescription.medications) ? editPrescription.medications : [],
                                diagnosis: editPrescription.diagnosis || '',
                                freeText: editPrescription.freeText || '',
                                notes: editPrescription.notes || '',
                            }}
                            onSuccess={() => {
                                setEditPrescription(null);
                                api.prescriptions.getByPatientId(patient._id).then(res => {
                                    if (res.success && res.data) setPrescriptions(res.data);
                                });
                            }}
                            onCancel={() => setEditPrescription(null)}
                        />
                    )}
                </DialogContent>
            </Dialog>

            <Dialog open={openEditProfile} onOpenChange={setOpenEditProfile}>
                <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>{t('patientDetails.editPatientProfile')}</DialogTitle>
                        <DialogDescription>
                            {t('patientDetails.updatePatientInfo')}
                        </DialogDescription>
                    </DialogHeader>
                    <PatientForm
                        initialData={patient}
                        onSuccess={() => {
                            setOpenEditProfile(false);
                            refreshPatient();
                        }}
                        onCancel={() => setOpenEditProfile(false)}
                    />
                </DialogContent>
            </Dialog>

            <Dialog
                open={openAddExam}
                onOpenChange={(open) => {
                    setOpenAddExam(open);
                    if (!open) resetExamForm();
                }}
            >
                <DialogContent className="sm:max-w-2xl">
                    <DialogHeader>
                        <DialogTitle>{isEditingExam ? t('common.edit') : t('patientDetails.addExam')}</DialogTitle>
                        <DialogDescription>{t('patientDetails.examsDescription')}</DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleAddExam} className="space-y-4">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="exam-name">{t('patientDetails.examName')}</Label>
                                <Input
                                    id="exam-name"
                                    value={examForm.name}
                                    onChange={(e) => setExamForm(prev => ({ ...prev, name: e.target.value }))}
                                    required
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="exam-type">{t('patientDetails.examType')}</Label>
                                <Input
                                    id="exam-type"
                                    value={examForm.type}
                                    onChange={(e) => setExamForm(prev => ({ ...prev, type: e.target.value }))}
                                    placeholder={t('patientDetails.examTypePlaceholder')}
                                    required
                                />
                            </div>
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="exam-result">{t('patientDetails.result')}</Label>
                            <Input
                                id="exam-result"
                                value={examForm.result}
                                onChange={(e) => setExamForm(prev => ({ ...prev, result: e.target.value }))}
                                required
                            />
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="exam-date">{t('patientDetails.examDate')}</Label>
                                <Input
                                    id="exam-date"
                                    type="date"
                                    value={examForm.date}
                                    onChange={(e) => setExamForm(prev => ({ ...prev, date: e.target.value }))}
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="exam-file">{t('patientDetails.examImage')}</Label>
                                <Input
                                    id="exam-file"
                                    type="file"
                                    accept="image/*"
                                    onChange={(e) => setExamFile(e.target.files?.[0] || null)}
                                    required={!isEditingExam}
                                />
                            </div>
                        </div>
                        {isEditingExam && examForm.fileUrl && (
                            <div className="rounded-md border bg-slate-50 p-3 space-y-2">
                                <p className="text-xs font-medium text-slate-600">{t('patientDetails.currentAttachment')}</p>
                                <Button type="button" variant="link" className="h-auto p-0" asChild>
                                    <a href={getAbsoluteFileUrl(examForm.fileUrl)} target="_blank" rel="noopener noreferrer">
                                        {t('patientDetails.openAttachment')}
                                    </a>
                                </Button>
                                {/\.(jpg|jpeg|png|gif|webp|bmp|svg)$/i.test(examForm.fileUrl) && (
                                    <div className="w-full max-w-xs sm:max-w-sm aspect-[4/5] overflow-hidden rounded border bg-white">
                                        <img
                                            src={getAbsoluteFileUrl(examForm.fileUrl)}
                                            alt={t('patientDetails.currentExamAttachment')}
                                            className="h-full w-full object-cover"
                                        />
                                    </div>
                                )}
                            </div>
                        )}

                        <div className="space-y-2">
                            <Label htmlFor="exam-notes">{t('patientDetails.notes')}</Label>
                            <Input
                                id="exam-notes"
                                value={examForm.notes}
                                onChange={(e) => setExamForm(prev => ({ ...prev, notes: e.target.value }))}
                            />
                        </div>

                        <div className="flex justify-end gap-2 pt-2">
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => {
                                    setOpenAddExam(false);
                                    resetExamForm();
                                }}
                            >
                                {t('common.cancel')}
                            </Button>
                            <Button type="submit" disabled={savingExam}>
                                {savingExam ? t('common.saving') : (isEditingExam ? t('common.save') : t('patientDetails.saveExam'))}
                            </Button>
                        </div>
                    </form>
                </DialogContent>
            </Dialog>

            <Dialog
                open={openAddDocument}
                onOpenChange={(open) => {
                    setOpenAddDocument(open);
                    if (!open) resetDocumentForm();
                }}
            >
                <DialogContent className="sm:max-w-2xl">
                    <DialogHeader>
                        <DialogTitle>{isEditingDocument ? t('common.edit') : t('patientDetails.addDocument')}</DialogTitle>
                        <DialogDescription>{t('patientDetails.documentsDescription')}</DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleAddDocument} className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="doc-name">{t('patientDetails.documentName')}</Label>
                            <Input
                                id="doc-name"
                                value={documentForm.name}
                                onChange={(e) => setDocumentForm(prev => ({ ...prev, name: e.target.value }))}
                                required
                            />
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="doc-url">{t('patientDetails.documentImage')}</Label>
                            <Input
                                id="doc-url"
                                type="file"
                                accept="image/*"
                                onChange={(e) => setDocumentFile(e.target.files?.[0] || null)}
                                required={!isEditingDocument}
                            />
                        </div>
                        {isEditingDocument && documentForm.url && (
                            <div className="rounded-md border bg-slate-50 p-3 space-y-2">
                                <p className="text-xs font-medium text-slate-600">{t('patientDetails.currentAttachment')}</p>
                                <Button type="button" variant="link" className="h-auto p-0" asChild>
                                    <a href={getAbsoluteFileUrl(documentForm.url)} target="_blank" rel="noopener noreferrer">
                                        {t('patientDetails.openDocument')}
                                    </a>
                                </Button>
                                {/\.(jpg|jpeg|png|gif|webp|bmp|svg)$/i.test(documentForm.url) && (
                                    <div className="w-full max-w-xs sm:max-w-sm aspect-[4/5] overflow-hidden rounded border bg-white">
                                        <img
                                            src={getAbsoluteFileUrl(documentForm.url)}
                                            alt={t('patientDetails.currentDocumentAttachment')}
                                            className="h-full w-full object-cover"
                                        />
                                    </div>
                                )}
                            </div>
                        )}

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="doc-date">{t('patientDetails.examDate')}</Label>
                                <Input
                                    id="doc-date"
                                    type="date"
                                    value={documentForm.date}
                                    onChange={(e) => setDocumentForm(prev => ({ ...prev, date: e.target.value }))}
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="doc-category">{t('patientDetails.category')}</Label>
                                <Input
                                    id="doc-category"
                                    value={documentForm.category}
                                    onChange={(e) => setDocumentForm(prev => ({ ...prev, category: e.target.value }))}
                                    placeholder={t('patientDetails.categoryPlaceholder')}
                                />
                            </div>
                        </div>

                        <div className="flex justify-end gap-2 pt-2">
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => {
                                    setOpenAddDocument(false);
                                    resetDocumentForm();
                                }}
                            >
                                {t('common.cancel')}
                            </Button>
                            <Button type="submit" disabled={savingDocument}>
                                {savingDocument ? t('common.saving') : (isEditingDocument ? t('common.save') : t('patientDetails.saveDocument'))}
                            </Button>
                        </div>
                    </form>
                </DialogContent>
            </Dialog>
        </div >
    )
}
