'use client';

import React, { useState, useEffect } from 'react';
import {
  AlertOctagon,
  ShieldAlert,
  Clock,
  MapPin,
  CheckCircle2,
  Filter,
  RotateCw,
  Eye,
  AlertTriangle,
  Radio,
  ExternalLink
} from 'lucide-react';
import { IncidentReport, IncidentStatus, IncidentSeverity, ScopeType } from '@/types';
import { INITIAL_INCIDENTS } from '@/lib/electoralData';

interface IncidentDeskProps {
  userScopeType?: ScopeType;
  userScopeId?: string;
}

export const IncidentDesk: React.FC<IncidentDeskProps> = ({
  userScopeType = 'NATIONAL',
  userScopeId = 'ALL',
}) => {
  const [incidents, setIncidents] = useState<IncidentReport[]>(INITIAL_INCIDENTS);
  const [selectedSeverity, setSelectedSeverity] = useState<string>('ALL');
  const [selectedStatus, setSelectedStatus] = useState<string>('ALL');
  const [loading, setLoading] = useState(false);
  const [updatingId, setUpdatingId] = useState<string | null>(null);

  const fetchIncidents = async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/incidents?status=${selectedStatus}&severity=${selectedSeverity}`);
      const data = await res.json();
      if (data.incidents) {
        setIncidents(data.incidents);
      }
    } catch (err) {
      console.error('Fetch incidents error:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchIncidents();
  }, [selectedSeverity, selectedStatus]);

  const handleUpdateStatus = async (id: string, newStatus: IncidentStatus) => {
    setUpdatingId(id);
    try {
      const res = await fetch('/api/incidents', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          id,
          status: newStatus,
          resolution_notes: `Status changed to ${newStatus} by Situation Room Command.`,
        }),
      });
      const data = await res.json();
      if (res.ok) {
        setIncidents((prev) =>
          prev.map((inc) => (inc.id === id ? { ...inc, status: newStatus } : inc))
        );
      }
    } catch (err) {
      console.error('Update status error:', err);
    } finally {
      setUpdatingId(null);
    }
  };

  const getSeverityBadge = (severity: IncidentSeverity) => {
    switch (severity) {
      case 'CRITICAL':
        return (
          <span className="px-2 py-0.5 rounded-full text-[10px] font-extrabold uppercase bg-rose-950 text-rose-300 border border-rose-600 animate-pulse flex items-center gap-1">
            <span className="w-1.5 h-1.5 rounded-full bg-rose-500" /> Critical
          </span>
        );
      case 'HIGH':
        return (
          <span className="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase bg-amber-950 text-amber-300 border border-amber-600 flex items-center gap-1">
            High Severity
          </span>
        );
      default:
        return (
          <span className="px-2 py-0.5 rounded-full text-[10px] font-medium uppercase bg-blue-950 text-blue-300 border border-blue-700">
            Medium
          </span>
        );
    }
  };

  return (
    <div className="bg-slate-900 border border-slate-800 rounded-2xl shadow-xl overflow-hidden">
      {/* Incident Header */}
      <div className="p-4 sm:p-5 bg-slate-950/90 border-b border-slate-800 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
        <div className="flex items-center space-x-3">
          <div className="w-9 h-9 rounded-xl bg-rose-950/80 border border-rose-600/40 text-rose-400 flex items-center justify-center">
            <ShieldAlert className="w-5 h-5 animate-pulse" />
          </div>
          <div>
            <h3 className="text-sm sm:text-base font-bold text-white flex items-center gap-2">
              Live Situation Room Incident Desk
              <span className="text-[10px] bg-rose-950 text-rose-300 px-2 py-0.5 rounded-full border border-rose-700 font-mono">
                {incidents.filter((i) => i.status !== 'RESOLVED').length} Active
              </span>
            </h3>
            <p className="text-[11px] text-slate-400">
              Emergency beacon broadcasts, field distress logs, and rapid response dispatches
            </p>
          </div>
        </div>

        {/* Filters and Refresh */}
        <div className="flex items-center gap-2 w-full sm:w-auto">
          {/* Severity Filter */}
          <select
            value={selectedSeverity}
            onChange={(e) => setSelectedSeverity(e.target.value)}
            className="py-1.5 px-2 bg-slate-900 border border-slate-800 rounded-xl text-xs text-white focus:outline-none"
          >
            <option value="ALL">All Severities</option>
            <option value="CRITICAL">Critical Only</option>
            <option value="HIGH">High Severity</option>
            <option value="MEDIUM">Medium Severity</option>
          </select>

          {/* Status Filter */}
          <select
            value={selectedStatus}
            onChange={(e) => setSelectedStatus(e.target.value)}
            className="py-1.5 px-2 bg-slate-900 border border-slate-800 rounded-xl text-xs text-white focus:outline-none"
          >
            <option value="ALL">All Statuses</option>
            <option value="PENDING">Pending Action</option>
            <option value="INVESTIGATING">Investigating</option>
            <option value="RESOLVED">Resolved</option>
          </select>

          <button
            onClick={fetchIncidents}
            disabled={loading}
            className="p-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white transition"
            title="Refresh Incidents"
          >
            <RotateCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </div>

      {/* Incidents List */}
      <div className="p-4 sm:p-5 divide-y divide-slate-800/80 space-y-3 max-h-[480px] overflow-y-auto">
        {incidents.length === 0 ? (
          <div className="py-8 text-center text-slate-500 text-xs">
            No incidents reported matching current filters.
          </div>
        ) : (
          incidents.map((inc) => (
            <div
              key={inc.id}
              className="pt-3 first:pt-0 pb-3 flex flex-col sm:flex-row items-start justify-between gap-3"
            >
              <div className="space-y-1.5 flex-1">
                <div className="flex items-center flex-wrap gap-2">
                  {getSeverityBadge(inc.severity)}
                  <span className="px-2 py-0.5 rounded bg-slate-800 border border-slate-700 font-mono text-[10px] font-bold text-white">
                    {inc.category.replace('_', ' ')}
                  </span>
                  <span className="text-[11px] font-mono text-emerald-400 font-bold flex items-center gap-1">
                    <MapPin className="w-3 h-3" />
                    {inc.pu_code} &bull; {inc.lga_name}, {inc.state_name}
                  </span>
                </div>

                <p className="text-xs text-slate-200 leading-relaxed font-normal">
                  {inc.description}
                </p>

                <div className="flex items-center gap-3 text-[10px] text-slate-400 font-mono">
                  <span>Reported by: <strong className="text-slate-300">{inc.reported_by_name || 'Agent'}</strong></span>
                  <span>&bull;</span>
                  <span>{new Date(inc.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
                  {inc.latitude && (
                    <>
                      <span>&bull;</span>
                      <span>GPS: {inc.latitude.toFixed(4)}, {inc.longitude?.toFixed(4)}</span>
                    </>
                  )}
                </div>

                {inc.resolution_notes && (
                  <div className="p-2 rounded-lg bg-slate-950 border border-slate-800 text-[11px] text-slate-300 flex items-center gap-1.5">
                    <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400 flex-shrink-0" />
                    <span>Resolution: {inc.resolution_notes}</span>
                  </div>
                )}
              </div>

              {/* Status Action Switcher */}
              <div className="flex items-center gap-1.5 self-end sm:self-center flex-shrink-0">
                <button
                  type="button"
                  disabled={updatingId === inc.id}
                  onClick={() => handleUpdateStatus(inc.id, 'PENDING')}
                  className={`px-2.5 py-1 rounded-lg text-[11px] font-semibold border transition ${
                    inc.status === 'PENDING'
                      ? 'bg-rose-950 text-rose-300 border-rose-600'
                      : 'bg-slate-950 text-slate-400 border-slate-800 hover:text-white'
                  }`}
                >
                  Pending
                </button>
                <button
                  type="button"
                  disabled={updatingId === inc.id}
                  onClick={() => handleUpdateStatus(inc.id, 'INVESTIGATING')}
                  className={`px-2.5 py-1 rounded-lg text-[11px] font-semibold border transition ${
                    inc.status === 'INVESTIGATING'
                      ? 'bg-amber-950 text-amber-300 border-amber-600'
                      : 'bg-slate-950 text-slate-400 border-slate-800 hover:text-white'
                  }`}
                >
                  Investigating
                </button>
                <button
                  type="button"
                  disabled={updatingId === inc.id}
                  onClick={() => handleUpdateStatus(inc.id, 'RESOLVED')}
                  className={`px-2.5 py-1 rounded-lg text-[11px] font-semibold border transition ${
                    inc.status === 'RESOLVED'
                      ? 'bg-emerald-950 text-emerald-300 border-emerald-600'
                      : 'bg-slate-950 text-slate-400 border-slate-800 hover:text-white'
                  }`}
                >
                  Resolved
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
};
