'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 { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { Loader2 } from 'lucide-react';
import { useEffect, useState } from 'react';

interface ClinicalRecordFormProps {
    patientId: string;
    onSuccess?: () => void;
    onCancel?: () => void;
}

export default function MedicalRecordForm({ patientId, onSuccess, onCancel }: ClinicalRecordFormProps) {
    const { t, language } = useLanguage();
    const ATTITUDE_LITTLE_COOPERATION = 'littleCooperation';
    const ATTITUDE_DEFIANT = 'defiant';
    const [loading, setLoading] = useState(false);
    const [fetchingPatient, setFetchingPatient] = useState(true);
    const [patient, setPatient] = useState<any>(null);
    const [error, setError] = useState<string | null>(null);

    const [formData, setFormData] = useState({
        reasonForConsultation: '',
        medicalHistory: {
            underMedicalTreatment: false,
            takingMedication: false,
            medicationDetails: '',
            previousDentalTreatmentProblems: false,
            problemsDetails: '',
            immunizationsUpToDate: false,
            womenOnly: {
                pregnant: false,
                breastfeeding: false,
                oralContraceptives: false,
            },
        },
        habits: {
            smoker: false,
            nailBiting: false,
            lipBiting: false,
            thumbSucking: false,
            mouthBreather: false,
            atypicalSwallowing: false,
            bruxism: false,
            other: '',
        },
        patientAttitude: {
            cooperative: false,
            apprehensive: false,
            fearful: false,
            other: '',
        },
        comments: '',
    });

    useEffect(() => {
        if (patientId) {
            setFetchingPatient(true);
            fetch(`${API_BASE_URL}/api/patients/${patientId}`)
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        setPatient(data.data);
                    }
                })
                .catch(err => console.error(err))
                .finally(() => setFetchingPatient(false));
        }
    }, [patientId]);

    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 handleNestedChange = (section: string, subsection: string, field: string, value: any) => {
        setFormData((prev: any) => ({
            ...prev,
            [section]: {
                ...prev[section],
                [subsection]: {
                    ...prev[section][subsection],
                    [field]: value,
                },
            },
        }));
    };

    const handleSubmit = async (e: React.SyntheticEvent<HTMLFormElement>) => {
        e.preventDefault();
        setLoading(true);
        setError(null);

        try {
            const response = await fetch(`${API_BASE_URL}/api/patients/${patientId}/clinical-records`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
            });

            if (response.ok) {
                onSuccess?.();
            } else {
                const errorData = await response.json();
                setError(errorData.message || t('medicalRecord.saveFailed'));
            }
        } catch (error) {
            console.error('Error adding clinical record:', error);
            setError(t('common.unexpectedError'));
        } finally {
            setLoading(false);
        }
    };

    const calculateAge = (dob: string) => {
        if (!dob) return '';
        const ageDifMs = Date.now() - new Date(dob).getTime();
        const ageDate = new Date(ageDifMs);
        return Math.abs(ageDate.getUTCFullYear() - 1970);
    };

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

    if (fetchingPatient) {
        return <div className="flex justify-center p-8"><Loader2 className="animate-spin text-primary" /></div>;
    }

    if (!patient) {
        return <div className="text-red-500 p-4">{t('medicalRecord.patientNotFound')}</div>;
    }

    return (
        <div className="space-y-6 max-w-5xl mx-auto p-2 sm:p-8 bg-white text-slate-900 font-sans">
            <div className="text-center border-b-2 border-slate-800 pb-4 mb-6">
                <h1 className="text-2xl sm:text-3xl font-bold uppercase tracking-wide text-slate-900">{t('medicalRecord.title')}</h1>
            </div>

            <form onSubmit={handleSubmit} className="space-y-6">
                {/* Patient Personal Information Section */}
                <div className="space-y-4 mb-8">
                    <h2 className="text-xl font-bold text-slate-900 border-b border-slate-300 pb-1">{t('medicalRecord.personalInfo')}</h2>
                    <div className="grid grid-cols-1 md:grid-cols-12 gap-x-4 gap-y-4 text-sm">
                        <div className="md:col-span-6 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap min-w-20">{t('medicalRecord.fullName')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{patient.userId?.firstName} {patient.userId?.lastName}</div>
                        </div>
                        <div className="md:col-span-3 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.sex')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{getLocalizedGender(patient.gender)}</div>
                        </div>
                        <div className="md:col-span-3 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.age')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{calculateAge(patient.dateOfBirth)}</div>
                        </div>

                        <div className="md:col-span-6 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.occupation')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{patient.occupation || ''}</div>
                        </div>
                        <div className="md:col-span-6 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.dob')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{patient.dateOfBirth ? new Date(patient.dateOfBirth).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US', { timeZone: 'UTC' }) : ''}</div>
                        </div>

                        <div className="md:col-span-6 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.educationLevel')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{patient.educationLevel || ''}</div>
                        </div>
                        <div className="md:col-span-6 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.maritalStatus')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{patient.maritalStatus || ''}</div>
                        </div>

                        <div className="md:col-span-12 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.address')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{patient.address || ''}</div>
                        </div>

                        <div className="md:col-span-6 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.phoneNumbers')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{patient.userId?.phone || ''}</div>
                        </div>
                        <div className="md:col-span-6 flex items-baseline gap-2" />

                        <div className="md:col-span-12 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.emergencyContact')}</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">
                                {patient.emergencyContact?.name} ({patient.emergencyContact?.phone || ''}) - {patient.emergencyContact?.relation || ''}
                            </div>
                        </div>

                        <div className="md:col-span-4 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.idNumber')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{patient.nationalId || ''}</div>
                        </div>
                        <div className="md:col-span-4 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.insurance')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{patient.insurance?.provider || ''}</div>
                        </div>
                        <div className="md:col-span-4 flex items-baseline gap-2">
                            <Label className="font-semibold whitespace-nowrap">{t('medicalRecord.policyNumber')}:</Label>
                            <div className="border-b border-slate-400 w-full px-2 py-0.5">{patient.insurance?.policyNumber || ''}</div>
                        </div>
                    </div>
                </div>

                {/* Reason for Consultation */}
                <div className="space-y-4 mb-8">
                    <h2 className="text-xl font-bold text-slate-900 border-b border-slate-300 pb-1">{t('medicalRecord.reasonForConsultation')}</h2>
                    <Textarea
                        className="min-h-[80px] border-slate-300 resize-none bg-slate-50"
                        placeholder={t('medicalRecord.reasonPlaceholder')}
                        value={formData.reasonForConsultation}
                        onChange={(e) => handleChange('root', 'reasonForConsultation', e.target.value)}
                    />

                    <div className="space-y-3 mt-4 text-sm">
                        <div className="flex flex-col md:flex-row md:items-center gap-2 md:gap-4">
                            <span className="min-w-[400px]">{t('medicalRecord.underMedicalTreatment')}</span>
                            <div className="flex gap-4">
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="underTreatmentYes"
                                        checked={formData.medicalHistory.underMedicalTreatment}
                                        onCheckedChange={(c) => handleChange('medicalHistory', 'underMedicalTreatment', !!c)}
                                    />
                                    <Label htmlFor="underTreatmentYes">{t('common.yes')}</Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="underTreatmentNo"
                                        checked={!formData.medicalHistory.underMedicalTreatment}
                                        onCheckedChange={(c) => handleChange('medicalHistory', 'underMedicalTreatment', !c)}
                                    />
                                    <Label htmlFor="underTreatmentNo">{t('common.no')}</Label>
                                </div>
                            </div>
                        </div>
                        <div className="flex flex-col md:flex-row md:items-center gap-2">
                            <span className="whitespace-nowrap">{t('medicalRecord.takingMedication')}</span>
                            <div className="flex gap-4 ml-2">
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="medsYes"
                                        checked={formData.medicalHistory.takingMedication}
                                        onCheckedChange={(c) => handleChange('medicalHistory', 'takingMedication', !!c)}
                                    />
                                    <Label htmlFor="medsYes">{t('common.yes')}</Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="medsNo"
                                        checked={!formData.medicalHistory.takingMedication}
                                        onCheckedChange={(c) => handleChange('medicalHistory', 'takingMedication', !c)}
                                    />
                                    <Label htmlFor="medsNo">{t('common.no')}</Label>
                                </div>
                            </div>
                            {formData.medicalHistory.takingMedication && (
                                <div className="flex-1 flex items-center gap-2">
                                    <span className="text-xs font-bold uppercase">{t('medicalRecord.which')}</span>
                                    <Input
                                        className="h-8 border-0 border-b border-slate-400 rounded-none px-0 focus-visible:ring-0"
                                        value={formData.medicalHistory.medicationDetails}
                                        onChange={(e) => handleChange('medicalHistory', 'medicationDetails', e.target.value)}
                                    />
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                <Separator className="bg-slate-300" />

                {/* Split Section: Medical History & Women Only */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8">
                    {/* Medical History Left Column */}
                    <div className="space-y-4">
                        <h2 className="text-xl font-bold text-slate-900 border-b border-slate-300 pb-1">{t('medicalRecord.medicalHistory')}</h2>
                        <div className="space-y-4 text-sm">
                            <div className="flex flex-col gap-2">
                                <span>{t('medicalRecord.dentalProblems')}</span>
                                <div className="flex gap-4">
                                    <div className="flex items-center space-x-2">
                                        <Checkbox
                                            id="dentalProbYes"
                                            checked={formData.medicalHistory.previousDentalTreatmentProblems}
                                            onCheckedChange={(c) => handleChange('medicalHistory', 'previousDentalTreatmentProblems', !!c)}
                                        />
                                        <Label htmlFor="dentalProbYes">{t('common.yes')}</Label>
                                    </div>
                                    <div className="flex items-center space-x-2">
                                        <Checkbox
                                            id="dentalProbNo"
                                            checked={!formData.medicalHistory.previousDentalTreatmentProblems}
                                            onCheckedChange={(c) => handleChange('medicalHistory', 'previousDentalTreatmentProblems', !c)}
                                        />
                                        <Label htmlFor="dentalProbNo">{t('common.no')}</Label>
                                    </div>
                                </div>
                                {formData.medicalHistory.previousDentalTreatmentProblems && (
                                    <Input
                                        placeholder={t('medicalRecord.which')}
                                        className="border-0 border-b border-slate-400 rounded-none px-0 focus-visible:ring-0"
                                        value={formData.medicalHistory.problemsDetails}
                                        onChange={(e) => handleChange('medicalHistory', 'problemsDetails', e.target.value)}
                                    />
                                )}
                            </div>

                            <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
                                <span>{t('medicalRecord.immunizations')}</span>
                                <div className="flex gap-4">
                                    <div className="flex items-center space-x-2">
                                        <Checkbox
                                            id="immunYes"
                                            checked={formData.medicalHistory.immunizationsUpToDate}
                                            onCheckedChange={(c) => handleChange('medicalHistory', 'immunizationsUpToDate', !!c)}
                                        />
                                        <Label htmlFor="immunYes">{t('common.yes')}</Label>
                                    </div>
                                    <div className="flex items-center space-x-2">
                                        <Checkbox
                                            id="immunNo"
                                            checked={!formData.medicalHistory.immunizationsUpToDate}
                                            onCheckedChange={(c) => handleChange('medicalHistory', 'immunizationsUpToDate', !c)}
                                        />
                                        <Label htmlFor="immunNo">{t('common.no')}</Label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Women Only Right Column */}
                    <div className="space-y-4">
                        <h2 className="text-xl font-bold text-slate-900 border-b border-slate-300 pb-1">{t('medicalRecord.womenOnly')}</h2>
                        <div className="space-y-3 text-sm">
                            {[
                                { id: 'pregnant', label: t('medicalRecord.pregnant') },
                                { id: 'breastfeeding', label: t('medicalRecord.breastfeeding') },
                                { id: 'oralContraceptives', label: t('medicalRecord.oralContraceptives') }
                            ].map((item) => (
                                <div key={item.id} className="flex justify-between items-center max-w-xs">
                                    <span className="font-medium">• {item.label}:</span>
                                    <div className="flex gap-4">
                                        <div className="flex items-center space-x-2">
                                            <Checkbox
                                                id={`${item.id}Yes`}
                                                checked={(formData.medicalHistory.womenOnly as any)[item.id]}
                                                onCheckedChange={(c) => handleNestedChange('medicalHistory', 'womenOnly', item.id, !!c)}
                                            />
                                            <Label htmlFor={`${item.id}Yes`}>{t('common.yes')}</Label>
                                        </div>
                                        <div className="flex items-center space-x-2">
                                            <Checkbox
                                                id={`${item.id}No`}
                                                checked={!(formData.medicalHistory.womenOnly as any)[item.id]}
                                                onCheckedChange={(c) => handleNestedChange('medicalHistory', 'womenOnly', item.id, !c)}
                                            />
                                            <Label htmlFor={`${item.id}No`}>{t('common.no')}</Label>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>

                <Separator className="bg-slate-300" />

                {/* Split Section: Habits & Patient Attitude */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8">
                    {/* Habits Left */}
                    <div className="space-y-4">
                        <h2 className="text-xl font-bold text-slate-900 border-b border-slate-300 pb-1">{t('medicalRecord.habits')}</h2>
                        <div className="grid grid-cols-2 gap-3 text-sm">
                            {[
                                { id: 'smoker', label: t('medicalRecord.smoker') },
                                { id: 'nailBiting', label: t('medicalRecord.nailBiting') },
                                { id: 'lipBiting', label: t('medicalRecord.lipBiting') },
                                { id: 'thumbSucking', label: t('medicalRecord.fingerSucking') },
                                { id: 'mouthBreather', label: t('medicalRecord.mouthBreather') },
                                { id: 'atypicalSwallowing', label: t('medicalRecord.atypicalSwallowing') },
                                { id: 'bruxism', label: t('medicalRecord.bruxism') }
                            ].map((habit) => (
                                <div key={habit.id} className="flex items-center space-x-2">
                                    <Checkbox
                                        id={habit.id}
                                        checked={(formData.habits as any)[habit.id]}
                                        onCheckedChange={(c) => handleChange('habits', habit.id, c)}
                                    />
                                    <Label htmlFor={habit.id}>{habit.label}</Label>
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Patient Attitude Right */}
                    <div className="space-y-4">
                        <h2 className="text-xl font-bold text-slate-900 border-b border-slate-300 pb-1">{t('medicalRecord.patientAttitude')}</h2>
                        <div className="grid grid-cols-2 gap-3 text-sm">
                            {[
                                { id: 'cooperative', label: t('medicalRecord.cooperative') },
                                { id: 'littleCooperation', label: t('medicalRecord.littleCooperation') },
                                { id: 'apprehensive', label: t('medicalRecord.apprehensive') },
                                { id: 'fearful', label: t('medicalRecord.fearful') },
                                { id: 'defiant', label: t('medicalRecord.defiant') }
                            ].map((att) => (
                                <div key={att.id} className="flex items-center space-x-2">
                                    <Checkbox
                                        id={att.id}
                                        checked={
                                            // Mapping special added UI keys to model keys
                                            att.id === 'littleCooperation' ? formData.patientAttitude.other === ATTITUDE_LITTLE_COOPERATION :
                                                att.id === 'defiant' ? formData.patientAttitude.other === ATTITUDE_DEFIANT :
                                                    (formData.patientAttitude as any)[att.id]
                                        }
                                        onCheckedChange={(c) => {
                                            if (att.id === 'littleCooperation' || att.id === 'defiant') {
                                                handleChange('patientAttitude', 'other', c ? (att.id === 'littleCooperation' ? ATTITUDE_LITTLE_COOPERATION : ATTITUDE_DEFIANT) : '');
                                            } else {
                                                handleChange('patientAttitude', att.id, c);
                                            }
                                        }}
                                    />
                                    <Label htmlFor={att.id}>{att.label}</Label>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>

                {/* Comments */}
                <div className="space-y-2">
                    <h2 className="text-xl font-bold text-slate-900 border-b border-slate-300 pb-1">{t('medicalRecord.comments')}</h2>
                    <Textarea
                        className="min-h-[100px] bg-slate-50"
                        value={formData.comments}
                        onChange={(e) => handleChange('root', 'comments', e.target.value)}
                    />
                </div>

                <div className="flex justify-end gap-3 pt-6 border-t print:hidden">
                    {onCancel && (
                        <Button type="button" variant="outline" onClick={onCancel}>
                            {t('common.cancel')}
                        </Button>
                    )}
                    <Button type="submit" disabled={loading}>
                        {loading ? t('common.saving') : t('common.save')}
                    </Button>
                </div>
                {error && (
                    <div className="text-red-500 text-sm mt-2 text-right">
                        {error}
                    </div>
                )}
            </form>
        </div>
    );
}
