import { toReachableAbsoluteUrl } from './url-utils';
import enMessages from '@/messages/en.json';
import esMessages from '@/messages/es.json';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || '';

export const toAbsoluteUrl = (path: string | undefined): string =>
    toReachableAbsoluteUrl(path, API_BASE_URL);

const resolveMessages = () => {
    const lang = typeof window !== 'undefined' && localStorage.getItem('language') === 'en' ? 'en' : 'es';
    return lang === 'en' ? enMessages : esMessages;
};

type GenderLabels = {
    male: string;
    female: string;
    other: string;
};

export const formatGenderForPrint = (
    genderValue: string | undefined,
    labels: GenderLabels
): string => {
    const normalized = (genderValue || '').trim().toLowerCase();

    if (normalized === 'male' || normalized === 'm') return labels.male;
    if (normalized === 'female' || normalized === 'f') return labels.female;
    if (normalized === 'other' || normalized === 'o') return labels.other;

    return genderValue?.trim() || '';
};

/**
 * Extracts consistent doctor + clinic data for printing.
 * Uses the record's populated doctorId as primary source, falls back to the logged-in user.
 * Call this once and pass the result to printRecord().
 */
export const getDoctorPrintData = (
    record: any, // clinical record, dental record, or prescription — must have doctorId populated
    user: any,   // from useAuthStore
    labels?: { doctor?: string }
): Pick<PrintData, 'doctor' | 'clinic'> => {
    const doctorId = record?.doctorId;
    const doctorUserId = doctorId?.userId;
    const doctorLabel = labels?.doctor || '';

    const name = doctorUserId?.firstName
        ? `${doctorUserId.firstName} ${doctorUserId.lastName || ''}`.trim()
        : user?.firstName
            ? `${user.firstName} ${user.lastName || ''}`.trim()
            : doctorLabel;

    const specialty = doctorId?.specialization || user?.doctor?.specialization || '';
    const license = doctorId?.licenseNumber || user?.doctor?.licenseNumber || '';
    const signatureUrl = toAbsoluteUrl(doctorId?.signatureUrl || user?.doctor?.signatureUrl);
    const logoUrl = toAbsoluteUrl(doctorUserId?.profileImage || user?.profileImage);

    const clinicName = doctorUserId?.clinic?.name || user?.clinic?.name || '';
    const clinicAddress = doctorUserId?.clinic?.address || user?.clinic?.address || '';
    const clinicPhone = doctorUserId?.clinic?.phone || user?.clinic?.phone || '';

    return {
        doctor: { name, specialty, license, signatureUrl, logoUrl },
        clinic: { name: clinicName, address: clinicAddress, phone: clinicPhone },
    };
};

export interface PrintData {
    doctor: {
        name: string;
        specialty?: string;
        license?: string;
        signatureUrl?: string; // Full URL or relative path
        logoUrl?: string; // Doctor profile image URL
    };
    clinic: {
        name: string;
        address?: string;
        phone?: string;
        logoUrl?: string;
    };
    patient: {
        name: string;
        dob?: string;
        gender?: string;
        phone?: string;
        id?: string;
        insurance?: string;
    };
    record: {
        date: string; // Formatted date string
        type: string;
        title?: string;
    };
    labels?: {
        patient?: string;
        phone?: string;
        gender?: string;
        dob?: string;
        id?: string;
        insurance?: string;
        doctor?: string;
        licenseNumber?: string;
    };
    content: string; // The specific HTML body for the record
}

// ─── Odontogram SVG Generator ────────────────────────────────────────────────

type ToothSurface = { top: string; bottom: string; left: string; right: string; center: string };
type PrintTooth = { id: number; status: string; surfaces: ToothSurface };
type OdontogramLegendLabels = {
    healthy: string;
    caries: string;
    filled: string;
    missing: string;
    exodontia: string;
    crown: string;
    rootCanal: string;
    implant: string;
};

