'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { eitData } from './data';

export default function EITToolPage() {
    const defaultTool = Object.keys(eitData)[0];
    const [selectedToolKey, setSelectedToolKey] = useState<string>(defaultTool);
    const [entityName, setEntityName] = useState<string>('');
    const [directEmployment, setDirectEmployment] = useState<string>('');
    const [directWages, setDirectWages] = useState<string>('');

    const [generating, setGenerating] = useState(false);
    const [reportData, setReportData] = useState<any>(null);
    const [error, setError] = useState('');

    const currentToolInfo = eitData[selectedToolKey];

    const handleGenerate = () => {
        if (!entityName.trim()) {
            setError(`Please enter a valid ${currentToolInfo.entityLabel}.`);
            return;
        }

        const empVal = parseFloat(directEmployment.replace(/[^0-9.]/g, ''));
        const wagesVal = parseFloat(directWages.replace(/[^0-9.]/g, ''));

        if (isNaN(empVal) || empVal < 0) {
            setError('Please enter a valid number for Direct Employment Impact.');
            return;
        }
        if (isNaN(wagesVal) || wagesVal < 0) {
            setError('Please enter a valid number for Wages Direct Impact (in Millions).');
            return;
        }

        setError('');
        setGenerating(true);

        setTimeout(() => {
            // Calculations mimicking legacy class.eit.php
            const empDirect = empVal;
            const empTotal = Math.round(empVal * currentToolInfo.employmentMultiplier);
            const empSecondary = empTotal - empDirect;

            const wagesDirect = wagesVal;
            const wagesTotal = Number((wagesVal * currentToolInfo.wagesMultiplier).toFixed(2));
            const wagesSecondary = Number((wagesTotal - wagesDirect).toFixed(2));

            const replacements: Record<string, string> = {
                '[DATE]': new Date().toLocaleDateString('en-US', { month: 'numeric', day: 'numeric', year: 'numeric' }),
                '[EMPLOY_DIRECT_IMPACT]': Math.round(empDirect).toLocaleString(),
                '[EMPLOY_SECONDARY_IMPACT]': empSecondary.toLocaleString(),
                '[EMPLOY_TOTAL_IMPACT]': empTotal.toLocaleString(),
                '[WAGES_DIRECT_IMPACT]': `$${wagesDirect.toFixed(2)}`,
                '[WAGES_SECONDARY_IMPACT]': `$${wagesSecondary.toFixed(2)}`,
                '[WAGES_TOTAL_IMPACT]': `$${wagesTotal.toFixed(2)}`,
                '[CLINIC_NAME]': entityName,
                '[HOSPITAL_NAME]': entityName,
                '[WHITE_PAPER_LINK]': `<a href="${currentToolInfo.whitepaperLink}" target="_blank" class="text-[#861F41] font-bold underline hover:text-[#E87722]">${currentToolInfo.whitepaperText}</a>`
            };

            let generatedHtml = currentToolInfo.bodyHtml;
            for (const [key, value] of Object.entries(replacements)) {
                generatedHtml = generatedHtml.split(key).join(value);
            }

            setReportData({
                tool: currentToolInfo,
                calculated: {
                    empDirect, empTotal, empSecondary,
                    wagesDirect, wagesTotal, wagesSecondary
                },
                entityName,
                html: generatedHtml
            });
            setGenerating(false);

            setTimeout(() => {
                document.getElementById('report-container')?.scrollIntoView({ behavior: 'smooth' });
            }, 100);
        }, 600);
    };

    const handlePrint = () => {
        window.print();
    };

    return (
        <div className="flex flex-col w-full min-h-screen relative pt-12 pb-24 print:pt-0 print:pb-0 bg-surface">
            {/* Header / Intro section (Hidden on print) */}
            <div className="container mx-auto px-8 max-w-5xl mb-12 print:hidden relative z-10">
                <div className="flex items-center gap-3 mb-4">
                    <span className="material-symbols-outlined text-[#E87722]">payments</span>
                    <span className="text-[#E87722] font-headline font-bold tracking-[0.2em] text-xs uppercase">Workforce Intelligence Tool</span>
                </div>
                <h1 className="text-4xl md:text-5xl font-headline font-bold text-primary leading-tight mb-4 tracking-tight">
                    Economic Impact Tool
                </h1>
                <p className="text-lg text-on-surface-variant font-body mb-6 w-[#80%]">
                    This tool measures the economic impact of rural healthcare facilities on their communities. By submitting your raw employment data, NCAHD applies statistically validated multipliers derived from IMPLAN modeling across the US.
                </p>
            </div>

            {/* Input Form Module (Hidden on print) */}
            <div className="container mx-auto px-8 max-w-5xl print:hidden relative z-10">
                <div className="glass-panel p-8 rounded-3xl border border-primary/20 shadow-xl bg-white/70 backdrop-blur-xl mb-16">
                    <h2 className="text-2xl font-headline font-bold text-primary uppercase mb-6 tracking-wide border-b border-primary/10 pb-4">EIT Report Parameters</h2>

                    {error && <div className="p-4 mb-6 bg-error-container text-on-error-container rounded-lg font-body font-medium">{error}</div>}

                    <div className="grid md:grid-cols-2 gap-10">
                        {/* Left Column: Tool Selector */}
                        <div className="flex flex-col gap-6">
                            <div className="flex flex-col gap-2">
                                <label className="font-headline font-bold text-primary tracking-wide text-sm uppercase">1. Facility Tool Model <span className="text-[#E87722]">*</span></label>
                                <div className="border border-slate-300 rounded-lg bg-white overflow-hidden flex flex-col flex-grow shadow-sm">
                                    <div className="p-2 flex flex-col gap-1 custom-scrollbar">
                                        {Object.entries(eitData).map(([key, info]: [string, any]) => (
                                            <label key={key} className={`flex items-start gap-3 p-3 cursor-pointer rounded transition-colors group ${selectedToolKey === key ? 'bg-[#861F41]/10 border border-[#861F41]/20' : 'hover:bg-slate-50 border border-transparent'}`}>
                                                <input
                                                    type="radio"
                                                    name="toolSelection"
                                                    checked={selectedToolKey === key}
                                                    onChange={() => {
                                                        setSelectedToolKey(key);
                                                        setEntityName('');
                                                    }}
                                                    className="w-4 h-4 mt-1 text-[#861F41] border-slate-300 focus:ring-[#861F41]"
                                                />
                                                <div className="flex flex-col">
                                                    <span className={`font-body font-semibold text-sm ${selectedToolKey === key ? 'text-[#861F41]' : 'text-primary'}`}>{info.title}</span>
                                                </div>
                                            </label>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Right Column: Values */}
                        <div className="flex flex-col gap-6">
                            <div className="flex flex-col gap-2">
                                <label className="font-headline font-bold text-primary tracking-wide text-sm uppercase">2. {currentToolInfo.entityLabel} <span className="text-[#E87722]">*</span></label>
                                <input
                                    type="text"
                                    className="p-3 border border-slate-300 rounded-lg bg-white focus:ring-2 focus:ring-[#861F41] outline-none font-body shadow-sm w-full"
                                    placeholder={currentToolInfo.entityPlaceholder || `e.g. ${currentToolInfo.entityLabel}`}
                                    value={entityName}
                                    onChange={(e) => setEntityName(e.target.value)}
                                />
                            </div>

                            <div className="flex flex-col gap-2">
                                <label className="font-headline font-bold text-primary tracking-wide text-sm uppercase">3. Employment Direct Impact <span className="text-[#E87722]">*</span></label>
                                <div className="relative">
                                    <span className="absolute left-3 top-1/2 -translate-y-1/2 material-symbols-outlined text-slate-400 text-lg">group</span>
                                    <input
                                        type="number"
                                        min="0"
                                        className="pl-10 p-3 border border-slate-300 rounded-lg bg-white focus:ring-2 focus:ring-[#861F41] outline-none font-body shadow-sm w-full"
                                        placeholder="Number of Employees"
                                        value={directEmployment}
                                        onChange={(e) => setDirectEmployment(e.target.value)}
                                    />
                                </div>
                            </div>

                            <div className="flex flex-col gap-2">
                                <label className="font-headline font-bold text-primary tracking-wide text-sm uppercase">4. Wages Direct Impact <span className="text-slate-500 lowercase text-xs font-normal">(in Millions)</span> <span className="text-[#E87722]">*</span></label>
                                <div className="relative">
                                    <span className="absolute left-3 top-1/2 -translate-y-1/2 material-symbols-outlined text-slate-400 text-lg">attach_money</span>
                                    <input
                                        type="number"
                                        min="0"
                                        step="0.1"
                                        className="pl-10 p-3 border border-slate-300 rounded-lg bg-white focus:ring-2 focus:ring-[#861F41] outline-none font-body shadow-sm w-full"
                                        placeholder="e.g. 10.5"
                                        value={directWages}
                                        onChange={(e) => setDirectWages(e.target.value)}
                                    />
                                    <span className="absolute right-4 top-1/2 -translate-y-1/2 font-body font-bold text-slate-400">M</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="mt-8 border-t border-primary/10 pt-6 flex justify-end">
                        <button
                            onClick={handleGenerate}
                            disabled={generating}
                            className="bg-[#861F41] hover:bg-[#6c1733] text-white font-headline font-bold py-4 px-10 rounded-lg transition-all shadow-md active:scale-95 disabled:opacity-50 flex items-center gap-2 text-lg uppercase tracking-wider"
                        >
                            {generating ? 'Calculating...' : 'Generate Report'}
                            {!generating && <span className="material-symbols-outlined text-lg">insights</span>}
                        </button>
                    </div>
                </div>
            </div>

            {/* Generated Report View */}
            {reportData && (
                <div id="report-container" className="container mx-auto px-4 md:px-8 max-w-5xl print:px-0">
                    <style media="print">
                        {`
                            @page {
                                size: letter portrait;
                                margin: 0.5in;
                            }
                            body {
                                -webkit-print-color-adjust: exact !important;
                                print-color-adjust: exact !important;
                            }
                        `}
                    </style>
                    <div className="bg-white rounded-[2rem] print:rounded-none shadow-2xl print:shadow-none p-8 md:p-12 print:p-0 border border-slate-100 object-contain w-full">

                        {/* Web Report Header (Hidden in Print) */}
                        <div className="print:hidden mb-12 flex flex-col md:flex-row md:items-start justify-between gap-6">
                            <div>
                                <div className="flex items-center gap-3 mb-4">
                                    <span className="material-symbols-outlined text-[#E87722]">check_circle</span>
                                    <span className="text-[#E87722] font-headline font-bold tracking-[0.2em] text-xs uppercase">EIT Report Generated</span>
                                </div>
                            </div>

                            <div className="flex-shrink-0">
                                <button
                                    onClick={handlePrint}
                                    className="bg-surface hover:bg-slate-200 text-primary border border-slate-300 font-headline font-bold py-2 px-6 rounded-lg transition-all shadow-sm flex items-center gap-2"
                                >
                                    <span className="material-symbols-outlined text-[20px]">print</span>
                                    Export to PDF
                                </button>
                            </div>
                        </div>

                        {/* Modernized Report Print Payload */}
                        <div className="flex flex-col border-none text-on-surface px-0 md:px-4 text-[15px] leading-[1.7] break-inside-avoid">

                            {/* NCAHD Sole Logo and Header Lockup */}
                            <div className="flex items-center gap-6 mb-8 print:mb-6">
                                <Image 
                                    src="/spsdt_archive/images/NCAHD.jpg" 
                                    alt="NCAHD Logo"
                                    width={150}
                                    height={72}
                                    unoptimized
                                    className="h-[72px] w-auto object-contain" 
                                />
                                <div className="flex flex-col">
                                    <h2 className="text-3xl font-headline font-bold text-primary tracking-tight">
                                        {reportData.tool.title}
                                    </h2>
                                    <div className="text-xl font-headline font-semibold text-primary mt-1">
                                        For {reportData.entityName}
                                    </div>
                                </div>
                            </div>

                            {/* Report Calculation Table */}
                            <div className="bg-slate-50 print:bg-white border-l-4 border-[#861F41] p-6 mb-4 shadow-sm print:shadow-none print:border print:border-[#861F41]">
                                <h2 className="text-xl font-headline font-bold text-[#861F41] mb-6 tracking-tight">
                                    {reportData.tool.title}
                                </h2>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-8 print:grid-cols-2">
                                    <div className="flex flex-col gap-4">
                                        <div className="bg-white p-4 border border-slate-200 rounded-md print:border-none print:p-0 print:mb-4">
                                            <div className="text-xs uppercase font-bold text-slate-500 mb-1">Direct Employment Impact</div>
                                            <div className="text-2xl font-bold text-primary tabular-nums">{Math.round(reportData.calculated.empDirect).toLocaleString()}</div>
                                        </div>
                                        <div className="bg-white p-4 border border-slate-200 rounded-md print:border-none print:p-0 print:mb-4">
                                            <div className="text-xs uppercase font-bold text-slate-500 mb-1">Secondary Employment Impact</div>
                                            <div className="text-2xl font-bold text-primary tabular-nums">{Math.round(reportData.calculated.empSecondary).toLocaleString()}</div>
                                        </div>
                                        <div className="bg-[#861F41]/5 p-4 border border-[#861F41]/20 rounded-md print:border-none print:p-0">
                                            <div className="text-xs uppercase font-bold text-[#861F41] mb-1">Total Employment Impact</div>
                                            <div className="text-2xl font-bold text-[#861F41] tabular-nums">{Math.round(reportData.calculated.empTotal).toLocaleString()}</div>
                                        </div>
                                    </div>
                                    <div className="flex flex-col gap-4">
                                        <div className="bg-white p-4 border border-slate-200 rounded-md print:border-none print:p-0 print:mb-4">
                                            <div className="text-xs uppercase font-bold text-slate-500 mb-1">Direct Wages/Salaries/Benefits</div>
                                            <div className="text-2xl font-bold text-primary tabular-nums">${reportData.calculated.wagesDirect.toFixed(2)} <span className="text-sm font-normal text-slate-500">M</span></div>
                                        </div>
                                        <div className="bg-white p-4 border border-slate-200 rounded-md print:border-none print:p-0 print:mb-4">
                                            <div className="text-xs uppercase font-bold text-slate-500 mb-1">Secondary Wages Impact</div>
                                            <div className="text-2xl font-bold text-primary tabular-nums">${reportData.calculated.wagesSecondary.toFixed(2)} <span className="text-sm font-normal text-slate-500">M</span></div>
                                        </div>
                                        <div className="bg-[#861F41]/5 p-4 border border-[#861F41]/20 rounded-md print:border-none print:p-0">
                                            <div className="text-xs uppercase font-bold text-[#861F41] mb-1">Total Wages Impact</div>
                                            <div className="text-2xl font-bold text-[#861F41] tabular-nums">${reportData.calculated.wagesTotal.toFixed(2)} <span className="text-sm font-normal text-slate-500">M</span></div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Dynamically Injected Body Paragraphs */}
                            <div 
                                className="max-w-none font-body [&_h4:first-child]:mt-0 [&_h4]:text-primary [&_h4]:font-headline [&_h4]:font-bold [&_h4]:text-2xl [&_h4]:mt-8 [&_h4]:mb-4 [&_h4]:border-b-2 [&_h4]:border-slate-100 [&_h4]:pb-2 [&_h4]:tracking-tight [&_p]:text-slate-700 [&_p]:leading-relaxed [&_p]:text-[15px] [&_p]:mb-4 [&_b]:text-[#861F41] [&_b]:font-bold [&_a]:text-[#E87722] [&_a]:underline [&_a]:font-semibold print:[&_p]:text-black print:[&_b]:text-black print:[&_h4]:text-black print:[&_h4]:border-b-2 print:[&_h4]:border-slate-300 print:[&_h4]:text-xl print:[&_h4]:mt-6 print:[&_h4]:mb-3 mt-4"
                                dangerouslySetInnerHTML={{ __html: reportData.html }}
                            />

                            {/* Contact Section / Document End */}
                            <div className="mt-8 pt-8 border-t border-slate-200 print:border-slate-800 break-inside-avoid">
                                <div className="flex justify-between items-start">
                                    <div>
                                        <h4 className="font-headline font-bold text-primary text-sm uppercase mb-2">Program Contact</h4>
                                        <p className="font-body text-sm text-slate-700 print:text-black leading-relaxed">
                                            <b>Ann K. Peton, MPH</b><br />
                                            Director, National Center for the Analysis of Healthcare Data<br />
                                            <a href="mailto:apeton@vcom.vt.edu" className="text-[#861F41] hover:underline">apeton@vcom.vt.edu</a><br />
                                            <b>(573)-301-9654</b>
                                        </p>
                                    </div>
                                    <div className="flex flex-col items-end gap-3 pt-1">
                                        <div className="text-sm font-body text-slate-500 print:text-black font-semibold">
                                            Report Generated: {new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}
                                        </div>
                                        <Image 
                                            src="/spsdt_archive/images/NCAHD.jpg" 
                                            alt="NCAHD Logo"
                                            width={100}
                                            height={40}
                                            unoptimized
                                            className="h-10 w-auto object-contain print:h-8" 
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Standard Report Conclusion */}
                        <div className="hidden print:flex flex-col items-center justify-center mt-12 mb-8 gap-4 break-inside-avoid">
                            <p className="text-sm font-headline font-bold text-black text-center max-w-lg mt-8 border-t border-black pt-8 w-full">
                                Thank you for using NCAHD's Economic Impact Tool.
                            </p>
                            <div className="text-xs text-slate-500 font-body print:text-black">
                                &copy; {new Date().getFullYear()} National Center for the Analysis of Healthcare Data. Proprietary Analytics.
                            </div>
                        </div>

                        <div className="mt-8 text-center text-xs text-slate-500 font-body pt-8 border-t border-slate-200 print:hidden">
                            &copy; {new Date().getFullYear()} National Center for the Analysis of Healthcare Data. Proprietary Analytics.
                        </div>

                    </div>
                </div>
            )}
        </div>
    );
}
