"use client";

import { useRouter } from "next/navigation";
import { useAuth } from "@/components/AuthProvider";
import { useIncidents } from "@/lib/useIncidents";
import { c2api } from "@/lib/c2api";
import type { IncidentRecord } from "@/lib/types";
import { useState } from "react";

const TYPE_COLORS: Record<string, string> = {
  fire:     "bg-red-900 text-red-300",
  police:   "bg-blue-900 text-blue-300",
  ems:      "bg-yellow-900 text-yellow-300",
  accident: "bg-orange-900 text-orange-300",
  other:    "bg-gray-800 text-gray-300",
};

const SEVERITY_COLORS: Record<string, string> = {
  major:   "bg-red-950 text-red-400",
  moderate: "bg-orange-950 text-orange-400",
  minor:   "bg-gray-800 text-gray-400",
};

function severityBadge(severity: string | null | undefined) {
  if (!severity || severity === "unknown") return null;
  const cls = SEVERITY_COLORS[severity] ?? "bg-gray-800 text-gray-400";
  return (
    <span className={`text-xs font-mono px-2 py-0.5 rounded-full capitalize ${cls}`}>
      {severity}
    </span>
  );
}

function typeBadge(type: string | null) {
  const cls = TYPE_COLORS[type ?? "other"] ?? TYPE_COLORS.other;
  return (
    <span className={`text-xs font-mono px-2 py-0.5 rounded-full capitalize ${cls}`}>
      {type ?? "other"}
    </span>
  );
}

function fmtTime(iso: string) {
  try { return new Date(iso).toLocaleString(); } catch { return iso; }
}

function IncidentRow({ incident, isAdmin, onResolve }: {
  incident: IncidentRecord;
  isAdmin: boolean;
  onResolve: (id: string) => void;
}) {
  const router = useRouter();

  return (
    <tr
      className="border-b border-gray-800 hover:bg-gray-900 cursor-pointer"
      onClick={() => router.push(`/incidents/${incident.incident_id}`)}
    >
      <td className="px-4 py-3">{typeBadge(incident.type)}</td>
      <td className="px-4 py-3 text-white text-sm">{incident.title ?? "—"}</td>
      <td className="px-4 py-3">
        <span className={`text-xs px-2 py-0.5 rounded-full ${
          incident.status === "active"
            ? "bg-green-900 text-green-300"
            : "bg-gray-800 text-gray-400"
        }`}>
          {incident.status}
        </span>
      </td>
      <td className="px-4 py-3">{severityBadge(incident.severity)}</td>
      <td className="px-4 py-3 text-gray-400 text-xs font-mono">{incident.call_ids.length}</td>
      <td className="px-4 py-3 text-gray-400 text-xs font-mono">{fmtTime(incident.started_at)}</td>
      <td className="px-4 py-3 text-gray-400 text-xs font-mono">{fmtTime(incident.updated_at)}</td>
      <td className="px-4 py-3">
        {isAdmin && incident.status === "active" && (
          <button
            onClick={(e) => { e.stopPropagation(); onResolve(incident.incident_id); }}
            className="text-xs bg-gray-800 hover:bg-gray-700 text-gray-300 px-2 py-1 rounded transition-colors"
          >
            Resolve
          </button>
        )}
      </td>
    </tr>
  );
}

function CreateModal({ onClose, onCreate }: {
  onClose: () => void;
  onCreate: (body: object) => Promise<void>;
}) {
  const [title,   setTitle]   = useState("");
  const [type,    setType]    = useState("other");
  const [summary, setSummary] = useState("");
  const [saving,  setSaving]  = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      await onCreate({ title, type, summary: summary || null, status: "active" });
      onClose();
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
      <form
        onSubmit={handleSubmit}
        className="bg-gray-900 border border-gray-700 rounded-xl p-6 w-full max-w-md space-y-4"
      >
        <h2 className="text-white font-bold">Create Incident</h2>
        <div>
          <label className="text-xs text-gray-400 block mb-1">Title</label>
          <input
            required value={title} onChange={(e) => setTitle(e.target.value)}
            className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-indigo-500"
          />
        </div>
        <div>
          <label className="text-xs text-gray-400 block mb-1">Type</label>
          <select
            value={type} onChange={(e) => setType(e.target.value)}
            className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none"
          >
            {["fire", "police", "ems", "accident", "other"].map((t) => (
              <option key={t} value={t}>{t}</option>
            ))}
          </select>
        </div>
        <div>
          <label className="text-xs text-gray-400 block mb-1">Summary (optional)</label>
          <textarea
            value={summary} onChange={(e) => setSummary(e.target.value)} rows={2}
            className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none resize-none"
          />
        </div>
        <div className="flex gap-3 justify-end">
          <button type="button" onClick={onClose} className="text-sm text-gray-400 hover:text-gray-200 px-4 py-2">
            Cancel
          </button>
          <button
            type="submit" disabled={saving}
            className="bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white text-sm rounded-lg px-4 py-2"
          >
            {saving ? "Creating…" : "Create"}
          </button>
        </div>
      </form>
    </div>
  );
}