const STATUS_COLOR: Record<string, string> = {
    caries:  '#f87171', // red-400
    filled:  '#60a5fa', // blue-400
    crown:   '#facc15', // yellow-400
    rct:     '#c084fc', // purple-400
    implant: '#10b981', // emerald-500
    missing: '#ffffff',
    exodontia: '#ffffff',
    healthy: '#ffffff',
};

const toothSvg = (tooth: PrintTooth): string => {
    const isMissing = tooth.status === 'missing';
    const isExodontia = tooth.status === 'exodontia';
    const isImplant = tooth.status === 'implant';
    const isAbsentTooth = isMissing || isExodontia;
    const c = (s: string) => STATUS_COLOR[s] ?? '#ffffff';

    const topC    = isAbsentTooth ? '#fff' : c(tooth.surfaces?.top    ?? 'healthy');
    const bottomC = isAbsentTooth ? '#fff' : c(tooth.surfaces?.bottom ?? 'healthy');
    const leftC   = isAbsentTooth ? '#fff' : c(tooth.surfaces?.left   ?? 'healthy');
    const rightC  = isAbsentTooth ? '#fff' : c(tooth.surfaces?.right  ?? 'healthy');
    const centerC = isAbsentTooth ? '#fff' : c(tooth.surfaces?.center ?? 'healthy');
    const opacity = isAbsentTooth ? '0.4' : '1';

    return `
      <g opacity="${opacity}">
        <rect x="0" y="0" width="32" height="32" fill="#f8fafc" stroke="#cbd5e1" stroke-width="1"/>
        <path d="M0,0 L32,0 L24,8 L8,8 Z"        fill="${topC}"    stroke="#cbd5e1" stroke-width="0.5"/>
        <path d="M0,32 L32,32 L24,24 L8,24 Z"     fill="${bottomC}" stroke="#cbd5e1" stroke-width="0.5"/>
        <path d="M0,0 L0,32 L8,24 L8,8 Z"         fill="${leftC}"   stroke="#cbd5e1" stroke-width="0.5"/>
        <path d="M32,0 L32,32 L24,24 L24,8 Z"     fill="${rightC}"  stroke="#cbd5e1" stroke-width="0.5"/>
        <rect x="8" y="8" width="16" height="16"  fill="${centerC}" stroke="#cbd5e1" stroke-width="0.5"/>
        ${isMissing ? '<path d="M2,2 L30,30 M30,2 L2,30" stroke="#1e293b" stroke-width="2"/>' : ''}
        ${isExodontia ? '<path d="M2,2 L30,30 M30,2 L2,30" stroke="#dc2626" stroke-width="2"/>' : ''}
        ${isImplant ? '<circle cx="16" cy="13" r="4.5" fill="none" stroke="#0f766e" stroke-width="1.8"/><line x1="16" y1="18" x2="16" y2="27" stroke="#0f766e" stroke-width="1.8"/><line x1="12" y1="20.5" x2="20" y2="20.5" stroke="#0f766e" stroke-width="1.5"/>' : ''}
      </g>`;
};

/**
 * Builds a full printable HTML odontogram from a dentalRecord's odontogram map.
 * Pass record.odontogram (the plain-object from the API response).
 */
