'use client';

import PrescriptionForm from '@/app/components/Prescription/PrescriptionForm';
import { Button } from '@/components/ui/button';
import { api } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';

import { getDoctorPrintData, printRecord } from '@/lib/print-service';
import { ArrowLeft, Edit, Printer } from 'lucide-react';
import { useParams, useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

export default function PrescriptionDetailPage() {
    const router = useRouter();
    const params = useParams<{ id: string; prescriptionId: string }>();
    const { user } = useAuthStore();
    const { t, language } = useLanguage();
    const [prescription, setPrescription] = useState<any>(null);
    const [patient, setPatient] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const [editing, setEditing] = useState(false);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const [prescRes, patientRes] = await Promise.all([
                    api.prescriptions.getById(params.prescriptionId),
                    api.patients.getById(params.id),
                ]);
                if (prescRes.success && prescRes.data) setPrescription(prescRes.data);
                if (patientRes.success && patientRes.data) setPatient(patientRes.data);
            } catch (err) {
                console.error('Failed to fetch data:', err);
            } finally {
                setLoading(false);
            }
        };
        fetchData();
    }, [params.prescriptionId, params.id]);

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

    const handlePrint = () => {
        if (!prescription) return;

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

        const patientName = patient ? `${patient.userId?.firstName || ''} ${patient.userId?.lastName || ''}` : '';
        const patientPhone = patient?.userId?.phone || '';
        const patientGender = patient?.gender || '';
        const patientDob = patient?.dateOfBirth ? formatDate(patient.dateOfBirth) : '';

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

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

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

        let content: string;

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

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

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

        printRecord({
            doctor,
            clinic,
            patient: {
                name: patientName,
                dob: patientDob,
                gender: patientGender,
                phone: patientPhone,
                id: patient?.nationalId,
                insurance: [patient?.insurance?.provider, patient?.insurance?.policyNumber ? `#${patient.insurance.policyNumber}` : ''].filter(Boolean).join(' ') || undefined,
            },
            record: {
                date: formatDate(prescription.createdAt),
                type: docTypeLabel,
                title: isPrescription ? t('prescriptions.medicalPrescription') : undefined,
            },
            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
        });
    };

    if (loading) return <div className="p-8">{t('common.loading')}</div>;
    if (!prescription) return <div className="p-8 text-red-600">{t('patientDetails.prescriptionNotFound')}</div>;

    if (editing) {
        const initialData = {
            _id: prescription._id,
            documentType: prescription.documentType || 'Prescription',
            medications: prescription.medications || [],
            diagnosis: prescription.diagnosis || '',
            freeText: prescription.freeText || '',
            notes: prescription.notes || '',
        };

        return (
            <div className="container mx-auto py-8 max-w-3xl">
                <PrescriptionForm
                    patientId={params.id}
                    initialData={initialData}
                    onSuccess={() => {
                        setEditing(false);
                        setLoading(true);
                        api.prescriptions.getById(params.prescriptionId).then(res => {
                            if (res.success && res.data) setPrescription(res.data);
                            setLoading(false);
                        });
                    }}
                    onCancel={() => setEditing(false)}
                />
            </div>
        );
    }

    return (
            <div className="space-y-6 md:space-y-10 p-4 md:p-8 bg-white rounded-xl shadow-lg border border-slate-100 max-w-3xl mx-auto my-8">
            <div className="flex justify-between items-center border-b-2 border-slate-100 pb-4">
                <Button variant="ghost" onClick={() => router.push(`/patients/${params.id}`)}>
                    <ArrowLeft className="h-4 w-4 mr-2" /> {t('patientDetails.backToPatient')}
                </Button>
                <div className="flex gap-2">
                    <Button variant="outline" onClick={() => setEditing(true)}>
                        <Edit className="h-4 w-4 mr-2" /> {t('common.edit')}
                    </Button>
                    <Button variant="outline" onClick={handlePrint}>
                        <Printer className="h-4 w-4 mr-2" /> {t('common.print')}
                    </Button>
                </div>
            </div>

            <div className="space-y-6">
                <div className="flex justify-between items-center">
                    <div className="flex items-center gap-3">
                        <h1 className="text-2xl md:text-3xl font-bold text-slate-800">{t('patientDetails.prescriptionDetails')}</h1>
                        {prescription.documentType && prescription.documentType !== 'Prescription' && (
                            <span className="px-3 py-1 rounded-full bg-slate-100 text-slate-600 text-sm font-medium">
                                {(() => {
                                    switch (prescription.documentType) {
                                        case 'Referral': return t('prescriptions.documentTypeReferral');
                                        case 'Certification': return t('prescriptions.documentTypeCertification');
                                        case 'Medical Leave': return t('prescriptions.documentTypeMedicalLeave');
                                        case 'Laboratory': return t('prescriptions.documentTypeLaboratory');
                                        case 'Imaging': return t('prescriptions.documentTypeImaging');
                                        default: return prescription.documentType;
                                    }
                                })()}
                            </span>
                        )}
                    </div>
                    <span className="text-sm text-slate-500">{formatDate(prescription.createdAt)}</span>
                </div>

                {prescription.diagnosis && (
                    <div className="space-y-2">
                        <h3 className="text-xl font-bold text-slate-800 border-b border-slate-100 pb-2">{t('patientDetails.diagnosisLabel')}</h3>
                        <p className="text-base">{prescription.diagnosis}</p>
                    </div>
                )}

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

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

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

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