function IncidentCards({ incidents, isAdmin, onResolve }: {
  incidents: IncidentRecord[];
  isAdmin: boolean;
  onResolve: (id: string) => void;
}) {
  const router = useRouter();
  return (
    <div className="space-y-2">
      {incidents.map((inc) => (
        <div
          key={inc.incident_id}
          className="bg-gray-900 border border-gray-800 rounded-xl p-4 cursor-pointer active:bg-gray-800"
          onClick={() => router.push(`/incidents/${inc.incident_id}`)}
        >
          <div className="flex items-center justify-between gap-2 mb-1.5">
            <div className="flex items-center gap-2">
              {typeBadge(inc.type)}
              <span className={`text-xs px-2 py-0.5 rounded-full ${
                inc.status === "active" ? "bg-green-900 text-green-300" : "bg-gray-800 text-gray-400"
              }`}>{inc.status}</span>
            </div>
            {isAdmin && inc.status === "active" && (
              <button
                onClick={(e) => { e.stopPropagation(); onResolve(inc.incident_id); }}
                className="text-xs bg-gray-800 hover:bg-gray-700 text-gray-300 px-2 py-1 rounded transition-colors"
              >
                Resolve
              </button>
            )}
          </div>
          <p className="text-white text-sm font-semibold leading-snug">{inc.title ?? "—"}</p>
          <div className="flex items-center gap-2 mt-1">
            {severityBadge(inc.severity)}
            <p className="text-gray-500 text-xs font-mono">
              {fmtTime(inc.started_at)} · {inc.call_ids.length} call{inc.call_ids.length !== 1 ? "s" : ""}
            </p>
          </div>
        </div>
      ))}
    </div>
  );
}

function IncidentTable({ incidents, isAdmin, onResolve }: {
  incidents: IncidentRecord[];
  isAdmin: boolean;
  onResolve: (id: string) => void;
}) {
  return (
    <>
      {/* Mobile card view */}
      <div className="sm:hidden">
        <IncidentCards incidents={incidents} isAdmin={isAdmin} onResolve={onResolve} />
      </div>

      {/* Desktop table view */}
      <div className="hidden sm:block bg-gray-900 border border-gray-800 rounded-xl overflow-hidden">
        <table className="w-full text-left">
          <thead>
            <tr className="border-b border-gray-800 text-xs text-gray-500 uppercase">
              <th className="px-4 py-3">Type</th>
              <th className="px-4 py-3">Title</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3">Severity</th>
              <th className="px-4 py-3">Calls</th>
              <th className="px-4 py-3">Started</th>
              <th className="px-4 py-3">Updated</th>
              <th className="px-4 py-3"></th>
            </tr>
          </thead>
          <tbody>
            {incidents.map((inc) => (
              <IncidentRow
                key={inc.incident_id}
                incident={inc}
                isAdmin={isAdmin}
                onResolve={onResolve}
              />
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

export default function IncidentsPage() {
  const { isAdmin }              = useAuth();
  const { incidents, loading }   = useIncidents();
  const [showCreate, setShowCreate] = useState(false);

  const active   = incidents.filter((i) => i.status === "active");
  const resolved = incidents.filter((i) => i.status === "resolved");

  async function handleResolve(id: string) {
    try { await c2api.updateIncident(id, { status: "resolved" }); }
    catch (e) { console.error(e); }
  }

  return (
    <div className="p-6 max-w-7xl mx-auto space-y-8">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <h1 className="text-white text-xl font-bold font-mono">Incidents</h1>
          {active.length > 0 && (
            <span className="text-xs bg-red-900 text-red-300 px-2 py-0.5 rounded-full font-mono">
              {active.length} active
            </span>
          )}
        </div>
        {isAdmin && (
          <button
            onClick={() => setShowCreate(true)}
            className="bg-indigo-600 hover:bg-indigo-500 text-white text-sm rounded-lg px-4 py-2 transition-colors"
          >
            + Create Incident
          </button>
        )}
      </div>

      {loading ? (
        <p className="text-gray-500 text-sm font-mono">Loading…</p>
      ) : (
        <>
          {active.length > 0 && (
            <section>
              <h2 className="text-sm font-mono text-gray-400 uppercase tracking-wider mb-3">Active</h2>
              <IncidentTable incidents={active} isAdmin={isAdmin} onResolve={handleResolve} />
            </section>
          )}

          {resolved.length > 0 && (
            <section>
              <h2 className="text-sm font-mono text-gray-400 uppercase tracking-wider mb-3">Resolved</h2>
              <IncidentTable incidents={resolved} isAdmin={isAdmin} onResolve={handleResolve} />
            </section>
          )}

          {incidents.length === 0 && (
            <p className="text-gray-600 text-sm font-mono">No incidents recorded yet.</p>
          )}
        </>
      )}

      {showCreate && (
        <CreateModal onClose={() => setShowCreate(false)} onCreate={async (b) => { await c2api.createIncident(b); }} />
      )}
    </div>
  );
}
