'use client';

import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useAuthStore } from '@/lib/auth-store';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { buildOdontogramHtml, formatGenderForPrint, getDoctorPrintData, printRecord } from '@/lib/print-service';
import { Printer } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import InteractiveOdontogram, { ToothState } from './InteractiveOdontogram';

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

export default function DentalRecordForm({ patientId, patient, onSuccess, onCancel, initialData, viewOnly = false, recordId }: DentalRecordFormProps) {
    const { t, language } = useLanguage();
    const [loading, setLoading] = useState(false);
    const initialProcedures = Array.isArray(initialData?.procedures) && initialData.procedures.length > 0
        ? initialData.procedures
        : (viewOnly ? [] : [{ procedure: '', date: '', totalPaid: '' }]);
    const [formData, setFormData] = useState({
        dentalHistory: {
            lossOfTeeth: initialData?.dentalHistory?.lossOfTeeth ?? false,
            causeOfLoss: initialData?.dentalHistory?.causeOfLoss ?? '',
            previousDentalTreatment: initialData?.dentalHistory?.previousDentalTreatment ?? false,
            treatmentExplanation: initialData?.dentalHistory?.treatmentExplanation ?? '',
            brushingFrequency: initialData?.dentalHistory?.brushingFrequency ?? '',
            bleedingGums: initialData?.dentalHistory?.bleedingGums ?? false,
            badBreath: initialData?.dentalHistory?.badBreath ?? false,
            foodImpaction: initialData?.dentalHistory?.foodImpaction ?? false,
            mouthRinse: initialData?.dentalHistory?.mouthRinse ?? false,
            dentalFloss: initialData?.dentalHistory?.dentalFloss ?? false,
            anesthesiaProblems: initialData?.dentalHistory?.anesthesiaProblems ?? false,
            dentalTrauma: initialData?.dentalHistory?.dentalTrauma ?? '',
            extraoralExamNote: initialData?.dentalHistory?.extraoralExamNote ?? '',
        },
        extraoralExamination: {
            head: initialData?.extraoralExamination?.head ?? (initialData ? '' : 'Normal'),
            face: initialData?.extraoralExamination?.face ?? (initialData ? '' : 'Normal'),
            neck: initialData?.extraoralExamination?.neck ?? (initialData ? '' : 'Normal'),
            eyes: initialData?.extraoralExamination?.eyes ?? (initialData ? '' : 'Normal'),
            ears: initialData?.extraoralExamination?.ears ?? (initialData ? '' : 'Normal'),
            nose: initialData?.extraoralExamination?.nose ?? (initialData ? '' : 'Normal'),
            tmj: initialData?.extraoralExamination?.tmj ?? (initialData ? '' : 'Normal'),
            skin: initialData?.extraoralExamination?.skin ?? (initialData ? '' : 'Normal'),
            lips: initialData?.extraoralExamination?.lips ?? (initialData ? '' : 'Normal'),
            other: initialData?.extraoralExamination?.other ?? '',
        },
        intraoralExamination: {
            hardPalate: initialData?.intraoralExamination?.hardPalate ?? (initialData ? '' : 'Normal'),
            softPalate: initialData?.intraoralExamination?.softPalate ?? (initialData ? '' : 'Normal'),
            cheeks: initialData?.intraoralExamination?.cheeks ?? (initialData ? '' : 'Normal'),
            tongue: initialData?.intraoralExamination?.tongue ?? (initialData ? '' : 'Normal'),
            floorOfMouth: initialData?.intraoralExamination?.floorOfMouth ?? (initialData ? '' : 'Normal'),
            oralMucosa: initialData?.intraoralExamination?.oralMucosa ?? (initialData ? '' : 'Normal'),
            gums: initialData?.intraoralExamination?.gums ?? (initialData ? '' : 'Normal'),
            frenula: initialData?.intraoralExamination?.frenula ?? (initialData ? '' : 'Normal'),
            oropharynx: initialData?.intraoralExamination?.oropharynx ?? (initialData ? '' : 'Normal'),
            salivaryGlands: initialData?.intraoralExamination?.salivaryGlands ?? (initialData ? '' : 'Normal'),
            residualRidge: initialData?.intraoralExamination?.residualRidge ?? (initialData ? '' : 'Normal'),
            occlusion: initialData?.intraoralExamination?.occlusion ?? (initialData ? '' : 'Normal'),
        },
        procedures: initialProcedures,
        odontogramNotes: initialData?.odontogramNotes ?? initialData?.odontogram?.General?.notes ?? '',
        radiographicAnalysis: initialData?.radiographicAnalysis ?? '',
        treatmentPlan: initialData?.treatmentPlan ?? '',
    });

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

    const [odontogramData, setOdontogramData] = useState<ToothState[]>(initialOdontogramData);

    const handleChange = (section: string, field: string, value: any) => {
        setFormData((prev: any) => {
            if (section === 'root') {
                return { ...prev, [field]: value };
            }
            return {
                ...prev,
                [section]: {
                    ...prev[section],
                    [field]: value,
                },
            };
        });
    };

    const handleProcedureChange = (index: number, field: 'procedure' | 'date' | 'totalPaid', value: string) => {
        setFormData((prev: any) => {
            const updatedProcedures = [...prev.procedures];
            updatedProcedures[index] = {
                ...updatedProcedures[index],
                [field]: value
            };
            return { ...prev, procedures: updatedProcedures };
        });
    };

    const addProcedureRow = () => {
        setFormData((prev: any) => ({
            ...prev,
            procedures: [...prev.procedures, { procedure: '', date: '', totalPaid: '' }]
        }));
    };

    const removeProcedureRow = (index: number) => {
        setFormData((prev: any) => {
            const next = prev.procedures.filter((_: any, i: number) => i !== index);
            return {
                ...prev,
                procedures: next.length > 0 ? next : [{ procedure: '', date: '', totalPaid: '' }]
            };
        });
    };

    const handlePrint = () => {
        if (!initialData) return;
        const user = useAuthStore.getState().user;
        const { doctor, clinic } = getDoctorPrintData(initialData, user, {
            doctor: t('common.doctor'),
        });

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

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

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

        const odontogramHtml = buildOdontogramHtml(initialData.odontogram, {
            healthy: t('patientDetails.healthy'),
            caries: t('patientDetails.decay'),
            filled: t('patientDetails.filled'),
            missing: t('patientDetails.missing'),
            exodontia: t('patientDetails.exodontia'),
            crown: t('patientDetails.crown'),
            rootCanal: t('patientDetails.rootCanal'),
            implant: t('patientDetails.implant'),
        });
        const dentalNotes = initialData.odontogramNotes || initialData.odontogram?.General?.notes || '';
        const procedures = Array.isArray(initialData.procedures)
            ? initialData.procedures.filter((p: any) => p?.procedure || p?.date || p?.totalPaid)
            : [];
        const recordDate = new Date(initialData.date || initialData.createdAt).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US', { timeZone: 'UTC' });

        printRecord({
            doctor,
            clinic,
            patient: {
                name: patientName,
                phone: patient?.userId?.phone,
                gender: formatGenderForPrint(patient?.gender, {
                    male: t('common.male'),
                    female: t('common.female'),
                    other: t('common.other'),
                }),
                dob: patient?.dateOfBirth ? new Date(patient.dateOfBirth).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US', { timeZone: 'UTC' }) : undefined,
                id: patient?.nationalId,
                insurance: insuranceStr,
            },
            record: { date: recordDate, type: t('dentalRecord.title'), title: t('dentalRecord.title') },
            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: `
                <div class="section">
                    <div class="section-title">${t('dentalRecord.dentalHistory')}</div>
                    <table><tbody>
                        ${dh.lossOfTeeth ? `<tr><td style="width:40%;color:#64748b;font-weight:600;">${t('dentalRecord.lossOfTeeth')}</td><td>${yesText}${dh.causeOfLoss ? ' — ' + dh.causeOfLoss : ''}</td></tr>` : ''}
                        ${dh.previousDentalTreatment ? `<tr><td style="width:40%;color:#64748b;font-weight:600;">${t('dentalRecord.previousDentalTreatment')}</td><td>${yesText}${dh.treatmentExplanation ? ' — ' + dh.treatmentExplanation : ''}</td></tr>` : ''}
                        ${dh.brushingFrequency ? `<tr><td style="width:40%;color:#64748b;font-weight:600;">${t('dentalRecord.brushingFrequency')}</td><td>${dh.brushingFrequency}</td></tr>` : ''}
                        ${dh.dentalTrauma ? `<tr><td style="width:40%;color:#64748b;font-weight:600;">${t('dentalRecord.dentalTrauma')}</td><td>${dh.dentalTrauma}</td></tr>` : ''}
                    </tbody></table>
                    ${dhFlags ? `<div style="margin-top:8px;display:flex;flex-wrap:wrap;gap:6px;">${dhFlags}</div>` : ''}
                </div>
                ${renderKvSection(t('dentalRecord.extraoralExamination'), initialData.extraoralExamination || {})}
                ${renderKvSection(t('dentalRecord.intraoralExamination'), initialData.intraoralExamination || {})}
                <div class="section">
                    <div class="section-title">${t('dentalRecord.odontogram')}</div>
                    ${odontogramHtml}
                    ${procedures.length > 0 ? `
                        <div style="margin-top:10px;display:grid;gap:10px;">
                            ${procedures.map((p: any, idx: number) => `
                                <div style="border:1px solid #e2e8f0;border-radius:8px;padding:10px;">
                                    <div style="font-size:11px;color:#64748b;font-weight:600;margin-bottom:6px;">${t('dentalRecord.procedureEntry')} ${idx + 1}</div>
                                    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;">
                                        <div><div style="font-size:11px;color:#64748b;">${t('dentalRecord.procedurePerformed')}</div><div style="font-size:13px;color:#0f172a;">${p.procedure || '-'}</div></div>
                                        <div><div style="font-size:11px;color:#64748b;">${t('dentalRecord.procedureDate')}</div><div style="font-size:13px;color:#0f172a;">${p.date ? new Date(p.date).toLocaleDateString() : '-'}</div></div>
                                        <div><div style="font-size:11px;color:#64748b;">${t('dentalRecord.totalPaid')}</div><div style="font-size:13px;color:#0f172a;">${p.totalPaid || '-'}</div></div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    ` : ''}
                    ${dentalNotes ? `<div class="notes" style="margin-top:10px;">${dentalNotes}</div>` : ''}
                </div>
                ${initialData.radiographicAnalysis ? `<div class="section"><div class="section-title">${t('dentalRecord.radiographicAnalysis')}</div><div class="section-text">${initialData.radiographicAnalysis}</div></div>` : ''}
                ${initialData.treatmentPlan ? `<div class="section"><div class="section-title">${t('dentalRecord.treatmentPlan')}</div><div class="section-text">${initialData.treatmentPlan}</div></div>` : ''}
            `,
        });
    };

    const handleSubmit = async (e: React.SyntheticEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (viewOnly) return;

        setLoading(true);

        const token = useAuthStore.getState().token;
        if (!token) {
            toast.error(t('dentalRecord.loginRequiredSave'));
            setLoading(false);
            return;
        }

        // Transform the odontogramData array into a map-like object the backend likely expects
        const odontogramMap: Record<string, any> = {};
        if (odontogramData && odontogramData.length > 0) {
            odontogramData.forEach(tooth => {
                // Only save teeth that have non-healthy status to save space/bandwidth
                if (tooth.status !== 'healthy' || Object.values(tooth.surfaces).some(s => s !== 'healthy')) {
                    odontogramMap[tooth.id.toString()] = {
                        status: tooth.status,
                        surfaces: tooth.surfaces,
                        notes: tooth.notes || ''
                    };
                }
            });
        }

        // Also keep the general note
        if (formData.odontogramNotes) {
            odontogramMap['General'] = { notes: formData.odontogramNotes, condition: t('dentalRecord.generalNotes'), treatment: '' };
        }

        const payload = {
            ...formData,
            procedures: formData.procedures.filter((p: { procedure: any; date: any; totalPaid: any; }) => p.procedure || p.date || p.totalPaid),
            odontogram: Object.keys(odontogramMap).length > 0 ? odontogramMap : undefined
        };

        try {
            const method = recordId ? 'PUT' : 'POST';
            const url = recordId ? `${API_BASE_URL}/api/patients/${patientId}/dental-records/${recordId}` : `${API_BASE_URL}/api/patients/${patientId}/dental-records`;

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

            if (response.ok) {
                toast.success(recordId ? t('dentalRecord.updateSuccess') : t('dentalRecord.saveSuccess'));
                onSuccess?.();
            } else {
                const errorData = await response.json();
                toast.error(errorData?.error || t('dentalRecord.saveFailed'));
            }
        } catch (error) {
            console.error('Error adding dental record:', error);
            toast.error(t('dentalRecord.saveUnexpectedError'));
        } finally {
            setLoading(false);
        }
    };

    return (
        <form onSubmit={handleSubmit} className="space-y-6 md:space-y-10 p-2 md:p-4 bg-white rounded-xl shadow-lg border border-slate-100 w-full">
            <div className="space-y-6">
                <h2 className="text-xl md:text-2xl font-bold text-slate-800 border-b-2 border-slate-100 pb-3">{t('dentalRecord.dentalHistory')}</h2>
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div className="flex flex-col w-full gap-2">
                        <div className="flex items-center space-x-3">
                            <Checkbox
                                id="lossOfTeeth"
                                checked={formData.dentalHistory.lossOfTeeth}
                                onCheckedChange={(c) => handleChange('dentalHistory', 'lossOfTeeth', c)}
                                disabled={viewOnly}
                            />
                            <Label htmlFor="lossOfTeeth" className="font-medium cursor-pointer">{t('dentalRecord.lossOfTeeth')}</Label>
                        </div>
                        {formData.dentalHistory.lossOfTeeth && (
                            <div className="pl-0 sm:pl-7 w-full">
                                <Input
                                    placeholder={t('dentalRecord.causeOfLossPlaceholder')}
                                    value={formData.dentalHistory.causeOfLoss}
                                    onChange={(e) => handleChange('dentalHistory', 'causeOfLoss', e.target.value)}
                                    className="w-full"
                                    disabled={viewOnly}
                                />
                            </div>
                        )}
                    </div>

                    <div className="flex flex-col w-full gap-2">
                        <div className="flex items-center space-x-3">
                            <Checkbox
                                id="previousDentalTreatment"
                                checked={formData.dentalHistory.previousDentalTreatment}
                                onCheckedChange={(c) => handleChange('dentalHistory', 'previousDentalTreatment', c)}
                                disabled={viewOnly}
                            />
                            <Label htmlFor="previousDentalTreatment" className="font-medium cursor-pointer">{t('dentalRecord.previousDentalTreatment')}</Label>
                        </div>
                        {formData.dentalHistory.previousDentalTreatment && (
                            <div className="pl-0 sm:pl-7 w-full">
                                <Input
                                    placeholder={t('dentalRecord.previousTreatmentPlaceholder')}
                                    value={formData.dentalHistory.treatmentExplanation}
                                    onChange={(e) => handleChange('dentalHistory', 'treatmentExplanation', e.target.value)}
                                    className="w-full"
                                    disabled={viewOnly}
                                />
                            </div>
                        )}
                    </div>

                    <div className="flex flex-col sm:flex-row sm:items-center space-y-2 sm:space-y-0 sm:space-x-2">
                        <Label htmlFor="brushingFrequency">{t('dentalRecord.brushingFrequency')}</Label>
                        <Input
                            id="brushingFrequency"
                            className="w-full sm:w-40"
                            value={formData.dentalHistory.brushingFrequency}
                            onChange={(e) => handleChange('dentalHistory', 'brushingFrequency', e.target.value)}
                            disabled={viewOnly}
                        />
                    </div>

                    <div className="col-span-1 lg:col-span-2 flex gap-4 flex-wrap pt-4">
                        {['bleedingGums', 'badBreath', 'foodImpaction', 'mouthRinse', 'dentalFloss', 'anesthesiaProblems'].map((item) => (
                            <div key={item} className="flex items-center space-x-3 bg-slate-50 px-4 py-3 rounded-lg border border-transparent hover:border-slate-200 transition-colors cursor-pointer">
                                <Checkbox
                                    id={item}
                                    checked={(formData.dentalHistory as any)[item]}
                                    onCheckedChange={(c) => handleChange('dentalHistory', item, c)}
                                    disabled={viewOnly}
                                />
                                <Label htmlFor={item} className="capitalize font-medium cursor-pointer">{t(`dentalRecord.${item}`)}</Label>
                            </div>
                        ))}
                    </div>

                    <div className="col-span-1 lg:col-span-2 pt-4">
                        <Label className="text-base font-semibold text-slate-700 mb-2 block">{t('dentalRecord.dentalTrauma')}</Label>
                        <Input
                            className="bg-slate-50"
                            value={formData.dentalHistory.dentalTrauma}
                            onChange={(e) => handleChange('dentalHistory', 'dentalTrauma', e.target.value)}
                            disabled={viewOnly}
                        />
                    </div>
                </div>
            </div>

            <div className="space-y-6">
                <h2 className="text-xl md:text-2xl font-bold text-slate-800 border-b-2 border-slate-100 pb-3">{t('dentalRecord.extraoralExamination')}</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 md:gap-6">
                    {Object.keys(formData.extraoralExamination).map((key) => (
                        <div key={key} className="space-y-1">
                            <Label htmlFor={`extra-${key}`} className="capitalize">{t(`dentalRecord.${key}`)}</Label>
                            <Input
                                id={`extra-${key}`}
                                placeholder={t('dentalRecord.normalPlaceholder')}
                                value={(formData.extraoralExamination as any)[key]}
                                onChange={(e) => handleChange('extraoralExamination', key, e.target.value)}
                                disabled={viewOnly}
                            />
                        </div>
                    ))}
                </div>
            </div>

            <div className="space-y-6">
                <h2 className="text-xl md:text-2xl font-bold text-slate-800 border-b-2 border-slate-100 pb-3">{t('dentalRecord.intraoralExamination')}</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 md:gap-6">
                    {Object.keys(formData.intraoralExamination).map((key) => (
                        <div key={key} className="space-y-1">
                            <Label htmlFor={`intra-${key}`} className="capitalize">{t(`dentalRecord.${key}`)}</Label>
                            <Input
                                id={`intra-${key}`}
                                placeholder={t('dentalRecord.normalPlaceholder')}
                                value={(formData.intraoralExamination as any)[key]}
                                onChange={(e) => handleChange('intraoralExamination', key, e.target.value)}
                                disabled={viewOnly}
                            />
                        </div>
                    ))}
                </div>
            </div>

            <div className="space-y-6">
                <h2 className="text-2xl font-bold text-slate-800 border-b-2 border-slate-100 pb-3">{t('dentalRecord.odontogram')}</h2>
                <div className="bg-white p-2 rounded-xl border border-slate-200 -mx-2 md:-mx-4">
                    <InteractiveOdontogram
                        initialData={initialOdontogramData}
                        onChange={setOdontogramData}
                        readonly={viewOnly}
                    />
                </div>
                <div className="mt-4 space-y-4">
                    <div className="flex items-center justify-between">
                        <Label className="text-base font-semibold text-slate-700">{t('dentalRecord.proceduresPerformed')}</Label>
                        {!viewOnly && (
                            <Button type="button" variant="outline" size="sm" onClick={addProcedureRow}>
                                {t('dentalRecord.addProcedure')}
                            </Button>
                        )}
                    </div>
                    <div className="space-y-3">
                        {formData.procedures.map((item:any, index:any) => (
                            <div key={`procedure-${index}`} className="border border-slate-200 rounded-lg p-4 bg-slate-50/50 space-y-3">
                                <div className="flex items-center justify-between">
                                    <p className="text-sm font-medium text-slate-700">{t('dentalRecord.procedureEntry')} {index + 1}</p>
                                    {!viewOnly && formData.procedures.length > 1 && (
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            size="sm"
                                            className="text-red-600 hover:text-red-700"
                                            onClick={() => removeProcedureRow(index)}
                                        >
                                            {t('common.delete')}
                                        </Button>
                                    )}
                                </div>
                                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                                    <div className="space-y-1">
                                        <Label>{t('dentalRecord.procedurePerformed')}</Label>
                                        <Input
                                            value={item.procedure}
                                            onChange={(e) => handleProcedureChange(index, 'procedure', e.target.value)}
                                            disabled={viewOnly}
                                        />
                                    </div>
                                    <div className="space-y-1">
                                        <Label>{t('dentalRecord.procedureDate')}</Label>
                                        <Input
                                            type="date"
                                            value={item.date ? new Date(item.date).toISOString().split('T')[0] : ''}
                                            onChange={(e) => handleProcedureChange(index, 'date', e.target.value)}
                                            disabled={viewOnly}
                                        />
                                    </div>
                                    <div className="space-y-1">
                                        <Label>{t('dentalRecord.totalPaid')}</Label>
                                        <Input
                                            value={item.totalPaid}
                                            onChange={(e) => handleProcedureChange(index, 'totalPaid', e.target.value)}
                                            disabled={viewOnly}
                                        />
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
                <div className="mt-4">
                    <Label className="mb-2 block">{t('dentalRecord.notes')}</Label>
                    <Textarea
                        value={formData.odontogramNotes}
                        onChange={(e) => handleChange('root', 'odontogramNotes', e.target.value)}
                        placeholder={t('dentalRecord.odontogramNotesPlaceholder')}
                        className="min-h-[100px]"
                        disabled={viewOnly}
                    />
                </div>
            </div>

            <div className="space-y-6">
                <h2 className="text-2xl font-bold text-slate-800 border-b-2 border-slate-100 pb-3">{t('dentalRecord.radiographicAnalysis')}</h2>
                <Textarea
                    value={formData.radiographicAnalysis}
                    onChange={(e) => handleChange('root', 'radiographicAnalysis', e.target.value)}
                    className="min-h-[100px]"
                    disabled={viewOnly}
                />
            </div>

            <div className="space-y-6">
                <h2 className="text-2xl font-bold text-slate-800 border-b-2 border-slate-100 pb-3">{t('dentalRecord.treatmentPlan')}</h2>
                <Textarea
                    value={formData.treatmentPlan}
                    onChange={(e) => handleChange('root', 'treatmentPlan', e.target.value)}
                    className="min-h-[100px]"
                    disabled={viewOnly}
                />
            </div>

            <div className="flex flex-wrap justify-end gap-2 sm:gap-3 pt-4 sm:pt-6 border-t">
                {onCancel && (
                    <Button type="button" variant="outline" onClick={onCancel} className="w-full sm:w-auto">
                        {viewOnly ? t('common.close') : t('common.cancel')}
                    </Button>
                )}
                {initialData && (
                    <Button type="button" variant="outline" onClick={handlePrint} className="w-full sm:w-auto">
                        <Printer className="h-4 w-4 mr-2" />
                        {t('common.print')}
                    </Button>
                )}
                {!viewOnly && (
                    <Button type="submit" disabled={loading} className="w-full sm:w-auto">
                        {loading ? t('common.saving') : t('common.save')}
                    </Button>
                )}
            </div>
        </form>
    );
}
