/**
 * HailRiskStep — Screen 6 "Hail risk" (spec §6).
 * Runs geocode → /api/storm-history → Poisson model, freezes the snapshot into
 * the session (spec §12), and renders the historical-only risk card + map.
 */
import React, { useEffect } from 'react';
import { Loader2, AlertCircle } from 'lucide-react';
import { useEstimateWizard } from '../../EstimateWizardContext';
import { useWizardHailRisk } from '../../hooks/useWizardHailRisk';
import PropertyMap from '../PropertyMap';
import HailRiskSnapshot from '../HailRiskSnapshot';

const HailRiskStep = () => {
    const { inputs, session, patchSession, tenantConfig, logEvent } = useEstimateWizard();

    // Reuse a previously frozen snapshot if the user navigates back/forward.
    const alreadyHave = !!session.hailSnapshot;

    const { loading, error, property, snapshot } = useWizardHailRisk({
        address: inputs.address,
        property: session.property,
        enabled: !alreadyHave,
        stormSettings: tenantConfig.stormSettings,
    });

    // Freeze property + snapshot into the session once resolved.
    useEffect(() => {
        if (alreadyHave) return;
        if (snapshot && property) {
            patchSession({ property, hailSnapshot: snapshot });
            logEvent('hail_snapshot_generated', {
                exposureTier: snapshot.exposureTier,
                p10Base: snapshot.probability10yr.base,
                confidence: snapshot.confidence,
            });
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [snapshot, property, alreadyHave]);

    const shownProperty = session.property || property;
    const shownSnapshot = session.hailSnapshot || snapshot;

    if (loading && !shownSnapshot) {
        return (
            <div className="flex flex-col items-center justify-center py-12 text-center">
                <Loader2 size={28} className="text-amber-500 animate-spin mb-3" />
                <p className="text-sm text-zinc-500 dark:text-zinc-400">
                    Checking historical storm reports for your area…
                </p>
            </div>
        );
    }

    if (error && !shownSnapshot) {
        return (
            <div className="rounded-2xl border border-red-200 dark:border-red-500/20 bg-red-50 dark:bg-red-500/10 p-4 flex items-start gap-3">
                <AlertCircle size={20} className="text-red-500 shrink-0" />
                <div>
                    <p className="font-semibold text-red-700 dark:text-red-300">Storm history unavailable</p>
                    <p className="text-sm text-red-600 dark:text-red-400 mt-0.5">
                        We couldn’t load storm data right now — your rep will review local hail history during your visit.
                        You can still continue.
                    </p>
                </div>
            </div>
        );
    }

    return (
        <div className="space-y-4">
            {shownProperty && (
                <PropertyMap
                    lat={shownProperty.lat}
                    lon={shownProperty.lon}
                    radiusMiles={shownSnapshot?.radiusMiles ?? 20}
                />
            )}
            <HailRiskSnapshot snapshot={shownSnapshot} />
        </div>
    );
};

export default HailRiskStep;