export const buildOdontogramHtml = (
    odontogramMap: Record<string, any> | undefined,
    customLegendLabels?: Partial<OdontogramLegendLabels>
): string => {
    // Merge saved teeth over a full healthy baseline
    const ALL_TEETH = [
        18,17,16,15,14,13,12,11, 21,22,23,24,25,26,27,28,
        48,47,46,45,44,43,42,41, 31,32,33,34,35,36,37,38,
        56,55,54,53,52,51, 61,62,63,64,65,66,
        86,85,84,83,82,81, 71,72,73,74,75,76
    ];

    const healthy = (): PrintTooth['surfaces'] => ({ top:'healthy', bottom:'healthy', left:'healthy', right:'healthy', center:'healthy' });
    const state: Record<number, PrintTooth> = {};
    ALL_TEETH.forEach(id => { state[id] = { id, status: 'healthy', surfaces: healthy() }; });

    if (odontogramMap) {
        Object.entries(odontogramMap).forEach(([key, val]: [string, any]) => {
            const id = parseInt(key);
            if (!isNaN(id) && state[id]) {
                state[id] = {
                    id,
                    status:   val.status   ?? 'healthy',
                    surfaces: val.surfaces ?? healthy(),
                };
            }
        });
    }

    const GAP = 3; // px between teeth
    const W   = 32; // tooth SVG width
    const STEP = W + GAP;
    const rowH = W + 20; // extra for tooth number label

    const renderRow = (ids: number[], flipped = false): string => {
        const rowW = ids.length * STEP - GAP;
        return `
          <svg width="${rowW}" height="${rowH}" xmlns="http://www.w3.org/2000/svg">
            ${ids.map((id, i) => {
                const x = i * STEP;
                const labelY = flipped ? rowH - 2 : 12;
                const svgY   = flipped ? 0 : 16;
                return `
                  <text x="${x + W / 2}" y="${labelY}" text-anchor="middle" font-size="8" fill="#94a3b8" font-family="Arial,sans-serif">${id}</text>
                  <g transform="translate(${x},${svgY})">${toothSvg(state[id])}</g>`;
            }).join('')}
          </svg>`;
    };

    const legendDefaults: OdontogramLegendLabels = {
        healthy: 'Healthy',
        caries: 'Caries',
        filled: 'Filled',
        missing: 'Missing',
        exodontia: 'Exodontia',
        crown: 'Crown',
        rootCanal: 'Root Canal',
        implant: 'Implant',
    };
    const legendLabels = { ...legendDefaults, ...customLegendLabels };

    const legend = `
      <div style="display:flex;gap:12px;flex-wrap:wrap;font-size:10px;color:#475569;margin-top:8px;font-family:Arial,sans-serif;">
        ${Object.entries({ [legendLabels.healthy]:'#fff', [legendLabels.caries]:'#f87171', [legendLabels.filled]:'#60a5fa', [legendLabels.missing]:'#e2e8f0', [legendLabels.exodontia]:'#dc2626', [legendLabels.crown]:'#facc15', [legendLabels.rootCanal]:'#c084fc', [legendLabels.implant]:'#10b981' })
            .map(([lbl, col]) => `<span style="display:flex;align-items:center;gap:4px;"><span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:${col};border:1px solid #cbd5e1;"></span>${lbl}</span>`)
            .join('')}
      </div>`;

    return `
      <div style="font-family:Arial,sans-serif;">
        <div style="display:flex;gap:24px;justify-content:center;margin-bottom:6px;">
          ${renderRow([18,17,16,15,14,13,12,11], false)}
          ${renderRow([21,22,23,24,25,26,27,28], false)}
        </div>
        <div style="border-top:1px dashed #cbd5e1;margin:4px 0;"></div>
        <div style="display:flex;gap:24px;justify-content:center;margin-top:6px;">
          ${renderRow([48,47,46,45,44,43,42,41], true)}
          ${renderRow([31,32,33,34,35,36,37,38], true)}
        </div>
        <div style="border-top:1px dashed #cbd5e1;margin:8px 0;"></div>
        <div style="display:flex;gap:24px;justify-content:center;margin-bottom:6px;">
          ${renderRow([56,55,54,53,52,51], false)}
          ${renderRow([61,62,63,64,65,66], false)}
        </div>
        <div style="border-top:1px dashed #cbd5e1;margin:4px 0;"></div>
        <div style="display:flex;gap:24px;justify-content:center;margin-top:6px;">
          ${renderRow([86,85,84,83,82,81], true)}
          ${renderRow([71,72,73,74,75,76], true)}
        </div>
        ${legend}
      </div>`;
};

// ─── printRecord ─────────────────────────────────────────────────────────────
export const printRecord = (data: PrintData) => {
    const messages: any = resolveMessages();

    const signatureUrl = data.doctor.signatureUrl;
    const logoUrl = data.clinic.logoUrl || `${window.location.origin}/assets/logo-v4-fixed.png`;
    const doctorLogoUrl = data.doctor.logoUrl;
    const labels = {
        patient: data.labels?.patient || messages?.common?.patient || '',
        phone: data.labels?.phone || messages?.common?.phone || '',
        gender: data.labels?.gender || messages?.common?.gender || '',
        dob: data.labels?.dob || messages?.common?.dob || '',
        id: data.labels?.id || messages?.common?.id || '',
        insurance: data.labels?.insurance || messages?.medicalRecord?.insurance || '',
        doctor: data.labels?.doctor || messages?.common?.doctor || '',
        licenseNumber: data.labels?.licenseNumber || messages?.common?.licenseNumber || '',
    };

    const html = `
        <html>
            <head>
                <title>${data.record.type} - ${data.patient.name}</title>
                <style>
                    * { margin: 0; padding: 0; box-sizing: border-box; }
                    body { font-family: 'Segoe UI', Arial, sans-serif; padding: 0; color: #1e293b; }
                    .page { max-width: 800px; margin: 0 auto; padding: 40px; }
                    .header { display: flex; justify-content: space-between; align-items: flex-start; padding-bottom: 20px; border-bottom: 3px solid #0891b2; margin-bottom: 24px; }
                    .header-left { display: flex; flex-direction: column; }
                    .header-left h1 { font-size: 24px; color: #0891b2; margin-bottom: 4px; font-weight: 800; }
                    .header-left p { font-size: 14px; color: #64748b; margin-bottom: 2px; }
                    .header-left .specialty { color: #475569; font-weight: 600; font-size: 15px; margin-bottom: 4px; }
                    .header-left .clinic-details { font-size: 12px; color: #64748b; margin-top: 4px; }
                    .header-right { text-align: right; display: flex; flex-direction: column; align-items: flex-end; }
                    .header-right .doctor-logo { height: 80px; width: 80px; object-fit: cover; border-radius: 50%; border: 2px solid #e2e8f0; display: block; margin: 0 auto 8px; }
                    .header-right .date { font-size: 14px; color: #64748b; }

                    .patient-info { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px 20px; margin-bottom: 24px; display: grid; grid-template-columns: 1fr 1fr; gap: 8px 32px; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                    .patient-info .info-item { font-size: 13px; }
                    .patient-info .info-label { color: #64748b; font-weight: 500; }
                    .patient-info .info-value { color: #1e293b; font-weight: 600; }

                    .content { word-break: break-all; overflow-wrap: anywhere; }
                    .section { margin-bottom: 24px; }
                    .section-title { font-size: 14px; font-weight: 700; color: #0891b2; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 12px; padding-bottom: 6px; border-bottom: 1px solid #e2e8f0; }
                    .section-text { font-size: 14px; line-height: 1.6; white-space: pre-wrap; }

                    /* Utility classes for content */
                    .diagnosis-text { font-size: 15px; padding: 10px 0; line-height: 1.6; white-space: pre-wrap; }
                    table { width: 100%; border-collapse: collapse; margin-bottom: 15px; }
                    th { background: #f1f5f9; padding: 10px 12px; text-align: left; font-size: 12px; font-weight: 700; color: #475569; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #e2e8f0; }
                    td { padding: 10px 12px; border-bottom: 1px solid #e2e8f0; font-size: 14px; }
                    .notes { background: #fffbeb; border: 1px solid #fde68a; border-radius: 8px; padding: 12px 16px; font-size: 14px; line-height: 1.6; white-space: pre-wrap; word-break: break-word; overflow-wrap: break-word; text-align: left; -webkit-print-color-adjust: exact; print-color-adjust: exact; }

                    .badge { display: inline-block; padding: 2px 10px; background: #f1f5f9; border: 1px solid #e2e8f0; border-radius: 999px; font-size: 12px; color: #475569; font-weight: 500; }

                    .footer { margin-top: 48px; padding-top: 20px; border-top: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: flex-end; }
                    .clinic-info { font-size: 12px; color: #64748b; max-width: 50%; }
                    .signature { text-align: center; }
                    .signature .line { width: 100%; border-top: 1px solid #1e293b; margin-bottom: 6px; }
                    .signature .name { font-size: 14px; font-weight: 600; }
                    .signature .label { font-size: 11px; color: #64748b; }
                    .signature-image { max-width: 150px; max-height: 60px; margin-bottom: 4px; object-fit: contain; display: block; margin-left: auto; margin-right: auto; }

                    body::before {
                        content: "";
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background-image: url('${logoUrl}');
                        background-repeat: no-repeat;
                        background-position: center;
                        background-size: 80%;
                        opacity: 0.04;
                        z-index: -1;
                        pointer-events: none;
                    }

                    @media print {
                        body { padding: 0; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                        .page { max-width: 100%; padding: 20px 30px; }
                        body::before { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                    }
                </style>
            </head>
            <body>
                <div class="page">
                    <div class="header">
                        <div class="header-left">
                            <h1>${data.doctor.name}</h1>
                            <p class="specialty">${data.doctor.specialty || ''}</p>
                            <div class="clinic-details">
                                <div>${data.clinic.name}</div>
                                ${data.clinic.address ? `<div>${data.clinic.address}</div>` : ''}
                                ${data.clinic.phone ? `<div>${data.clinic.phone}</div>` : ''}
                            </div>
                        </div>
                        <div class="header-right">
                            ${doctorLogoUrl ? `<img src="${doctorLogoUrl}" alt="" class="doctor-logo" style="display:none;" onload="this.style.display='block'" onerror="this.style.display='none'" />` : ''}
                            <div class="date">${data.record.date}</div>
                        </div>
                    </div>

                    <div class="patient-info">
                        <div class="info-item"><span class="info-label">${labels.patient}: </span><span class="info-value">${data.patient.name}</span></div>
                        <div class="info-item"><span class="info-label">${labels.phone}: </span><span class="info-value">${data.patient.phone || '-'}</span></div>
                        <div class="info-item"><span class="info-label">${labels.gender}: </span><span class="info-value">${data.patient.gender || '-'}</span></div>
                        <div class="info-item"><span class="info-label">${labels.dob}: </span><span class="info-value">${data.patient.dob || '-'}</span></div>
                        ${data.patient.id ? `<div class="info-item"><span class="info-label">${labels.id}: </span><span class="info-value">${data.patient.id}</span></div>` : ''}
                        ${data.patient.insurance ? `<div class="info-item"><span class="info-label">${labels.insurance}: </span><span class="info-value">${data.patient.insurance}</span></div>` : ''}
                    </div>

                    ${data.record.title ? `<h2 style="font-size: 18px; color: #0891b2; margin-bottom: 16px; font-weight: 700;">${data.record.title}</h2>` : ''}

                    <div class="content">
                        ${data.content}
                    </div>

                    <div class="footer">
                        <div class="clinic-info">
                            <p><strong>${data.clinic.name}</strong></p>
                            ${data.clinic.address ? `<p>${data.clinic.address}</p>` : ''}
                            ${data.clinic.phone ? `<p>${data.clinic.phone}</p>` : ''}
                        </div>
                        <div class="signature">
                            ${signatureUrl ? `<img src="${signatureUrl}" alt="Signature" class="signature-image" style="display:none;" onload="this.style.display='block'" onerror="this.style.display='none'" />` : ''}
                            <div class="line"></div>
                            <div class="name">${data.doctor.name}</div>
                            <div class="label">${data.doctor.specialty || labels.doctor}${data.doctor.license ? ` • ${labels.licenseNumber}: ${data.doctor.license}` : ''}</div>
                        </div>
                    </div>
                </div>
            </body>
        </html>
    `;

    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    iframe.setAttribute('aria-hidden', 'true');
    document.body.appendChild(iframe);

    const cleanup = () => {
        try {
            document.body.removeChild(iframe);
        } catch {
            // no-op
        }
    };

    const frameWindow = iframe.contentWindow;
    if (!frameWindow) {
        cleanup();
        return;
    }

    frameWindow.document.open();
    frameWindow.document.write(html);
    frameWindow.document.close();

    // Wait for resources to settle, then open system print/PDF dialog.
    setTimeout(() => {
        frameWindow.focus();
        frameWindow.print();
        setTimeout(cleanup, 1000);
    }, 500);
};
