'use client';

import React, { useState, useEffect } from 'react';
import {
  AlertOctagon,
  X,
  MapPin,
  Camera,
  Radio,
  Send,
  CheckCircle2,
  ShieldAlert
} from 'lucide-react';
import { IncidentCategory, IncidentSeverity } from '@/types';

interface Props {
  isOpen: boolean;
  onClose: () => void;
  puCode: string;
  puName: string;
  onIncidentDispatched: (incident: any) => void;
}

export const IncidentBeaconModal: React.FC<Props> = ({
  isOpen,
  onClose,
  puCode,
  puName,
  onIncidentDispatched,
}) => {
  const [category, setCategory] = useState<IncidentCategory>('BALLOT_SNATCHING');
  const [severity, setSeverity] = useState<IncidentSeverity>('CRITICAL');
  const [description, setDescription] = useState('');
  const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(null);
  const [gettingLocation, setGettingLocation] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);

  // Attempt to fetch GPS coordinates
  useEffect(() => {
    if (isOpen) {
      setSuccess(false);
      if (typeof window !== 'undefined' && 'geolocation' in navigator) {
        setGettingLocation(true);
        navigator.geolocation.getCurrentPosition(
          (pos) => {
            setCoords({ lat: pos.coords.latitude, lng: pos.coords.longitude });
            setGettingLocation(false);
          },
          () => {
            // Default to Lagos Ikeja coordinates on failure
            setCoords({ lat: 6.6190, lng: 3.3580 });
            setGettingLocation(false);
          },
          { timeout: 6000 }
        );
      }
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);

    try {
      const res = await fetch('/api/incidents', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          pu_code: puCode,
          pu_id: `pu-${puCode}`,
          state_name: 'Lagos',
          lga_name: 'Ikeja',
          category,
          severity,
          description,
          latitude: coords?.lat || 6.6190,
          longitude: coords?.lng || 3.3580,
          media_urls: [],
          reported_by_name: `PU Agent (${puCode})`,
        }),
      });

      const data = await res.json();
      if (res.ok) {
        setSuccess(true);
        onIncidentDispatched(data.incident);
        setTimeout(() => {
          onClose();
        }, 1800);
      }
    } catch (err) {
      console.error('Incident report error:', err);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/85 backdrop-blur-sm animate-in fade-in">
      <div className="w-full max-w-lg bg-slate-900 border-2 border-red-700/80 rounded-2xl p-4 sm:p-5 shadow-2xl shadow-red-950/60 relative overflow-hidden">
        {/* Top Emergency Beacon Banner */}
        <div className="flex items-start justify-between gap-2 pb-3 border-b border-red-900/60">
          <div className="flex items-center space-x-2.5 min-w-0">
            <div className="w-8 h-8 rounded-xl bg-red-900/40 border border-red-600 text-red-400 flex items-center justify-center shrink-0">
              <AlertOctagon className="w-4 h-4 animate-pulse" />
            </div>
            <div className="min-w-0">
              <div className="flex flex-wrap items-center gap-1.5">
                <h3 className="text-sm font-extrabold text-red-400 uppercase tracking-wide">
                  Emergency SOS
                </h3>
                <span className="text-[9px] bg-red-700 text-white px-2 py-0.5 rounded-full font-black tracking-wider">
                  LIVE BEACON
                </span>
              </div>
              <p className="text-[11px] text-slate-400 font-mono truncate max-w-[220px] sm:max-w-xs">
                {puCode} &bull; {puName}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition shrink-0"
            aria-label="Close modal"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {success ? (
          <div className="py-8 text-center space-y-2">
            <CheckCircle2 className="w-12 h-12 text-emerald-400 mx-auto animate-bounce" />
            <h4 className="text-sm font-bold text-white">Emergency Beacon Dispatched</h4>
            <p className="text-xs text-slate-400 max-w-sm mx-auto">
              Situation room commanders, legal rapid response team, and security coordinators have been alerted.
            </p>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="mt-4 space-y-4">
            {/* Category Select */}
            <div>
              <label className="block text-xs font-semibold text-slate-300 mb-1.5">
                Incident Category
              </label>
              <select
                value={category}
                onChange={(e) => setCategory(e.target.value as IncidentCategory)}
                className="w-full py-2 px-3 bg-slate-950 border border-slate-800 rounded-xl text-xs text-white focus:outline-none focus:border-red-600"
              >
                <option value="BALLOT_SNATCHING">Ballot Snatching / Box Hijacking</option>
                <option value="VOTER_INTIMIDATION">Voter Intimidation / Thuggery</option>
                <option value="BVAS_FAILURE">BVAS Total Failure / Non-Accreditation</option>
                <option value="VIOLENCE">Violence / Physical Assault / Gunshots</option>
                <option value="LATE_ARRIVAL">Late Arrival of Materials (&gt;2 hrs)</option>
                <option value="UNAUTHORIZED_OFFICIALS">Unauthorized Security / Agents</option>
                <option value="LOGISTICS_DELAY">Logistics / Missing Result Sheets</option>
                <option value="OTHER">Other Critical Distress</option>
              </select>
            </div>

            {/* Severity level */}
            <div className="grid grid-cols-3 gap-2">
              <button
                type="button"
                onClick={() => setSeverity('CRITICAL')}
                className={`py-2 px-1 rounded-xl text-xs font-bold border transition text-center ${
                  severity === 'CRITICAL'
                    ? 'bg-red-950/80 border-red-600 text-red-200 ring-1 ring-red-600'
                    : 'bg-slate-950 border-slate-800 text-slate-400'
                }`}
              >
                CRITICAL
              </button>
              <button
                type="button"
                onClick={() => setSeverity('HIGH')}
                className={`py-2 px-1 rounded-xl text-xs font-bold border transition text-center ${
                  severity === 'HIGH'
                    ? 'bg-amber-950/80 border-amber-600 text-amber-200 ring-1 ring-amber-600'
                    : 'bg-slate-950 border-slate-800 text-slate-400'
                }`}
              >
                HIGH
              </button>
              <button
                type="button"
                onClick={() => setSeverity('MEDIUM')}
                className={`py-2 px-1 rounded-xl text-xs font-bold border transition text-center ${
                  severity === 'MEDIUM'
                    ? 'bg-slate-800 border-slate-600 text-slate-200 ring-1 ring-slate-600'
                    : 'bg-slate-950 border-slate-800 text-slate-400'
                }`}
              >
                MEDIUM
              </button>
            </div>

            {/* Description */}
            <div>
              <label className="block text-xs font-semibold text-slate-300 mb-1">
                Brief Situation Summary
              </label>
              <textarea
                required
                rows={3}
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="State what is happening, number of perpetrators, and current status of voting or INEC officials..."
                className="w-full py-2 px-3 bg-slate-950 border border-slate-800 rounded-xl text-xs text-white placeholder-slate-500 focus:outline-none focus:border-red-600"
              />
            </div>

            {/* GPS Geolocation Stamp */}
            <div className="p-2.5 bg-slate-950 rounded-xl border border-slate-800 flex items-center justify-between text-xs">
              <div className="flex items-center space-x-2 text-slate-300">
                <MapPin className="w-3.5 h-3.5 text-red-400 shrink-0" />
                <span className="font-mono text-[11px]">
                  {gettingLocation
                    ? 'Acquiring GPS fix...'
                    : coords
                    ? `GPS: ${coords.lat.toFixed(4)}, ${coords.lng.toFixed(4)}`
                    : 'GPS: 6.6190, 3.3580'}
                </span>
              </div>
              <span className="text-[10px] text-emerald-400 font-mono">Timestamped</span>
            </div>

            {/* Submit SOS Button */}
            <button
              type="submit"
              disabled={submitting || !description.trim()}
              className="w-full py-2.5 px-4 rounded-xl bg-gradient-to-r from-red-700 via-red-600 to-red-700 hover:from-red-600 hover:to-red-500 border border-red-500/50 text-white font-extrabold text-xs uppercase tracking-wider shadow-md shadow-red-950/60 flex items-center justify-center gap-2 transition disabled:opacity-50"
            >
              {submitting ? 'Broadcasting SOS Signal...' : 'Dispatch SOS Beacon'}
              <Send className="w-3.5 h-3.5" />
            </button>
          </form>
        )}
      </div>
    </div>
  );
};
