'use client';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useAuth } from '@/lib/auth-context';
import { useAuthStore } from '@/lib/auth-store';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { toReachableAbsoluteUrl } from '@/lib/url-utils';
import { formatGenderForPrint, getDoctorPrintData, printRecord } from '@/lib/print-service';
import { Printer, Upload } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import ICD10Select from './ICD10Select';

interface ClinicalRecordFormProps {
    patientId: string;
    patient?: any; // Full patient object for print
    onSuccess?: () => void;
    onCancel?: () => void;
    initialData?: any; // For editing existing records
    viewOnly?: boolean; // For read-only view
    recordId?: string; // For updating existing records
}

export default function ClinicalRecordForm({ patientId, patient, onSuccess, onCancel, initialData, viewOnly = false, recordId }: ClinicalRecordFormProps) {
    const { t, language } = useLanguage();
    const { user } = useAuth();
    const [loading, setLoading] = useState(false);
    const [diagnoses, setDiagnoses] = useState<string[]>(initialData?.diagnoses || []);
    const [files, setFiles] = useState<File[]>([]); // We won't upload for real in this iteration unless backend supports it, but we'll collect them.
    const [existingFiles, setExistingFiles] = useState<string[]>(initialData?.files || []);

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

    const isBlobUrl = (value?: string) => typeof value === 'string' && /^blob:/i.test(value.trim());

    const isDentist = user?.isDentist === true || user?.userType === 'dentist';

    const today = new Date().toISOString().split("T")[0];

    const [formData, setFormData] = useState({
        title: initialData?.title || t('clinicalRecord.title'),
        chiefComplaint: initialData?.chiefComplaint || '',
        historyOfPresentIllness: initialData?.historyOfPresentIllness || '',
        pastMedicalHistory: {
            pathological: initialData?.pastMedicalHistory?.pathological || '',
            medications: initialData?.pastMedicalHistory?.medications || '',
            allergies: initialData?.pastMedicalHistory?.allergies || '',
            surgeries: initialData?.pastMedicalHistory?.surgeries || '',
            trauma: initialData?.pastMedicalHistory?.trauma || '',
            toxicHabits: initialData?.pastMedicalHistory?.toxicHabits || '',
            occupation: initialData?.pastMedicalHistory?.occupation || '',
            immunizations: initialData?.pastMedicalHistory?.immunizations || '',
            familyHistory: initialData?.pastMedicalHistory?.familyHistory || '',
            gynecological: initialData?.pastMedicalHistory?.gynecological || '',
        },
        reviewOfSystems: initialData?.reviewOfSystems || '',
        physicalExamination: {
            skinAndMucosa: initialData?.physicalExamination?.skinAndMucosa || (initialData ? '' : 'Normal'),
            headAndNeck: initialData?.physicalExamination?.headAndNeck || (initialData ? '' : 'Normal'),
            chest: initialData?.physicalExamination?.chest || (initialData ? '' : 'Normal'),
            heart: initialData?.physicalExamination?.heart || (initialData ? '' : 'Normal'),
            lungs: initialData?.physicalExamination?.lungs || (initialData ? '' : 'Normal'),
            abdomenAndPelvis: initialData?.physicalExamination?.abdomenAndPelvis || (initialData ? '' : 'Normal'),
            upperExtremities: initialData?.physicalExamination?.upperExtremities || (initialData ? '' : 'Normal'),
            lowerExtremities: initialData?.physicalExamination?.lowerExtremities || (initialData ? '' : 'Normal'),
            neurological: initialData?.physicalExamination?.neurological || (initialData ? '' : 'Normal'),
        },
        vitalSigns: {
            bp: initialData?.vitalSigns?.bp || '',
            hr: initialData?.vitalSigns?.hr || '',
            rr: initialData?.vitalSigns?.rr || '',
            temp: initialData?.vitalSigns?.temp || '',
            spo2: initialData?.vitalSigns?.spo2 || '',
        },
        complementaryStudies: initialData?.complementaryStudies || '',
        plan: initialData?.plan || '',
    });

    // Update form data when initialData changes (for edit mode)
    useEffect(() => {
        if (initialData) {
            setFormData({
                title: initialData?.title || t('clinicalRecord.title'),
                chiefComplaint: initialData?.chiefComplaint || '',
                historyOfPresentIllness: initialData?.historyOfPresentIllness || '',
                pastMedicalHistory: {
                    pathological: initialData?.pastMedicalHistory?.pathological || '',
                    medications: initialData?.pastMedicalHistory?.medications || '',
                    allergies: initialData?.pastMedicalHistory?.allergies || '',
                    surgeries: initialData?.pastMedicalHistory?.surgeries || '',
                    trauma: initialData?.pastMedicalHistory?.trauma || '',
                    toxicHabits: initialData?.pastMedicalHistory?.toxicHabits || '',
                    occupation: initialData?.pastMedicalHistory?.occupation || '',
                    immunizations: initialData?.pastMedicalHistory?.immunizations || '',
                    familyHistory: initialData?.pastMedicalHistory?.familyHistory || '',
                    gynecological: initialData?.pastMedicalHistory?.gynecological || '',
                },
                reviewOfSystems: initialData?.reviewOfSystems || '',
                physicalExamination: {
                    skinAndMucosa: initialData?.physicalExamination?.skinAndMucosa || '',
                    headAndNeck: initialData?.physicalExamination?.headAndNeck || '',
                    chest: initialData?.physicalExamination?.chest || '',
                    heart: initialData?.physicalExamination?.heart || '',
                    lungs: initialData?.physicalExamination?.lungs || '',
                    abdomenAndPelvis: initialData?.physicalExamination?.abdomenAndPelvis || '',
                    upperExtremities: initialData?.physicalExamination?.upperExtremities || '',
                    lowerExtremities: initialData?.physicalExamination?.lowerExtremities || '',
                    neurological: initialData?.physicalExamination?.neurological || '',
                },
                vitalSigns: {
                    bp: initialData?.vitalSigns?.bp || '',
                    hr: initialData?.vitalSigns?.hr || '',
                    rr: initialData?.vitalSigns?.rr || '',
                    temp: initialData?.vitalSigns?.temp || '',
                    spo2: initialData?.vitalSigns?.spo2 || '',
                },
                complementaryStudies: initialData?.complementaryStudies || '',
                plan: initialData?.plan || '',
            });
            setDiagnoses(initialData?.diagnoses || []);
            setExistingFiles(initialData?.files || []);
        }
    }, [initialData, t]);

    const handleChange = (field: string, value: string) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const handleNestedChange = (section: 'pastMedicalHistory' | 'physicalExamination' | 'vitalSigns', field: string, value: string) => {
        setFormData(prev => ({
            ...prev,
            [section]: {
                ...prev[section],
                [field]: value
            }
        }));
    };

    const handleSave = async () => {
        if (viewOnly) return; // Don't save in view-only mode

        setLoading(true);
        try {
            // Get token from auth store
            const token = useAuthStore.getState().token;

            if (!token) {
                toast.error(t('clinicalRecord.loginRequiredSave'));
                setLoading(false);
                return;
            }

            // Upload files first
            const uploadedFilePaths: string[] = [];
            if (files.length > 0) {
                for (const file of files) {
                    const formData = new FormData();
                    formData.append('file', file);

                    try {
                        const uploadRes = await fetch(`${API_BASE_URL}/api/upload/clinical-record-file`, {
                            method: 'POST',
                            headers: {
                                'x-auth-token': token
                            },
                            body: formData
                        });

                        const uploadData = await uploadRes.json();

                        if (uploadRes.ok && uploadData.success) {
                            uploadedFilePaths.push(uploadData.filePath);
                        } else {
                            toast.error(t('clinicalRecord.uploadError').replace('{fileName}', file.name));
                        }
                    } catch {
                        toast.error(t('clinicalRecord.uploadError').replace('{fileName}', file.name));
                    }
                }
            }

            const stableExistingFiles = existingFiles.filter((fileUrl) => !isBlobUrl(fileUrl));

            const payload = {
                ...formData,
                diagnoses,
                date: initialData?.date || new Date(),
                files: [...stableExistingFiles, ...uploadedFilePaths]
            };

            const url = recordId
                ? `${API_BASE_URL}/api/patients/${patientId}/clinical-records/${recordId}`
                : `${API_BASE_URL}/api/patients/${patientId}/clinical-records`;

            const method = recordId ? 'PUT' : 'POST';

            const response = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    'x-auth-token': token
                },
                body: JSON.stringify(payload),
            });

            const data = await response.json().catch(() => ({}));

            if (response.ok) {
                toast.success(recordId ? t('clinicalRecord.updateSuccess') : t('clinicalRecord.saveSuccess'));
                onSuccess?.();
            } else {
                toast.error((data as { error?: string }).error || t('clinicalRecord.saveFailed'));
            }
        } catch {
            toast.error(t('clinicalRecord.unexpectedError'));
        } finally {
            setLoading(false);
        }
    };

    const handlePrint = () => {
        // Use initialData as the record source for view mode
        const record = initialData || {};
        const recordTitle = formData.title.trim() || t('clinicalRecord.title');

        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();
        };

        // Form data for content
        const vitals = formData.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;">${formData.vitalSigns.bp || '-'}</div></div>
                    <div><div class="label" style="font-size: 11px; color: #64748b;">${t('patientDetails.heartRate')}</div><div style="font-weight: 600;">${formData.vitalSigns.hr || '-'}</div></div>
                    <div><div class="label" style="font-size: 11px; color: #64748b;">${t('patientDetails.respiratoryRate')}</div><div style="font-weight: 600;">${formData.vitalSigns.rr || '-'}</div></div>
                    <div><div class="label" style="font-size: 11px; color: #64748b;">${t('patientDetails.temperature')}</div><div style="font-weight: 600;">${formData.vitalSigns.temp || '-'}</div></div>
                    <div><div class="label" style="font-size: 11px; color: #64748b;">${t('patientDetails.spo2')}</div><div style="font-weight: 600;">${formData.vitalSigns.spo2 || '-'}</div></div>
                </div>
            </div>
        ` : '';

        const historyContent = formData.pastMedicalHistory ? Object.entries(formData.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 = formData.physicalExamination ? Object.entries(formData.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 diagContent = diagnoses && diagnoses.length > 0 ? `
            <div class="section">
                <div class="section-title">${t('patientDetails.diagnoses')}</div>
                <ul style="padding-left: 20px; margin: 0;">
                    ${diagnoses.map((d: string) => `<li style="margin-bottom: 4px;">${d}</li>`).join()}
                </ul>
            </div>
        ` : '';

        const 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;">
                        ${formData.chiefComplaint || t('common.na')}
                    </div>
                </div>
                ${formData.historyOfPresentIllness ? `
                <div style="margin-bottom: 15px;">
                    <div style="font-weight: 600; color: #475569; margin-bottom: 4px;">${t('clinicalRecord.hpi')}</div>
                    <div>${formData.historyOfPresentIllness}</div>
                </div>` : ''}
            </div>

            ${vitals}
            ${historySection}
            ${examSection}
            ${diagContent}

            <div class="section">
                <div class="section-title">${t('clinicalRecord.plan')}</div>
                <div class="notes">${formData.plan || t('patientDetails.none')}</div>
            </div>
        `;

        const patientName = patient?.userId
            ? `${patient.userId.firstName || ''} ${patient.userId.lastName || ''}`.trim()
            : t('common.patient');
        const patientDob = patient?.dateOfBirth ? new Date(patient.dateOfBirth).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US', { timeZone: 'UTC' }) : '';
        const patientGender = formatGenderForPrint(patient?.gender, {
            male: t('common.male'),
            female: t('common.female'),
            other: t('common.other'),
        });
        const patientPhone = patient?.userId?.phone || '';
        const patientNationalId = patient?.nationalId;
        const insuranceStr = patient?.insurance?.provider
            ? `${patient.insurance.provider}${patient.insurance.policyNumber ? ` (#${patient.insurance.policyNumber})` : ''}`
            : undefined;

        printRecord({
            doctor,
            clinic,
            patient: {
                name: patientName,
                dob: patientDob,
                gender: patientGender,
                phone: patientPhone,
                id: patientNationalId,
                insurance: insuranceStr,
            },
            record: {
                date: new Date(record.date || today).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US'),
                type: t('patientDetails.activities.consultation'),
                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 resolvedFormTitleLabel = t('clinicalRecord.formTitleLabel');
    const formTitleLabel = resolvedFormTitleLabel === 'clinicalRecord.formTitleLabel'
        ? (language === 'es' ? 'Titulo del Formulario' : 'Form Title')
        : resolvedFormTitleLabel;
    const resolvedFormTitlePlaceholder = t('clinicalRecord.formTitlePlaceholder');
    const formTitlePlaceholder = resolvedFormTitlePlaceholder === 'clinicalRecord.formTitlePlaceholder'
        ? (language === 'es' ? 'Escriba el titulo de la consulta' : 'Enter consultation form title')
        : resolvedFormTitlePlaceholder;

    return (
        <div className="printable-area space-y-6 overflow-x-hidden rounded-xl border border-slate-100 bg-white p-3 shadow-lg sm:p-4 md:space-y-10 md:p-8">
            <div className="flex flex-col gap-3 border-b-2 border-slate-100 pb-4 sm:flex-row sm:items-start sm:justify-between">
                <div className="min-w-0 flex-1">
                    <Label className="block text-sm font-medium text-slate-500 mb-2">{formTitleLabel}</Label>
                    {viewOnly ? (
                        <h1 className="break-words text-2xl font-bold text-slate-800 md:text-3xl">{formData.title.trim() || t('clinicalRecord.title')}</h1>
                    ) : (
                        <Input
                            value={formData.title}
                            onChange={(e) => handleChange('title', e.target.value)}
                            placeholder={formTitlePlaceholder}
                            className="h-12 w-full text-lg font-bold sm:text-xl md:h-14 md:text-2xl"
                        />
                    )}
                </div>
                <div className="text-left sm:text-right">
                    <Label className="block text-sm font-medium text-slate-500">{t('clinicalRecord.date')}</Label>
                    <div className="text-lg font-semibold text-slate-800">{today}</div>
                </div>
            </div>

            {/* Chief Complaint & HPI */}
            <div className="space-y-6">
                <div className="space-y-2">
                    <Label className="text-base font-semibold text-slate-700">{t('clinicalRecord.chiefComplaint')}</Label>
                    <Textarea
                        value={formData.chiefComplaint}
                        onChange={e => handleChange('chiefComplaint', e.target.value)}
                        placeholder={t('clinicalRecord.chiefComplaintPlaceholder')}
                        className="bg-slate-50 min-h-[80px]"
                        disabled={viewOnly}
                    />
                </div>
                <div className="space-y-2">
                    <Label className="text-base font-semibold text-slate-700">{t('clinicalRecord.hpi')}</Label>
                    <Textarea
                        value={formData.historyOfPresentIllness}
                        onChange={e => handleChange('historyOfPresentIllness', e.target.value)}
                        placeholder={t('clinicalRecord.hpiPlaceholder')}
                        disabled={viewOnly}
                        className="bg-slate-50 min-h-[120px]"
                    />
                </div>
            </div>

            {/* Past Medical History */}
            <div className="space-y-6">
                <h3 className="text-xl font-bold text-slate-800 border-b border-slate-100 pb-2">{t('clinicalRecord.pastMedicalHistory')}</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                        <Label>{t('clinicalRecord.pathological')}</Label>
                        <Textarea
                            value={formData.pastMedicalHistory.pathological}
                            onChange={e => handleNestedChange('pastMedicalHistory', 'pathological', e.target.value)}
                            className="h-20"
                            disabled={viewOnly}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label>{t('clinicalRecord.medications')}</Label>
                        <Textarea
                            value={formData.pastMedicalHistory.medications}
                            onChange={e => handleNestedChange('pastMedicalHistory', 'medications', e.target.value)}
                            className="h-20"
                            disabled={viewOnly}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label>{t('clinicalRecord.allergies')}</Label>
                        <Textarea
                            value={formData.pastMedicalHistory.allergies}
                            onChange={e => handleNestedChange('pastMedicalHistory', 'allergies', e.target.value)}
                            className="h-20"
                            disabled={viewOnly}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label>{t('clinicalRecord.surgeries')}</Label>
                        <Textarea
                            value={formData.pastMedicalHistory.surgeries}
                            onChange={e => handleNestedChange('pastMedicalHistory', 'surgeries', e.target.value)}
                            className="h-20"
                            disabled={viewOnly}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label>{t('clinicalRecord.trauma')}</Label>
                        <Textarea
                            value={formData.pastMedicalHistory.trauma}
                            onChange={e => handleNestedChange('pastMedicalHistory', 'trauma', e.target.value)}
                            className="h-20"
                            disabled={viewOnly}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label>{t('clinicalRecord.toxicHabits')}</Label>
                        <Textarea
                            value={formData.pastMedicalHistory.toxicHabits}
                            onChange={e => handleNestedChange('pastMedicalHistory', 'toxicHabits', e.target.value)}
                            className="h-20"
                            disabled={viewOnly}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label>{t('clinicalRecord.occupation')}</Label>
                        <Input
                            value={formData.pastMedicalHistory.occupation}
                            onChange={e => handleNestedChange('pastMedicalHistory', 'occupation', e.target.value)}
                            disabled={viewOnly}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label>{t('clinicalRecord.immunizations')}</Label>
                        <Textarea
                            value={formData.pastMedicalHistory.immunizations}
                            onChange={e => handleNestedChange('pastMedicalHistory', 'immunizations', e.target.value)}
                            className="h-20"
                            disabled={viewOnly}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label>{t('clinicalRecord.familyHistory')}</Label>
                        <Textarea
                            value={formData.pastMedicalHistory.familyHistory}
                            onChange={e => handleNestedChange('pastMedicalHistory', 'familyHistory', e.target.value)}
                            className="h-20"
                            disabled={viewOnly}
                        />
                    </div>
                    <div className="space-y-2">
                        <Label>{t('clinicalRecord.gynecological')}</Label>
                        <Textarea
                            value={formData.pastMedicalHistory.gynecological}
                            onChange={e => handleNestedChange('pastMedicalHistory', 'gynecological', e.target.value)}
                            className="h-20"
                            disabled={viewOnly}
                        />
                    </div>
                </div>
            </div>

            {/* Review of Systems */}
            <div className="space-y-4">
                <h3 className="text-xl font-bold text-slate-800 border-b border-slate-100 pb-2">{t('clinicalRecord.reviewOfSystems')}</h3>
                <Textarea
                    value={formData.reviewOfSystems}
                    onChange={e => handleChange('reviewOfSystems', e.target.value)}
                    className="min-h-[100px]"
                    disabled={viewOnly}
                />
            </div>

            {/* Physical Examination */}
            <div className="space-y-6">
                <h3 className="text-xl font-bold text-slate-800 border-b border-slate-100 pb-2">{t('clinicalRecord.physicalExamination')}</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {[
                        { key: 'skinAndMucosa', label: t('clinicalRecord.skinAndMucosa') },
                        { key: 'headAndNeck', label: t('clinicalRecord.headAndNeck') },
                        { key: 'chest', label: t('clinicalRecord.chest') },
                        { key: 'heart', label: t('clinicalRecord.heart') },
                        { key: 'lungs', label: t('clinicalRecord.lungs') },
                        { key: 'abdomenAndPelvis', label: t('clinicalRecord.abdomenAndPelvis') },
                        { key: 'upperExtremities', label: t('clinicalRecord.upperExtremities') },
                        { key: 'lowerExtremities', label: t('clinicalRecord.lowerExtremities') },
                        { key: 'neurological', label: t('clinicalRecord.neurological') }
                    ].map((item) => (
                        <div key={item.key} className="space-y-1">
                            <Label className="text-sm font-medium text-slate-600">{item.label}</Label>
                            <Textarea
                                value={(formData.physicalExamination as any)[item.key]}
                                onChange={e => handleNestedChange('physicalExamination', item.key, e.target.value)}
                                placeholder={t('clinicalRecord.examNotesPlaceholder').replace('{label}', item.label.toLowerCase())}
                                className="h-24 resize-none"
                                disabled={viewOnly}
                            />
                        </div>
                    ))}
                </div>
            </div>

            {/* Vital Signs */}
            {!isDentist && (
                <div className="space-y-6">
                    <h3 className="text-xl font-bold text-slate-800 border-b border-slate-100 pb-2">{t('clinicalRecord.vitalSigns')}</h3>
                    <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                        <div className="space-y-1">
                            <Label>{t('patientDetails.bloodPressure')} (mmHg)</Label>
                            <Input
                                value={formData.vitalSigns.bp}
                                onChange={e => handleNestedChange('vitalSigns', 'bp', e.target.value)}
                                placeholder="120/80"
                                disabled={viewOnly}
                            />
                        </div>
                        <div className="space-y-1">
                            <Label>{t('patientDetails.heartRate')} (bpm)</Label>
                            <Input
                                value={formData.vitalSigns.hr}
                                onChange={e => handleNestedChange('vitalSigns', 'hr', e.target.value)}
                                placeholder="72"
                                disabled={viewOnly}
                            />
                        </div>
                        <div className="space-y-1">
                            <Label>{t('patientDetails.respiratoryRate')} (/min)</Label>
                            <Input
                                value={formData.vitalSigns.rr}
                                onChange={e => handleNestedChange('vitalSigns', 'rr', e.target.value)}
                                placeholder="16"
                                disabled={viewOnly}
                            />
                        </div>
                        <div className="space-y-1">
                            <Label>{t('patientDetails.temperature')} (°C)</Label>
                            <Input
                                value={formData.vitalSigns.temp}
                                onChange={e => handleNestedChange('vitalSigns', 'temp', e.target.value)}
                                placeholder="36.5"
                                disabled={viewOnly}
                            />
                        </div>
                        <div className="space-y-1">
                            <Label>{t('patientDetails.spo2')} (%)</Label>
                            <Input
                                value={formData.vitalSigns.spo2}
                                onChange={e => handleNestedChange('vitalSigns', 'spo2', e.target.value)}
                                placeholder="98"
                                disabled={viewOnly}
                            />
                        </div>
                    </div>
                </div>
            )}

            {/* Complementary Studies & Files */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                <div className="space-y-2">
                    <Label className="text-base font-semibold">{t('clinicalRecord.complementaryStudies')}</Label>
                    <Textarea
                        value={formData.complementaryStudies}
                        onChange={e => handleChange('complementaryStudies', e.target.value)}
                        className="h-32"
                        disabled={viewOnly}
                    />
                </div>
                <div className="space-y-2">
                    <Label className="text-base font-semibold">{t('clinicalRecord.uploadFiles')}</Label>

                    {!viewOnly && (
                        <div className="border-2 border-dashed border-slate-200 rounded-lg p-6 flex flex-col items-center justify-center text-slate-500 hover:bg-slate-50 transition-colors cursor-pointer relative">
                            <input
                                type="file"
                                accept=".jpg,.jpeg,.png,.pdf"
                                multiple
                                className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"
                                onChange={e => setFiles(prev => [...prev, ...(e.target.files ? Array.from(e.target.files) : [])])}
                            />
                            <Upload className="w-8 h-8 mb-2 text-slate-400" />
                            <span className="text-sm font-medium">{t('clinicalRecord.uploadPlaceholder')}</span>
                            <span className="text-xs text-slate-400 mt-1">
                                {(files.length + existingFiles.length) > 0
                                    ? t('clinicalRecord.filesSelected').replace('{count}', String(files.length + existingFiles.length))
                                    : t('clinicalRecord.noFilesSelected')}
                            </span>
                        </div>
                    )}

                    <div className="space-y-2 mt-2">
                        {/* Existing Files */}
                        {existingFiles.length === 0 && !viewOnly && files.length === 0 && (
                            <p className="text-sm text-slate-400 italic">{t('clinicalRecord.noFilesAttached')}</p>
                        )}

                        {existingFiles.map((fileUrl, idx) => (
                            <div key={`existing-${idx}`} className="text-xs text-slate-600 bg-blue-50 px-2 py-1 rounded flex justify-between items-center group">
                                <a href={getAbsoluteFileUrl(fileUrl)} target="_blank" rel="noopener noreferrer" className="truncate max-w-[200px] hover:underline text-blue-600 flex items-center gap-1">
                                    <span className="font-semibold">{t('clinicalRecord.documentsLabel')}:</span> {t('clinicalRecord.fileLabel')} {idx + 1}
                                </a>
                                {!viewOnly && (
                                    <button
                                        type="button"
                                        onClick={() => setExistingFiles(prev => prev.filter((_, i) => i !== idx))}
                                        className="text-red-500 hover:text-red-700 opacity-0 group-hover:opacity-100 transition-opacity px-2 font-bold"
                                        title={t('clinicalRecord.removeFile')}
                                    >
                                        ×
                                    </button>
                                )}
                            </div>
                        ))}

                        {/* New Files */}
                        {files.map((file, idx) => (
                            <div key={`new-${idx}`} className="text-xs text-slate-600 bg-slate-100 px-2 py-1 rounded flex justify-between items-center group">
                                <span className="truncate max-w-[200px]">{file.name}</span>
                                <div className="flex items-center gap-2">
                                    <span>{(file.size / 1024).toFixed(0)} KB</span>
                                    <button
                                        type="button"
                                        onClick={() => setFiles(prev => prev.filter((_, i) => i !== idx))}
                                        className="text-red-500 hover:text-red-700 opacity-0 group-hover:opacity-100 transition-opacity px-2 font-bold"
                                        title={t('clinicalRecord.removeFile')}
                                    >
                                        ×
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>

            {/* Diagnosis (ICD-10) */}
            <div className="space-y-4 pt-4 border-t border-slate-100">
                <ICD10Select diagnoses={diagnoses} setDiagnoses={setDiagnoses} />
            </div>

            {/* Plan */}
            <div className="space-y-2">
                <Label className="text-lg font-bold text-slate-800">{t('clinicalRecord.plan')}</Label>
                <Textarea
                    value={formData.plan}
                    onChange={e => handleChange('plan', e.target.value)}
                    className="min-h-[120px] bg-slate-50 text-base"
                    placeholder={t('clinicalRecord.planPlaceholder')}
                    disabled={viewOnly}
                />
            </div>

            {/* Actions */}
            <div className="flex flex-wrap justify-end gap-3 pt-6 border-t border-slate-100">
                {onCancel && (
                    <Button type="button" variant="outline" onClick={onCancel}>
                        {viewOnly ? t('common.close') : t('common.cancel')}
                    </Button>
                )}
                <Button type="button" variant="secondary" onClick={handlePrint} className="gap-2">
                    <Printer className="w-4 h-4" />
                    {t('common.print')}
                </Button>
                {!viewOnly && (
                    <Button type="button" onClick={handleSave} disabled={loading}>
                        {loading ? t('common.saving') : (recordId ? t('clinicalRecord.updateRecord') : t('clinicalRecord.saveRecord'))}
                    </Button>
                )}
            </div>
        </div>
    );
}
