'use client';

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

const ALL_SPECIALTIES = {
    'CARD': 'Cardiology',
    'DERM': 'Dermatology',
    'FM': 'Family Medicine',
    'IM': 'Internal Medicine',
    'NEU': 'Neurology',
    'OBGYN': 'Obstetrics/Gynecology',
    'OPH': 'Ophthalmology',
    'ORT': 'Orthopeadics',
    'ENT': 'Otolaryngology',
    'PED': 'Pediatrics',
    'PSY': 'Psychiatry',
    'URO': 'Urology'
};

export default function SPSDTToolPage() {
    const [states, setStates] = useState<string[]>([]);
    const [stateCounties, setStateCounties] = useState<Record<string, string[]>>({});
    
    // Form State
    const [selectedState, setSelectedState] = useState<string>('');
    const [selectedCounties, setSelectedCounties] = useState<string[]>([]);
    const [selectedSpecialties, setSelectedSpecialties] = useState<string[]>([]);

    // UI state
    const [loading, setLoading] = useState(true);
    const [generating, setGenerating] = useState(false);
    const [reportData, setReportData] = useState<any>(null);
    const [error, setError] = useState('');

    useEffect(() => {
        fetch('/api/spsdt/data')
            .then(res => res.json())
            .then(data => {
                if (data.states && data.stateCounties) {
                    setStates(data.states);
                    setStateCounties(data.stateCounties);
                } else if (data.error) {
                    setError('Failed to load data. The database might need to be provisioned via the admin portal.');
                }
                setLoading(false);
            })
            .catch(() => {
                setError('Failed to load options. Ensure admin setup is complete.');
                setLoading(false);
            });
    }, []);

    const availableCounties = selectedState ? stateCounties[selectedState] || [] : [];

    const handleStateChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        setSelectedState(e.target.value);
        setSelectedCounties(e.target.value ? ['All Counties'] : []);
    };

    const toggleCounty = (county: string) => {
        if (county === 'All Counties') {
            if (selectedCounties.includes('All Counties')) {
                setSelectedCounties([]);
            } else {
                setSelectedCounties(['All Counties']);
            }
            return;
        }

        let newSelection = selectedCounties.filter(c => c !== 'All Counties');
        if (newSelection.includes(county)) {
            newSelection = newSelection.filter(c => c !== county);
        } else {
            newSelection.push(county);
        }
        setSelectedCounties(newSelection);
    };

    const toggleSpecialty = (specKey: string) => {
        if (selectedSpecialties.includes(specKey)) {
            setSelectedSpecialties(selectedSpecialties.filter(s => s !== specKey));
        } else {
            setSelectedSpecialties([...selectedSpecialties, specKey]);
        }
    };

    const handleGenerate = async () => {
        if (!selectedState) {
            setError('Please select a state');
            return;
        }
        if (selectedCounties.length === 0) {
            setError('Please select at least one county');
            return;
        }
        if (selectedSpecialties.length === 0) {
            setError('Please select at least one specialty');
            return;
        }

        setError('');
        setGenerating(true);

        const countiesToFetch = selectedCounties.includes('All Counties') ? availableCounties : selectedCounties;

        try {
            const res = await fetch('/api/spsdt/data', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    state: selectedState,
                    counties: countiesToFetch,
                    specialties: selectedSpecialties
                })
            });
            const data = await res.json();
            if (res.ok) {
                setReportData(data);
                // Scroll down to report section gracefully
                setTimeout(() => {
                    document.getElementById('report-container')?.scrollIntoView({ behavior: 'smooth' });
                }, 100);
            } else {
                setError(data.error || 'Failed to generate report');
            }
        } catch (e) {
            setError('An error occurred during generation.');
        } finally {
            setGenerating(false);
        }
    };

    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]">monitor_heart</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">
                    Specialty Physician Supply & Demand Tool
                </h1>
                <p className="text-lg text-on-surface-variant font-body mb-6 w-[80%]">
                    Welcome to the NCAHD Specialty Physician Supply and Demand Tool. To generate your custom predictive report, use the parameters below to select the locality and relevant tracking specialties.
                </p>
                <div className="p-4 bg-[#E87722]/20 text-on-surface rounded-lg font-body text-sm inline-block">
                    To visualize this data via spatial maps, visit the <Link href="http://portals.ncahd.org/spsdt/" target="_blank" className="font-bold underline text-[#861F41] hover:text-[#E87722]">Interactive Mapping Portal</Link>.
                </div>
            </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">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>}

                    {loading ? (
                        <div className="animate-pulse space-y-4">
                            <div className="h-10 bg-slate-200 rounded w-1/3"></div>
                            <div className="h-32 bg-slate-200 rounded w-full"></div>
                        </div>
                    ) : (
                        <div className="grid md:grid-cols-2 gap-10">
                            
                            {/* Left Column: State & Category */}
                            <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. State <span className="text-[#E87722]">*</span></label>
                                    <select 
                                        className="p-3 border border-slate-300 rounded-lg bg-white focus:ring-2 focus:ring-[#861F41] outline-none font-body shadow-sm"
                                        value={selectedState}
                                        onChange={handleStateChange}
                                    >
                                        <option value="">-- Select a State --</option>
                                        {states.map(s => <option key={s} value={s}>{s}</option>)}
                                    </select>
                                </div>

                                <div className="flex flex-col gap-2 flex-grow">
                                    <label className="font-headline font-bold text-primary tracking-wide text-sm uppercase">2. County <span className="text-[#E87722]">*</span></label>
                                    <div className="border border-slate-300 rounded-lg bg-white overflow-hidden flex flex-col flex-grow min-h-[200px] max-h-[300px] shadow-sm">
                                        {!selectedState ? (
                                            <div className="p-4 text-slate-400 font-body text-sm italic">Select a state to view counties.</div>
                                        ) : (
                                            <div className="overflow-y-auto p-2 flex flex-col gap-1 custom-scrollbar">
                                                <label className="flex items-center gap-3 p-2 hover:bg-slate-50 cursor-pointer rounded transition-colors group">
                                                    <input 
                                                        type="checkbox" 
                                                        checked={selectedCounties.includes('All Counties')}
                                                        onChange={() => toggleCounty('All Counties')}
                                                        className="w-4 h-4 text-[#861F41] rounded border-slate-300 focus:ring-[#861F41]"
                                                    />
                                                    <span className="font-body text-sm font-semibold group-hover:text-primary">All Counties</span>
                                                </label>
                                                <div className="h-[1px] bg-slate-100 my-1 mx-2"></div>
                                                {availableCounties.map(county => (
                                                    <label key={county} className={`flex items-center gap-3 p-2 hover:bg-slate-50 cursor-pointer rounded transition-colors group ${selectedCounties.includes('All Counties') ? 'opacity-50 pointer-events-none' : ''}`}>
                                                        <input 
                                                            type="checkbox"
                                                            checked={selectedCounties.includes(county)}
                                                            onChange={() => toggleCounty(county)}
                                                            className="w-4 h-4 text-[#861F41] rounded border-slate-300 focus:ring-[#861F41]"
                                                        />
                                                        <span className="font-body text-sm group-hover:text-primary">{county}</span>
                                                    </label>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Right Column: Specialties */}
                            <div className="flex flex-col gap-2">
                                <label className="font-headline font-bold text-primary tracking-wide text-sm uppercase flex justify-between">
                                    <span>3. Specialty <span className="text-[#E87722]">*</span></span>
                                    <button 
                                        type="button" 
                                        onClick={() => setSelectedSpecialties(Object.keys(ALL_SPECIALTIES))}
                                        className="text-[10px] text-[#861F41] hover:underline"
                                    >Select All</button>
                                </label>
                                <div className="border border-slate-300 rounded-lg bg-white p-4 grid grid-cols-1 gap-2 shadow-sm h-full max-h-[390px] overflow-y-auto custom-scrollbar">
                                    {Object.entries(ALL_SPECIALTIES).map(([key, name]) => (
                                        <label key={key} className="flex items-center gap-3 p-2 hover:bg-slate-50 cursor-pointer rounded transition-colors group border border-transparent hover:border-slate-200">
                                            <input 
                                                type="checkbox"
                                                checked={selectedSpecialties.includes(key)}
                                                onChange={() => toggleSpecialty(key)}
                                                className="w-4 h-4 text-[#861F41] rounded border-slate-300 focus:ring-[#861F41]"
                                            />
                                            <div className="flex flex-col">
                                                <span className="font-headline font-bold text-sm text-primary group-hover:text-[#861F41] transition-colors">{name}</span>
                                                <span className="font-body text-xs text-slate-500 uppercase">{key}</span>
                                            </div>
                                        </label>
                                    ))}
                                </div>
                            </div>
                        </div>
                    )}

                    <div className="mt-8 border-t border-primary/10 pt-6 flex justify-end">
                        <button 
                            onClick={handleGenerate}
                            disabled={generating || loading}
                            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 ? 'Generating Report...' : 'Generate Report'}
                            {!generating && <span className="material-symbols-outlined text-lg">assessment</span>}
                        </button>
                    </div>
                </div>
            </div>

            {/* Generated Report View */}
            {reportData && (
                <div id="report-container" className="container mx-auto px-4 md:px-8 max-w-7xl print:px-0 print:max-w-none">
                    <style media="print">
                        {`
                            @page {
                                size: ${reportData.specialties.length <= 4 ? 'letter portrait' : reportData.specialties.length <= 7 ? 'letter landscape' : `${11 + (reportData.specialties.length - 7) * 1.5}in 8.5in`};
                                margin: 0.5in;
                            }
                            @page title_page {
                                size: letter portrait;
                                margin: 0.5in;
                            }
                        `}
                    </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 (Restored) */}
                        <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">SPSDT Report Generated</span>
                                </div>
                                <h3 className="text-3xl font-headline font-bold text-primary mb-2">
                                    {reportData.state} Supply & Demand Data
                                </h3>
                                <p className="text-on-surface-variant font-body mb-2">
                                    Showing projections for {reportData.counties.length} counties and {reportData.specialties.length} specialties.
                                </p>
                            </div>
                            
                            {/* Action Bar */}
                            <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>

                        {/* First Print Page Data */}
                        <div className="hidden print:flex flex-col border-none text-black px-4 print:h-[95vh] break-after-page text-[15px] leading-[1.6]" style={{ page: "title_page" } as any}>
                            {/* Logos */}
                            <div className="flex justify-between items-center w-full mb-12">
                                <Image 
                                    src="/spsdt_archive/images/VCOM.jpg" 
                                    alt="VCOM Logo"
                                    width={150}
                                    height={80}
                                    unoptimized
                                    className="h-20 w-auto object-contain" 
                                />
                                <Image 
                                    src="/spsdt_archive/images/NCAHD.jpg" 
                                    alt="NCAHD Logo"
                                    width={150}
                                    height={64}
                                    unoptimized
                                    className="h-16 w-auto object-contain" 
                                />
                            </div>

                            {/* Title */}
                            <div className="text-center mb-10">
                                <h2 className="text-2xl font-headline font-bold text-[#b03038] mb-2 tracking-tight">Specialty Physician Supply and Demand Report</h2>
                                <p className="text-lg text-black font-body">{new Date().toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'})}</p>
                            </div>

                            {/* Text Body */}
                            <div className="flex flex-col gap-6 font-body">
                                <p>
                                    This report is the result of the request made through the online Specialty Physician Supply and Demand (SPSD) tool. This tool and the results below are being provided, free of charge, by the National Center for the Analysis of Healthcare Data (NCAHD) and the National Center for Rural Health Works for the purpose of improving easy access to high quality physician workforce supply and demand data that has never before been provided to the public.
                                </p>

                                <p>
                                    <strong>Background:</strong> Previous specialty physician demand models generally utilized population measures such as determining the number of doctors a total population and do not ascertain differences in visit rates by different age demographics or account for health outcomes. In addition, they also do not take into account the current manner in which physicians provide care and how they are reimbursed. Our specialty physician demand model measures need based upon historical patient visit rates by different age demographics along with accounting for the current work production values by each physician specialty.
                                </p>

                                <p>
                                    Considering the fact that all existing physician data sources (e.g. AMA Masterfile, the NPI , Healthgrades, etc.) use self-reported data as the basis of their data, our partner research center, the National Center for Analysis of Healthcare Data (NCAHD) created, in 2008, a unique process using the only regulated physician data source, state licensure data, as our base to which we integrate other data sources as needed. We call this the Enhanced State Licensure (ESL) dataset and a current national version of this dataset is utilized in this application.
                                </p>

                                <p>
                                    Since we have individual practice location data for all actively practicing physicians in the nation, we are able to generate an FTE demand by any geographic area (zip code, county, state or service region) that when coupled with our specialty physician supply data provides a source of high-quality physician specialty information that will be updated annually.
                                </p>
                            </div>

                            <div className="mt-auto pb-12 text-center text-[#b03038] text-xl font-body">
                                Results table generated on page 2 of this PDF.
                            </div>
                        </div>

                        {/* Page 2 Print Logos */}
                        <div className="hidden print:flex flex-col">
                            <div className="flex justify-between items-center w-full mb-8">
                                <Image 
                                    src="/spsdt_archive/images/VCOM.jpg" 
                                    alt="VCOM Logo"
                                    width={120}
                                    height={64}
                                    unoptimized
                                    className="h-16 w-auto object-contain" 
                                />
                                <Image 
                                    src="/spsdt_archive/images/NCAHD.jpg" 
                                    alt="NCAHD Logo"
                                    width={120}
                                    height={48}
                                    unoptimized
                                    className="h-12 w-auto object-contain" 
                                />
                            </div>
                        </div>

                        {/* Report Data Table */}
                        <div className="w-full overflow-x-auto print:overflow-visible mt-6">
                            <table className="w-full border-collapse font-body text-sm min-w-max print:border print:border-black print:text-black">
                                <thead>
                                    <tr className="hidden print:table-row">
                                        <th colSpan={1 + (reportData.specialties.length * 2)} className="p-3 border print:border-black text-center font-headline font-bold text-lg leading-relaxed">
                                            Specialty Physician Supply* (S) and Demand** (D) Numbers for <br/> {reportData.state}
                                        </th>
                                    </tr>

                                    {/* Web Specialty Header Row */}
                                    <tr className="bg-[#861F41] text-white print:bg-white print:text-black">
                                        <th className="p-3 border border-[#6c1733] print:border-black text-left font-headline font-normal sticky print:static left-0 bg-[#861F41] print:bg-transparent z-10 print:z-auto w-[200px]">County</th>
                                        {reportData.specialties.map((spec: string) => (
                                            <th key={spec} colSpan={2} className="p-3 border border-[#6c1733] print:border-black text-center font-headline uppercase tracking-widest print:font-normal">{spec}</th>
                                        ))}
                                    </tr>
                                    {/* Supply / Demand Sub Header */}
                                    <tr className="bg-slate-50 text-primary border-b-2 border-slate-300 print:bg-white print:text-black print:border-none">
                                        <th className="p-2 border border-slate-200 print:border-black sticky print:static left-0 bg-slate-50 print:bg-transparent z-10 print:z-auto"></th>
                                        {reportData.specialties.map((spec: string) => (
                                            <React.Fragment key={`${spec}-sub`}>
                                                <th className="p-2 border border-slate-200 print:border-black text-center font-bold text-[#861F41] print:text-black print:font-normal" title="Demand">D</th>
                                                <th className="p-2 border border-slate-200 print:border-black text-center font-bold text-[#1F4186] print:text-black print:font-normal" title="Supply">S</th>
                                            </React.Fragment>
                                        ))}
                                    </tr>
                                </thead>
                                <tbody>
                                    {reportData.results.map((row: any, i: number) => (
                                        <tr key={row.county || i} className="hover:bg-slate-50 transition-colors border-b border-slate-200 print:border-black group">
                                            <td className="p-3 border-r print:border-x border-slate-200 print:border-black font-medium text-primary print:text-black sticky print:static left-0 bg-white print:bg-transparent group-hover:bg-slate-50 z-10 print:z-auto shadow-[1px_0_0_0_#e2e8f0] print:shadow-none print:font-normal">
                                                {row.county}
                                            </td>
                                            {reportData.specialties.map((spec: string) => {
                                                const dVal = row[`${spec}_demand`] !== null ? Number(row[`${spec}_demand`]) : null;
                                                const sVal = row[`${spec}_supply`] !== null ? Number(row[`${spec}_supply`]) : null;
                                                
                                                let dClass = "";
                                                let sClass = "";
                                                if (dVal !== null && sVal !== null) {
                                                    if (dVal > sVal) dClass = "bg-[#EF4444] text-black print:!bg-[#EF4444]";
                                                    if (sVal > dVal) sClass = "bg-[#22C55E] text-black print:!bg-[#22C55E]";
                                                }

                                                return (
                                                    <React.Fragment key={`${spec}-val-${i}`}>
                                                        <td className={`p-3 border-r border-slate-200 print:border-black print:border-t-black text-center tabular-nums text-slate-800 print:text-black ${dClass}`}
                                                            style={{ WebkitPrintColorAdjust: 'exact', colorAdjust: 'exact' }}>
                                                            {dVal !== null ? dVal.toFixed(1) : '-'}
                                                        </td>
                                                        <td className={`p-3 border-r border-slate-200 print:border-black print:border-t-black text-center tabular-nums text-slate-800 print:text-black ${sClass}`}
                                                            style={{ WebkitPrintColorAdjust: 'exact', colorAdjust: 'exact' }}>
                                                            {sVal !== null ? sVal.toFixed(1) : '-'}
                                                        </td>
                                                    </React.Fragment>
                                                );
                                            })}
                                        </tr>
                                    ))}
                                    {reportData.results.length === 0 && (
                                        <tr>
                                            <td colSpan={1 + (reportData.specialties.length * 2)} className="p-8 border border-slate-200 print:border-black text-center text-slate-500 font-body print:text-black">
                                                No calculated demographic records found for these selections securely.
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                                <tfoot className="hidden print:table-row-group">
                                    <tr>
                                        <td colSpan={1 + (reportData.specialties.length * 2)} className="p-2 border border-black print:border-black text-left text-[14px]">
                                            *Supply numbers from NCAHD 2016 ESL Physician data (green cells indicate a surplus) 1
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colSpan={1 + (reportData.specialties.length * 2)} className="p-2 border border-black print:border-black text-left text-[14px]">
                                            **Demand numbers derived through our methodology (red cells indicate a shortage) 1
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                            <div className="hidden print:block mt-6 text-[14px] text-black">
                                1: See Appendix - Metadata on Specialty Physician Supply and Demand Data
                            </div>
                        </div>
                        
                        {/* Print End Message (Replaces Footer) */}
                        <div className="hidden print:flex flex-col items-center justify-center mt-12 mb-8 gap-4 break-inside-avoid">
                            <Image 
                                src="/spsdt_archive/images/NCAHD.jpg" 
                                alt="NCAHD Logo"
                                width={120}
                                height={64}
                                unoptimized
                                className="h-16 w-auto object-contain mb-2" 
                            />
                            <p className="text-xl font-headline font-bold text-black text-center max-w-lg">
                                Thank you for using NCAHD's Specialty Physician Supply and Demand Tool.
                            </p>
                        </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>
    );
}
