'use client';

import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Separator } from '@/components/ui/separator';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useAuthStore } from '@/lib/auth-store';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { formatGenderForPrint, getDoctorPrintData, printRecord } from '@/lib/print-service';
import { Activity, Calendar, Edit, Eye, FileText, Loader2, Pill, Printer, Star } from 'lucide-react';
import { useEffect, useState } from 'react';
import SurveyList from '../Survey/SurveyList';
import InteractiveOdontogram from './InteractiveOdontogram';

interface PatientRecordsViewProps {
    patientId: string;
}

export default function PatientRecordsView({ patientId }: PatientRecordsViewProps) {
    const { user, isLoading: authLoading } = useAuthStore();
    const { t, language } = useLanguage();
    const [patient, setPatient] = useState<any>(null);
    const [prescriptions, setPrescriptions] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [selectedRecord, setSelectedRecord] = useState<any>(null);
    const [selectedRecordType, setSelectedRecordType] = useState<'clinical' | 'dental' | 'prescription' | null>(null);
    const [prescriptionPage, setPrescriptionPage] = useState(1);
    const prescriptionsPerPage = 5;

    // Check if the current user is a dentist
    const isDentist = !authLoading && (user?.isDentist === true || user?.role === 'dentist');

    useEffect(() => {
        if (patientId) {
            setLoading(true);
            Promise.all([
                fetch(`${API_BASE_URL}/api/patients/${patientId}`).then(res => res.json()),
                fetch(`${API_BASE_URL}/api/prescriptions/patient/${patientId}`).then(res => res.json())
            ])
                .then(([patientData, prescriptionData]) => {
                    if (patientData.success) {
                        setPatient(patientData.data);
                    }
                    if (prescriptionData.success) {
                        setPrescriptions(prescriptionData.data);
                    }
                })
                .catch(err => console.error(err))
                .finally(() => setLoading(false));
        }
    }, [patientId]);

    const formatDate = (d: string) => {
        if (!d) return t('common.na');
        return new Date(d).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
        });
    };

    const isStandardPrescription = (record: any) => !record?.documentType || record.documentType === 'Prescription';

    const getPrescriptionDocumentTypeLabel = (documentType?: string) => {
        switch (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 handleRecordClick = (record: any, type: 'clinical' | 'dental' | 'prescription') => {
        setSelectedRecord(record);
        setSelectedRecordType(type);
    };

    const handlePrint = (record: any, type: 'clinical' | 'dental' | 'prescription', e: React.MouseEvent) => {
        e.stopPropagation();

        const { doctor, clinic } = getDoctorPrintData(record, user, {
            doctor: t('common.doctor'),
        });

        let content = '';
        let recordTitle = '';
        let recordType = '';
        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();
        };

        if (type === 'clinical') {
            recordType = t('patientDetails.activities.consultation');
            recordTitle = record.title || t('patientDetails.medicalConsultationRecord');

            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 class="label" style="font-size: 11px; color: #64748b;">${t('patientDetails.bloodPressure')}</div><div style="font-weight: 600;">${record.vitalSigns.bp || '-'}</div></div>
                        <div><div class="label" style="font-size: 11px; color: #64748b;">${t('patientDetails.heartRate')}</div><div style="font-weight: 600;">${record.vitalSigns.hr || '-'}</div></div>
                        <div><div class="label" style="font-size: 11px; color: #64748b;">${t('patientDetails.respiratoryRate')}</div><div style="font-weight: 600;">${record.vitalSigns.rr || '-'}</div></div>
                        <div><div class="label" style="font-size: 11px; color: #64748b;">${t('patientDetails.temperature')}</div><div style="font-weight: 600;">${record.vitalSigns.temp || '-'}</div></div>
                        <div><div class="label" 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(([_, value]) => value && typeof value === 'string' && value.trim() !== '')
                .map(([key, value]) => `
                    <div style="margin-bottom: 10px;">
                        <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('patientDetails.medicalHistory')}</div>
                    ${historyContent}
                </div>
            ` : '';

            const examContent = record.physicalExamination ? Object.entries(record.physicalExamination)
                .filter(([_, value]) => value && typeof value === 'string' && value.trim() !== '')
                .map(([key, value]) => `
                    <div style="margin-bottom: 10px;">
                        <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 diagnoses = record.diagnoses && 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>
            ` : '';

            content = `
                <div class="section">
                    <div class="section-title">${t('patientDetails.viewMedicalConsultation')}</div>
                    <div style="margin-bottom: 15px;">
                        <div style="font-weight: 600; color: #475569; margin-bottom: 4px;">${t('clinicalRecord.chiefComplaint')}</div>
                        <div style="background: #f1f5f9; padding: 10px; border-radius: 6px;">
                            ${record.chiefComplaint || record.reasonForConsultation || t('common.na')}
                        </div>
                    </div>
                    ${record.historyOfPresentIllness ? `
                    <div style="margin-bottom: 15px;">
                        <div style="font-weight: 600; color: #475569; margin-bottom: 4px;">${t('clinicalRecord.hpi')}</div>
                        <div>${record.historyOfPresentIllness}</div>
                    </div>` : ''}
                </div>

                ${vitals}
                ${historySection}
                ${examSection}
                ${diagnoses}

                <div class="section">
                    <div class="section-title">${t('clinicalRecord.plan')}</div>
                    <div class="notes">${record.plan || record.comments || t('patientDetails.none')}</div>
                </div>
            `;
        } else if (type === 'dental') {
            recordType = t('patientDetails.activities.dentalRecord');
            recordTitle = t('patientDetails.viewDentalRecord');
            content = `
                <div class="section">
                    <div class="section-title">${t('dentalRecord.treatmentPlan')}</div>
                    <div class="notes">${record.treatmentPlan || t('common.na')}</div>
                </div>
            `;
        } else {
            const isPrescription = isStandardPrescription(record);
            const documentTypeLabel = getPrescriptionDocumentTypeLabel(record.documentType);
            recordType = isPrescription ? t('patientDetails.activities.prescription') : documentTypeLabel;
            recordTitle = isPrescription ? t('prescriptions.medicalPrescription') : documentTypeLabel;

            const meds = isPrescription
                ? (record.medications?.length > 0
                    ? record.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="padding:12px;text-align:center;color:#94a3b8;">${t('patientDetails.noMedicationsListed')}</td></tr>`)
                : '';

            content = `
                ${record.diagnosis ? `
                <div class="section">
                    <div class="section-title">${t('patientDetails.diagnosisLabel')}</div>
                    <div class="diagnosis-text">${record.diagnosis}</div>
                </div>` : ''}

                ${isPrescription ? `
                <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>` : ''}

                ${!isPrescription && record.freeText ? `
                <div class="section">
                    <div class="section-title">${t('prescriptions.freeText')}</div>
                    <div class="notes">${record.freeText}</div>
                </div>` : ''}

                ${record.notes ? `
                <div class="section">
                    <div class="section-title">${t('patientDetails.notes')}</div>
                    <div class="notes">${record.notes}</div>
                </div>` : ''}
            `;
        }

        const patientName = `${patient.userId?.firstName} ${patient.userId?.lastName}`;
        const patientDob = patient.dateOfBirth ? new Date(patient.dateOfBirth).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US', { timeZone: 'UTC' }) : t('common.na');
        const patientGender = formatGenderForPrint(patient.gender, {
            male: t('common.male'),
            female: t('common.female'),
            other: t('common.other'),
        }) || t('common.na');

        printRecord({
            doctor,
            clinic,
            patient: {
                name: patientName,
                dob: patientDob,
                gender: patientGender,
                phone: patient.userId?.phone || '',
                id: patient.nationalId,
            },
            record: {
                date: new Date(record.date || record.createdAt).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US'),
                type: recordType,
                title: recordTitle
            },
            labels: {
                patient: t('common.patient'),
                phone: t('common.phone'),
                gender: t('common.gender'),
                dob: t('common.dob'),
                id: t('common.id'),
                insurance: t('medicalRecord.insurance'),
                doctor: t('common.doctor'),
                licenseNumber: t('common.licenseNumber'),
            },
            content
        });
    };

    const handleEdit = (record: any, type: 'clinical' | 'dental' | 'prescription', e: React.MouseEvent) => {
        e.stopPropagation();
        // TODO: Navigate to edit page or open edit modal
        console.log('Edit record:', record, type);
    };

    const renderBooleanList = (data: any, labels: Record<string, string>) => {
        if (!data) return null;
        const active = Object.keys(labels).filter(key => data[key]);
        if (active.length === 0) return <span className="text-slate-500 italic">{t('patientDetails.none')}</span>;
        return (
            <div className="flex flex-wrap gap-2">
                {active.map(key => (
                    <Badge key={key} variant="secondary" className="bg-slate-100 text-slate-700">
                        {labels[key]}
                    </Badge>
                ))}
            </div>
        );
    };

    if (loading) {
        return (
            <div className="flex flex-col items-center justify-center p-12 space-y-4">
                <Loader2 className="h-8 w-8 animate-spin text-primary" />
                <p className="text-muted-foreground">{t('patientDetails.loading')}</p>
            </div>
        );
    }

    if (!patient) {
        return <div className="p-8 text-center text-red-500">{t('patientDetails.notFound').replace('{id}', String(patientId))}</div>;
    }

    const selectedPrescriptionIsStandard = selectedRecordType === 'prescription' && selectedRecord
        ? isStandardPrescription(selectedRecord)
        : false;
    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
    );

    return (
        <div className="space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center gap-4 border-b border-slate-100 pb-6">
                <div className="h-14 w-14 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 text-xl font-bold shrink-0">
                    {patient.userId?.firstName?.[0]}{patient.userId?.lastName?.[0]}
                </div>
                <div>
                    <h2 className="text-2xl font-bold text-slate-900">{patient.userId?.firstName} {patient.userId?.lastName}</h2>
                    <p className="text-sm text-slate-500">{t('patientDetails.recentActivity')} • {patient.userId?.email}</p>
                </div>
            </div>

            <Tabs defaultValue="clinical" className="w-full">
                <TabsList className={`grid w-full ${isDentist ? 'grid-cols-4' : 'grid-cols-3'} mb-6`}>
                    <TabsTrigger value="clinical" className="gap-2">
                        <Activity className="h-4 w-4" />
                        <span className="hidden sm:inline">{t('patientDetails.medicalConsultations')}</span>
                        <span className="sm:hidden">{t('patientDetails.medicalConsultations')}</span>
                    </TabsTrigger>
                    <TabsTrigger value="prescriptions" className="gap-2">
                        <Pill className="h-4 w-4" />
                        <span className="hidden sm:inline">{t('patientDetails.prescriptions')}</span>
                        <span className="sm:hidden">{t('patientDetails.prescriptionsAbbrev')}</span>
                    </TabsTrigger>
                    {isDentist && (
                        <TabsTrigger value="dental" className="gap-2">
                            <FileText className="h-4 w-4" />
                            <span className="hidden sm:inline">{t('patientDetails.dentalReports')}</span>
                            <span className="sm:hidden">{t('patientDetails.dentalReports')}</span>
                        </TabsTrigger>
                    )}
                    <TabsTrigger value="surveys" className="gap-2">
                        <Star className="h-4 w-4" />
                        <span className="hidden sm:inline">{t('survey.title')}</span>
                        <span className="sm:hidden">{t('survey.title')}</span>
                    </TabsTrigger>
                </TabsList>

                <TabsContent value="clinical" className="space-y-4 animate-in fade-in-50 slide-in-from-left-2">
                    <div className="flex items-center justify-between mb-2">
                        <h3 className="font-semibold text-lg">{t('patientDetails.medicalConsultations')}</h3>
                        <Badge variant="outline">{patient.clinicalRecords?.length || 0} {t('patientDetails.records')}</Badge>
                    </div>

                    <div className="h-[400px] overflow-y-auto pr-4">
                        {patient.clinicalRecords?.length ? (
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                {patient.clinicalRecords.map((record: any, i: number) => (
                                    <Card
                                        key={i}
                                        className="overflow-hidden border-l-4 border-l-blue-500 hover:shadow-lg transition-all cursor-pointer group"
                                        onClick={() => handleRecordClick(record, 'clinical')}
                                    >
                                        <CardHeader className="pb-2 bg-slate-50/30 group-hover:bg-blue-50/30 transition-colors">
                                            <CardTitle className="text-sm font-medium flex justify-between items-center text-slate-700">
                                                <div className="flex items-center gap-2">
                                                    <Calendar className="h-3 w-3" />
                                                    {formatDate(record.date || record.createdAt)}
                                                </div>
                                                <Badge className="bg-blue-100 text-blue-700 border-0">
                                                    {t('patientDetails.visit')} #{patient.clinicalRecords.length - i}
                                                </Badge>
                                            </CardTitle>
                                        </CardHeader>
                                        <CardContent className="pt-4 space-y-3 text-sm">
                                            <div className="min-h-[60px]">
                                                <div className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">{t('clinicalRecord.formTitleLabel')}</div>
                                                <div className="font-semibold text-slate-900 line-clamp-2 mb-2">{record.title || t('clinicalRecord.title')}</div>
                                                <div className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">{t('clinicalRecord.chiefComplaint')}</div>
                                                <div className="font-medium text-slate-900 line-clamp-3">{record.chiefComplaint || record.reasonForConsultation || t('common.na')}</div>
                                            </div>
                                            <div className="flex items-center justify-between gap-1 pt-2 border-t">
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    className="h-8 px-2 text-blue-600 hover:text-blue-700 hover:bg-blue-50 flex-1"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        handleRecordClick(record, 'clinical');
                                                    }}
                                                >
                                                    <Eye className="h-4 w-4 mr-1" />
                                                    <span className="hidden sm:inline">{t('common.view')}</span>
                                                </Button>
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    className="h-8 px-2 text-amber-600 hover:text-amber-700 hover:bg-amber-50 flex-1"
                                                    onClick={(e) => handleEdit(record, 'clinical', e)}
                                                >
                                                    <Edit className="h-4 w-4 mr-1" />
                                                    <span className="hidden sm:inline">{t('common.edit')}</span>
                                                </Button>
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    className="h-8 px-2 text-slate-600 hover:text-slate-700 hover:bg-slate-50 flex-1"
                                                    onClick={(e) => handlePrint(record, 'clinical', e)}
                                                >
                                                    <Printer className="h-4 w-4 mr-1" />
                                                    <span className="hidden sm:inline">{t('common.print')}</span>
                                                </Button>
                                            </div>
                                        </CardContent>
                                    </Card>
                                ))}
                            </div>
                        ) : (
                                <div className="flex flex-col items-center justify-center h-40 text-slate-400 border-2 border-dashed rounded-xl bg-slate-50">
                                    <Activity className="h-8 w-8 mb-2 opacity-50" />
                                    <p>{t('patientDetails.noMedicalRecords')}</p>
                                </div>
                            )}
                        </div>
                    </TabsContent>

                {isDentist && (
                    <TabsContent value="dental" className="space-y-4 animate-in fade-in-50 slide-in-from-right-2">
                        <div className="flex items-center justify-between mb-2">
                            <h3 className="font-semibold text-lg">{t('dentalRecord.dentalHistory')}</h3>
                            <Badge variant="outline">{patient.dentalRecords?.length || 0} {t('patientDetails.records')}</Badge>
                        </div>

                        <div className="h-[400px] overflow-y-auto pr-4">
                            {patient.dentalRecords?.length ? (
                                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                    {patient.dentalRecords.map((record: any, i: number) => (
                                        <Card
                                            key={i}
                                            className="overflow-hidden border-l-4 border-l-emerald-500 hover:shadow-lg transition-all cursor-pointer group"
                                            onClick={() => handleRecordClick(record, 'dental')}
                                        >
                                            <CardHeader className="pb-2 bg-slate-50/30 group-hover:bg-emerald-50/30 transition-colors">
                                                <CardTitle className="text-sm font-medium flex justify-between items-center text-slate-700">
                                                    <div className="flex items-center gap-2">
                                                        <Calendar className="h-3 w-3" />
                                                        {formatDate(record.date || record.createdAt)}
                                                    </div>
                                                    <Badge className="bg-emerald-100 text-emerald-700 border-0">
                                                        {t('patientDetails.recordNumber')} {patient.dentalRecords.length - i}
                                                    </Badge>
                                                </CardTitle>
                                            </CardHeader>
                                            <CardContent className="pt-4 space-y-3 text-sm">
                                                <div>
                                                    <div className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">{t('dentalRecord.treatmentPlan')}</div>
                                                    <div className="font-medium text-slate-900 line-clamp-2">{record.treatmentPlan || t('common.na')}</div>
                                                </div>
                                                <div className="flex items-center justify-between gap-2 pt-2 border-t">
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        className="h-8 px-2 text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50"
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            handleRecordClick(record, 'dental');
                                                        }}
                                                    >
                                                        <Eye className="h-4 w-4 mr-1" />
                                                        {t('common.view')}
                                                    </Button>
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        className="h-8 px-2 text-amber-600 hover:text-amber-700 hover:bg-amber-50"
                                                        onClick={(e) => handleEdit(record, 'dental', e)}
                                                    >
                                                        <Edit className="h-4 w-4 mr-1" />
                                                        {t('common.edit')}
                                                    </Button>
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        className="h-8 px-2 text-slate-600 hover:text-slate-700 hover:bg-slate-50"
                                                        onClick={(e) => handlePrint(record, 'dental', e)}
                                                    >
                                                        <Printer className="h-4 w-4 mr-1" />
                                                        {t('common.print')}
                                                    </Button>
                                                </div>
                                            </CardContent>
                                        </Card>
                                    ))}
                                </div>
                            ) : (
                                <div className="flex flex-col items-center justify-center h-40 text-slate-400 border-2 border-dashed rounded-xl bg-slate-50">
                                    <FileText className="h-8 w-8 mb-2 opacity-50" />
                                    <p>{t('patientDetails.noDentalReports')}</p>
                                </div>
                            )}
                        </div>
                    </TabsContent>
                )}

                <TabsContent value="surveys" className="space-y-4 animate-in fade-in-50 slide-in-from-right-2">
                    <div className="flex items-center justify-between mb-2">
                        <h3 className="font-semibold text-lg">{t('survey.title')}</h3>
                    </div>
                    <div className="h-[400px] overflow-y-auto pr-4">
                        <SurveyList patientId={patientId} />
                    </div>
                </TabsContent>

                <TabsContent value="prescriptions" className="space-y-4 animate-in fade-in-50 slide-in-from-right-2">
                    <div className="flex items-center justify-between mb-2">
                        <h3 className="font-semibold text-lg">{t('patientDetails.prescriptions')}</h3>
                        <Badge variant="outline">{prescriptions.length} {t('patientDetails.records')}</Badge>
                    </div>
                    <div className="h-[400px] overflow-y-auto pr-4">
                        {prescriptions.length ? (
                            <div className="space-y-4">
                                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                    {paginatedPrescriptions.map((record: any, i: number) => {
                                        const absoluteIndex = (currentPrescriptionPage - 1) * prescriptionsPerPage + i;
                                        return (
                                            <Card
                                                key={absoluteIndex}
                                                className="overflow-hidden border-l-4 border-l-purple-500 hover:shadow-lg transition-all cursor-pointer group"
                                                onClick={() => handleRecordClick(record, 'prescription')}
                                            >
                                                <CardHeader className="pb-2 bg-slate-50/30 group-hover:bg-purple-50/30 transition-colors">
                                                    <CardTitle className="text-sm font-medium flex justify-between items-center text-slate-700">
                                                        <div className="flex items-center gap-2">
                                                            <Calendar className="h-3 w-3" />
                                                            {formatDate(record.date || record.createdAt)}
                                                        </div>
                                                        <Badge className="bg-purple-100 text-purple-700 border-0">
                                                            {t('prescriptions.title')} #{prescriptions.length - absoluteIndex}
                                                        </Badge>
                                                    </CardTitle>
                                                </CardHeader>
                                                <CardContent className="pt-4 space-y-3 text-sm">
                                                    <div>
                                                        <div className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">{t('patientDetails.diagnosisLabel')}</div>
                                                        <div className="font-medium text-slate-900 line-clamp-2">{record.diagnosis || t('common.na')}</div>
                                                    </div>
                                                    <div className="flex items-center justify-between gap-2 pt-2 border-t">
                                                        <Button
                                                            variant="ghost"
                                                            size="sm"
                                                            className="h-8 px-2 text-purple-600 hover:text-purple-700 hover:bg-purple-50"
                                                            onClick={(e) => {
                                                                e.stopPropagation();
                                                                handleRecordClick(record, 'prescription');
                                                            }}
                                                        >
                                                            <Eye className="h-4 w-4 mr-1" />
                                                            {t('common.view')}
                                                        </Button>
                                                        <Button
                                                            variant="ghost"
                                                            size="sm"
                                                            className="h-8 px-2 text-amber-600 hover:text-amber-700 hover:bg-amber-50"
                                                            onClick={(e) => handleEdit(record, 'prescription', e)}
                                                        >
                                                            <Edit className="h-4 w-4 mr-1" />
                                                            {t('common.edit')}
                                                        </Button>
                                                        <Button
                                                            variant="ghost"
                                                            size="sm"
                                                            className="h-8 px-2 text-slate-600 hover:text-slate-700 hover:bg-slate-50"
                                                            onClick={(e) => handlePrint(record, 'prescription', e)}
                                                        >
                                                            <Printer className="h-4 w-4 mr-1" />
                                                            {t('common.print')}
                                                        </Button>
                                                    </div>
                                                </CardContent>
                                            </Card>
                                        );
                                    })}
                                </div>

                                {totalPrescriptionPages > 1 && (
                                    <div className="flex items-center justify-between border-t pt-3">
                                        <span className="text-xs text-slate-500">
                                            {t('common.page')} {currentPrescriptionPage} / {totalPrescriptionPages}
                                        </span>
                                        <div className="flex gap-2">
                                            <Button
                                                variant="outline"
                                                size="sm"
                                                disabled={currentPrescriptionPage === 1}
                                                onClick={() => setPrescriptionPage((prev) => Math.max(1, prev - 1))}
                                            >
                                                {t('common.previous')}
                                            </Button>
                                            <Button
                                                variant="outline"
                                                size="sm"
                                                disabled={currentPrescriptionPage === totalPrescriptionPages}
                                                onClick={() => setPrescriptionPage((prev) => Math.min(totalPrescriptionPages, prev + 1))}
                                            >
                                                {t('common.next')}
                                            </Button>
                                        </div>
                                    </div>
                                )}
                            </div>
                        ) : (
                                <div className="flex flex-col items-center justify-center h-40 text-slate-400 border-2 border-dashed rounded-xl bg-slate-50">
                                    <Pill className="h-8 w-8 mb-2 opacity-50" />
                                    <p>{t('patientDetails.noPrescriptions')}</p>
                                </div>
                            )}
                        </div>
                    </TabsContent>
            </Tabs>

            {/* Detailed View Dialog */}
            <Dialog open={!!selectedRecord} onOpenChange={(open) => !open && setSelectedRecord(null)}>
                <DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto w-full">
                    <DialogHeader className="pb-4 border-b">
                        <DialogTitle className="flex items-center gap-2 text-xl">
                            {selectedRecordType === 'clinical' ? <Activity className="h-5 w-5 text-blue-600" /> : selectedRecordType === 'dental' ? <FileText className="h-5 w-5 text-emerald-600" /> : <Pill className="h-5 w-5 text-purple-600" />}
                            {selectedRecordType === 'clinical'
                                ? t('patientDetails.viewMedicalConsultation')
                                : selectedRecordType === 'dental'
                                    ? t('patientDetails.viewDentalRecord')
                                    : t('patientDetails.prescriptionDetails')}
                        </DialogTitle>
                        <DialogDescription className="flex items-center gap-2">
                            <Calendar className="h-3 w-3" />
                            {selectedRecord && formatDate(selectedRecord.date || selectedRecord.createdAt)}
                        </DialogDescription>
                    </DialogHeader>

                    {selectedRecord && selectedRecordType === 'clinical' && (
                        <div className="space-y-6 pt-2">
                            <div>
                                <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('clinicalRecord.chiefComplaint')}</h4>
                                <p className="text-slate-900 bg-slate-50 p-3 rounded-lg border border-slate-100">{selectedRecord.reasonForConsultation}</p>
                            </div>

                            <Separator />

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('patientDetails.medicalHistory')}</h4>
                                    <div className="space-y-2">
                                        <div className="flex justify-between border-b border-dashed pb-1">
                                            <span className="text-sm text-slate-600">{t('medicalRecord.underMedicalTreatment')}</span>
                                            <span className="text-sm font-medium">{selectedRecord.medicalHistory?.underMedicalTreatment ? t('common.yes') : t('common.no')}</span>
                                        </div>
                                        <div className="flex justify-between border-b border-dashed pb-1">
                                            <span className="text-sm text-slate-600">{t('medicalRecord.takingMedication')}</span>
                                            <span className="text-sm font-medium">{selectedRecord.medicalHistory?.takingMedication ? t('common.yes') : t('common.no')}</span>
                                        </div>
                                        {selectedRecord.medicalHistory?.medicationDetails && (
                                            <div className="bg-yellow-50 p-2 rounded text-sm text-yellow-800 border border-yellow-100">
                                                {t('patientDetails.medicationsLabel')}: {selectedRecord.medicalHistory.medicationDetails}
                                            </div>
                                        )}
                                        <div className="flex justify-between border-b border-dashed pb-1">
                                            <span className="text-sm text-slate-600">{t('medicalRecord.allergies')}</span>
                                            <span className="text-sm font-medium">{selectedRecord.medicalHistory?.allergies || t('patientDetails.none')}</span>
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('medicalRecord.habits')}</h4>
                                    {renderBooleanList(selectedRecord.habits, {
                                        smoker: t('medicalRecord.smoker'),
                                        nailBiting: t('medicalRecord.nailBiting'),
                                        lipBiting: t('medicalRecord.lipBiting'),
                                        thumbSucking: t('medicalRecord.fingerSucking'),
                                        mouthBreather: t('medicalRecord.mouthBreather'),
                                        bruxism: t('medicalRecord.bruxism')
                                    })}
                                </div>
                            </div>

                            <Separator />

                            <div>
                                <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('medicalRecord.comments')}</h4>
                                <p className="text-slate-700 text-sm whitespace-pre-wrap">{selectedRecord.comments || t('patientDetails.none')}</p>
                            </div>
                        </div>
                    )}

                    {selectedRecord && selectedRecordType === 'dental' && (
                        <div className="space-y-6 pt-2">
                            <div>
                                <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('dentalRecord.treatmentPlan')}</h4>
                                <p className="text-slate-900 bg-emerald-50/50 p-3 rounded-lg border border-emerald-100">{selectedRecord.treatmentPlan || t('patientDetails.none')}</p>
                            </div>

                            <Separator />

                            <div>
                                <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('dentalRecord.dentalHistory')}</h4>
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    <div className="flex justify-between border-b border-dashed pb-1">
                                        <span className="text-sm text-slate-600">{t('dentalRecord.lossOfTeeth')}</span>
                                        <span className="text-sm font-medium">{selectedRecord.dentalHistory?.lossOfTeeth ? t('common.yes') : t('common.no')}</span>
                                    </div>
                                    <div className="flex justify-between border-b border-dashed pb-1">
                                        <span className="text-sm text-slate-600">{t('dentalRecord.bleedingGums')}</span>
                                        <span className="text-sm font-medium">{selectedRecord.dentalHistory?.bleedingGums ? t('common.yes') : t('common.no')}</span>
                                    </div>
                                    <div className="flex justify-between border-b border-dashed pb-1">
                                        <span className="text-sm text-slate-600">{t('dentalRecord.brushingFrequency')}</span>
                                        <span className="text-sm font-medium">{selectedRecord.dentalHistory?.brushingFrequency || t('common.na')}</span>
                                    </div>
                                    {selectedRecord.dentalHistory?.dentalTrauma && (
                                        <div className="col-span-1 sm:col-span-2 bg-red-50 p-2 rounded text-sm text-red-800 border border-red-100">
                                            {t('dentalRecord.dentalTrauma')}: {selectedRecord.dentalHistory.dentalTrauma}
                                        </div>
                                    )}
                                </div>
                            </div>

                            <Separator />

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('dentalRecord.extraoralExamination')}</h4>
                                    <div className="space-y-1 text-sm">
                                        {Object.entries(selectedRecord.extraoralExamination || {}).map(([key, value]) => (
                                            value ? <div key={key}><span className="font-medium capitalize">{key}:</span> {value as string}</div> : null
                                        ))}
                                        {!Object.values(selectedRecord.extraoralExamination || {}).some(v => v) && <span className="text-slate-500 italic">{t('patientDetails.none')}</span>}
                                    </div>
                                </div>
                                <div>
                                    <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('dentalRecord.intraoralExamination')}</h4>
                                    <div className="space-y-1 text-sm">
                                        {Object.entries(selectedRecord.intraoralExamination || {}).map(([key, value]) => (
                                            value ? <div key={key}><span className="font-medium capitalize">{key}:</span> {value as string}</div> : null
                                        ))}
                                        {!Object.values(selectedRecord.intraoralExamination || {}).some(v => v) && <span className="text-slate-500 italic">{t('patientDetails.none')}</span>}
                                    </div>
                                </div>
                            </div>

                            <Separator />

                            <div>
                                <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('dentalRecord.notes')}</h4>
                                {selectedRecord.odontogram && Object.keys(selectedRecord.odontogram).length > 0 ? (
                                    <div className="text-slate-700 text-sm space-y-2">
                                        {/* Render Interactive Odontogram if data available */}
                                        {Object.keys(selectedRecord.odontogram).some(k => k !== 'General' && !isNaN(Number(k))) && (
                                            <div className="mb-6 pointer-events-none scale-90 origin-top">
                                                <InteractiveOdontogram
                                                    readonly
                                                    initialData={Object.entries(selectedRecord.odontogram)
                                                        .filter(([k]) => !isNaN(Number(k)))
                                                        .map(([k, v]: [string, any]) => ({
                                                            id: Number(k),
                                                            status: v.status || 'healthy',
                                                            surfaces: v.surfaces || { top: 'healthy', bottom: 'healthy', left: 'healthy', right: 'healthy', center: 'healthy' },
                                                            notes: v.notes
                                                        }))
                                                    }
                                                />
                                            </div>
                                        )}

                                        {Object.entries(selectedRecord.odontogram).map(([key, value]: [string, any]) => {
                                            if (key === 'General' || isNaN(Number(key))) { // Only show text notes for general entries (or legacy)
                                                return (
                                                    <div key={key} className="bg-slate-50 p-2 rounded border border-slate-100">
                                                        {key !== 'General' && <span className="font-semibold mr-2 text-slate-900">{key}:</span>}
                                                        <span className="whitespace-pre-wrap">{value.notes || value.condition || t('patientDetails.none')}</span>
                                                    </div>
                                                );
                                            }
                                            return null;
                                        })}
                                    </div>
                                ) : (
                                    <p className="text-slate-700 text-sm italic">{t('patientDetails.none')}</p>
                                )}
                            </div>

                            <div>
                                <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('dentalRecord.radiographicAnalysis')}</h4>
                                <p className="text-slate-700 text-sm whitespace-pre-wrap">{selectedRecord.radiographicAnalysis || t('patientDetails.none')}</p>
                            </div>
                        </div>
                    )}

                    {selectedRecord && selectedRecordType === 'prescription' && (
                        <div className="space-y-6 pt-2">
                            <div>
                                <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('patientDetails.diagnosisLabel')}</h4>
                                <p className="text-slate-900 bg-purple-50 p-3 rounded-lg border border-purple-100">{selectedRecord.diagnosis || t('patientDetails.noDiagnosis')}</p>
                            </div>

                            <Separator />

                            {selectedPrescriptionIsStandard ? (
                                <div>
                                    <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('patientDetails.medicationsLabel')}</h4>
                                    {selectedRecord.medications && selectedRecord.medications.length > 0 ? (
                                        <div className="space-y-4">
                                            {selectedRecord.medications.map((med: any, i: number) => (
                                                <div key={i} className="bg-slate-50 p-4 rounded-lg border border-slate-100">
                                                    <div className="flex justify-between items-start mb-2">
                                                        <h5 className="font-bold text-slate-900 text-lg">{med.name}</h5>
                                                        <Badge variant="outline" className="bg-white">{med.dosage}</Badge>
                                                    </div>
                                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2 text-sm text-slate-700">
                                                        <div><span className="font-medium text-slate-500">{t('prescriptions.frequency')}:</span> {med.frequency}</div>
                                                        <div><span className="font-medium text-slate-500">{t('prescriptions.duration')}:</span> {med.duration}</div>
                                                        {med.instructions && (
                                                            <div className="sm:col-span-2 mt-2 pt-2 border-t border-dashed border-slate-200">
                                                                <span className="font-medium text-slate-500 block mb-1">{t('prescriptions.instructions')}:</span>
                                                                <span className="italic">{med.instructions}</span>
                                                            </div>
                                                        )}
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    ) : (
                                        <p className="text-slate-500 italic">{t('patientDetails.noMedicationsListed')}</p>
                                    )}
                                </div>
                            ) : (
                                <div>
                                    <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('prescriptions.freeText')}</h4>
                                    <p className="text-slate-700 text-sm whitespace-pre-wrap">{selectedRecord.freeText || t('patientDetails.none')}</p>
                                </div>
                            )}

                            <Separator />

                            <div>
                                <h4 className="text-sm font-semibold text-slate-500 uppercase tracking-wider mb-2">{t('patientDetails.notes')}</h4>
                                <p className="text-slate-700 text-sm whitespace-pre-wrap">{selectedRecord.notes || t('patientDetails.none')}</p>
                            </div>
                        </div>
                    )}

                    <div className="pt-4 flex justify-end">
                        <Button onClick={() => setSelectedRecord(null)}>{t('common.close')}</Button>
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
}
