// app/emergency/page.tsx

"use client";

import { AlertTriangle, CheckCircle, Crosshair, FileText, HeartPulse, Loader2, MapPin, PhoneCall, XCircle, Navigation } from 'lucide-react';
import { useState } from 'react';
import { SafePhoneLink } from '../components/PhoneLinks';
import { PageHeader } from '../components/ui/PageHeader';
import { SectionCard } from '../components/ui/SectionCard';

export default function Emergency() {
    const [confirmCall, setConfirmCall] = useState(false);
    const [location, setLocation] = useState<{ lat: number, lng: number, acc: number } | null>(null);
    const [locLoading, setLocLoading] = useState(false);
    const [locError, setLocError] = useState("");

    const getLocation = () => {
        setLocLoading(true);
        setLocError("");
        if (!navigator.geolocation) {
            setLocError("Din enhet saknar stöd för GPS.");
            setLocLoading(false);
            return;
        }

        navigator.geolocation.getCurrentPosition(
            (pos) => {
                setLocation({
                    lat: pos.coords.latitude,
                    lng: pos.coords.longitude,
                    acc: Math.round(pos.coords.accuracy) // Noggrannhet i meter
                });
                setLocLoading(false);
            },
            (err) => {
                setLocError("Kunde inte hämta plats. Kontrollera att GPS är aktiverat i telefonen.");
                setLocLoading(false);
            },
            { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 }
        );
    };

    return (
        <div className="space-y-6 animate-fade-in w-full mx-auto">
            <PageHeader
                title="Vid Nödsituation"
                icon={AlertTriangle}
                description="Agera lugnt, stanna kvar på platsen och tillkalla hjälp."
                variant="emergency"
            />

            <SectionCard
                variant="alert"
                title="Ring 112"
                icon={PhoneCall}
                description="Vid olycka, brand eller livshotande tillstånd. Berätta vem du är och vad som har hänt."
            >
                <div className="space-y-4">

                    {/* SÄKER 112-KNAPP */}
                    <div className="bg-white/40 p-2 rounded-2xl border border-emergency/20">
                        {!confirmCall ? (
                            <button
                                onClick={() => setConfirmCall(true)}
                                className="w-full flex items-center justify-center gap-3 bg-emergency text-white font-black uppercase tracking-widest text-lg py-4 rounded-xl shadow-sm hover:brightness-110 active:scale-[0.98] transition-all"
                            >
                                <PhoneCall size={24} className="animate-pulse" />
                                Ring 112
                            </button>
                        ) : (
                            <div className="flex flex-col sm:flex-row gap-2 animate-fade-in">
                                <a
                                    href="tel:112"
                                    onClick={() => setTimeout(() => setConfirmCall(false), 2000)} // Återställ efter klick
                                    className="flex-1 flex items-center justify-center gap-2 bg-emergency text-white font-black uppercase tracking-widest text-lg py-4 rounded-xl shadow-md hover:brightness-110 active:scale-[0.98] transition-all ring-4 ring-emergency/30"
                                >
                                    <CheckCircle size={24} />
                                    Ja, ring nu
                                </a>
                                <button
                                    onClick={() => setConfirmCall(false)}
                                    className="sm:w-1/3 flex items-center justify-center gap-2 bg-white text-ebony font-bold uppercase tracking-widest text-sm py-4 rounded-xl shadow-sm border border-emergency/20 hover:bg-eggshell transition-all"
                                >
                                    <XCircle size={18} />
                                    Avbryt
                                </button>
                            </div>
                        )}
                    </div>

                    {/* GPS OCH POSITION */}
                    <div className="bg-white/60 p-4 md:p-5 rounded-2xl border border-emergency/20">
                        <h3 className="font-black text-emergency flex items-center mb-2 text-xs uppercase tracking-widest">
                            <MapPin className="mr-2" size={16} /> Uppge din position
                        </h3>
                        <p className="text-ebony font-medium text-sm leading-relaxed mb-4">
                            Säg att du befinner dig i Kullabergs Naturreservat. Var specifik (t.ex. "Nära fyren" eller "Vid Josefinelust"). Minns du närmsta räddningspunkt?
                        </p>

                        <div className="bg-white p-3 rounded-xl border border-emergency/10 shadow-sm">
                            {location ? (
                                <div className="space-y-1 animate-fade-in">
                                    <p className="text-xs font-bold text-slate-teal uppercase tracking-widest">Dina koordinater (WGS84)</p>
                                    <p className="font-mono text-lg font-black text-ebony tracking-tight">
                                        {location.lat.toFixed(5)}, {location.lng.toFixed(5)}
                                    </p>
                                    <p className="text-[10px] font-bold text-ebony/50 uppercase">
                                        Noggrannhet: ca {location.acc} meter
                                    </p>

                                    <div className="flex flex-wrap items-center gap-3 mt-4 pt-3 border-t border-slate-teal/5">
                                        <a
                                            href={`https://maps.google.com/?q=${location.lat},${location.lng}`}
                                            target="_blank"
                                            rel="noreferrer"
                                            className="flex items-center gap-1.5 bg-seafoam/10 text-slate-teal px-3 py-1.5 rounded-lg text-xs font-bold hover:bg-seafoam/20 transition-colors"
                                        >
                                            <MapPin size={14} />
                                            Google Maps
                                        </a>
                                        <a
                                            href={`http://maps.apple.com/?ll=${location.lat},${location.lng}&q=Min+Position`}
                                            target="_blank"
                                            rel="noreferrer"
                                            className="flex items-center gap-1.5 bg-seafoam/10 text-slate-teal px-3 py-1.5 rounded-lg text-xs font-bold hover:bg-seafoam/20 transition-colors"
                                        >
                                            <Navigation size={14} />
                                            Apple Maps
                                        </a>
                                    </div>
                                </div>
                            ) : (
                                <button
                                    onClick={getLocation}
                                    disabled={locLoading}
                                    className="w-full flex items-center justify-center gap-2 bg-emergency/10 text-emergency hover:bg-emergency/20 font-bold uppercase tracking-widest text-xs py-3 rounded-lg transition-colors disabled:opacity-50"
                                >
                                    {locLoading ? <Loader2 size={16} className="animate-spin" /> : <Crosshair size={16} />}
                                    {locLoading ? "Söker satelliter..." : "Hämta min exakta position"}
                                </button>
                            )}

                            {locError && (
                                <p className="text-xs font-bold text-emergency mt-3 animate-fade-in flex items-start gap-1.5">
                                    <AlertTriangle size={14} className="shrink-0" />
                                    {locError}
                                </p>
                            )}
                        </div>
                    </div>

                </div>
            </SectionCard>

            {/* First Aid / HLR Card */}
            <SectionCard
                variant="default"
                title="Första Hjälpen & Hjärtstartare"
                icon={HeartPulse}
            >
                <ul className="space-y-3 text-ebony font-medium text-sm">
                    <li className="flex items-start">
                        <span className="bg-seafoam text-eggshell font-bold px-2 py-0.5 rounded mr-3 text-xs shrink-0">1</span>
                        <span>Säkra platsen – se till att varken du eller personen utsätts för mer fara.</span>
                    </li>
                    <li className="flex items-start">
                        <span className="bg-seafoam text-eggshell font-bold px-2 py-0.5 rounded mr-3 text-xs shrink-0">2</span>
                        <span>Finns hjärtstartare? Ja, närmaste hjärtstartare finns utanför <strong className="text-ebony font-black">Naturum</strong> (vid fyren) eller vid <strong className="text-ebony font-black">golfbanans klubbhus</strong>.</span>
                    </li>
                </ul>
            </SectionCard>

            {/* Internal Contact */}
            <SectionCard
                variant="default"
                title="Intern Rapportering"
                icon={FileText}
                description="När situationen är under kontroll, meddela alltid arbetsledaren om vad som inträffat."
            >
                <div className="space-y-3">
                    <div className="flex flex-col md:flex-row md:justify-between md:items-center pb-3 border-b border-slate-teal/10 gap-2">
                        <span className="text-sm font-bold text-ebony">William Söderberg</span>
                        <div className='flex gap-2 flex-wrap md:justify-end text-sm'>
                            <SafePhoneLink parts={['072', '247', '02', '91']} display="072-247 02 91" />
                            <SafePhoneLink parts={['078', '389', '355', '81', '0604']} display="078-389 35 58 10 604" />
                        </div>
                    </div>
                    <div className="flex flex-col md:flex-row md:justify-between md:items-center gap-2">
                        <span className="text-sm font-bold text-ebony">Oliver Nilsson</span>
                        <div className='flex gap-2 flex-wrap md:justify-end text-sm'>
                            <SafePhoneLink parts={['072', '717', '74', '40']} display="072-717 74 40" />
                            <SafePhoneLink parts={['078', '389', '355', '81', '0605']} display="078-389 35 58 10 605" />
                        </div>
                    </div>
                </div>
            </SectionCard>
        </div >
    );
}