"use client";

import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import { useIncident } from "@/lib/useIncidents";
import { useCallsByIncident } from "@/lib/useCalls";
import { useSystems } from "@/lib/useSystems";
import { useAuth } from "@/components/AuthProvider";
import { CallRow } from "@/components/CallRow";
import { c2api } from "@/lib/c2api";
import type { IncidentRecord } from "@/lib/types";

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",
};

function TypeBadge({ type }: { 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 StatusBadge({ status }: { status: IncidentRecord["status"] }) {
  return (
    <span className={`text-xs px-2 py-0.5 rounded-full font-mono ${
      status === "active" ? "bg-green-900 text-green-300" : "bg-gray-800 text-gray-400"
    }`}>
      {status}
    </span>
  );
}

export default function IncidentDetailPage() {
  const params  = useParams();
  const id      = params.id as string;
  const router  = useRouter();

  const { incident, loading }        = useIncident(id);
  const { calls, loading: callsLoading } = useCallsByIncident(id);
  const { systems }                  = useSystems();
  const { isAdmin }                  = useAuth();

  const [summarizing, setSummarizing] = useState(false);
  const [resolving,   setResolving]   = useState(false);

  const systemMap = Object.fromEntries(systems.map((s) => [s.system_id, s]));

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

  async function handleSummarize() {
    setSummarizing(true);
    try { await c2api.summarizeIncident(id); }
    catch (e) { console.error(e); }
    finally   { setSummarizing(false); }
  }

  if (loading) {
    return <p className="text-gray-500 text-sm font-mono p-6">Loading…</p>;
  }
  if (!incident) {
    return <p className="text-gray-500 text-sm font-mono p-6">Incident not found.</p>;
  }

  return (
    <div className="space-y-6">
      {/* Back */}
      <button
        onClick={() => router.back()}
        className="text-xs text-gray-500 hover:text-gray-300 font-mono transition-colors"
      >
        ← Incidents
      </button>

      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div className="flex items-center gap-3 flex-wrap">
          <TypeBadge type={incident.type} />
          <h1 className="text-xl font-bold text-white font-mono">
            {incident.title ?? "Incident"}
          </h1>
          <StatusBadge status={incident.status} />
        </div>
        {isAdmin && (
          <div className="flex gap-2 shrink-0">
            <button
              onClick={handleSummarize}
              disabled={summarizing}
              className="text-xs bg-indigo-700 hover:bg-indigo-600 disabled:opacity-50 text-white px-3 py-1.5 rounded-lg transition-colors"
            >
              {summarizing ? "Generating…" : "Regenerate summary"}
            </button>
            {incident.status === "active" && (
              <button
                onClick={handleResolve}
                disabled={resolving}
                className="text-xs bg-gray-800 hover:bg-gray-700 disabled:opacity-50 text-gray-300 px-3 py-1.5 rounded-lg transition-colors"
              >
                {resolving ? "Resolving…" : "Resolve"}
              </button>
            )}
          </div>
        )}
      </div>

      {/* Summary */}
      <section>
        <h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-2">
          Summary
        </h2>
        {incident.summary ? (
          <p className="text-sm text-gray-300 bg-gray-900 border border-gray-800 rounded-lg p-4 leading-relaxed">
            {incident.summary}
          </p>
        ) : (
          <p className="text-sm text-gray-600 font-mono italic">
            No summary yet.{" "}
            {isAdmin && (
              <button
                onClick={handleSummarize}
                disabled={summarizing}
                className="text-indigo-400 hover:text-indigo-300 not-italic transition-colors"
              >
                Generate now
              </button>
            )}
          </p>
        )}
      </section>

      {/* Tags + Location */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <section>
          <h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-2">Tags</h2>
          {incident.tags.length > 0 ? (
            <div className="flex flex-wrap gap-1">
              {incident.tags.map((t) => (
                <span key={t} className="text-xs bg-gray-800 text-gray-300 px-2 py-0.5 rounded-full">
                  {t}
                </span>
              ))}
            </div>
          ) : (
            <p className="text-gray-600 text-sm font-mono">No tags.</p>
          )}
        </section>

        {incident.location && (
          <section>
            <h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-2">Location</h2>
            <p className="text-sm text-gray-300 font-mono">{incident.location}</p>
          </section>
        )}
      </div>

      {/* Metadata */}
      <div className="text-xs text-gray-600 font-mono flex flex-wrap gap-x-6 gap-y-1">
        <span>Started: <span className="text-gray-400">{new Date(incident.started_at).toLocaleString()}</span></span>
        <span>Updated: <span className="text-gray-400">{new Date(incident.updated_at).toLocaleString()}</span></span>
        <span>Calls: <span className="text-gray-400">{incident.call_ids.length}</span></span>
        {incident.talkgroup_ids?.length > 0 && (
          <span>Talkgroups: <span className="text-gray-400">{incident.talkgroup_ids.join(", ")}</span></span>
        )}
      </div>

      {/* Calls */}
      <section>
        <h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">Calls</h2>
        {callsLoading ? (
          <p className="text-gray-600 text-sm font-mono">Loading calls…</p>
        ) : calls.length === 0 ? (
          <p className="text-gray-600 text-sm font-mono">No calls linked yet.</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-xs text-gray-500 uppercase tracking-wider border-b border-gray-800">
                  <th className="px-4 py-2 text-left">Time</th>
                  <th className="px-4 py-2 text-left">Talkgroup</th>
                  <th className="px-4 py-2 text-left">System</th>
                  <th className="px-4 py-2 text-left">Node</th>
                  <th className="px-4 py-2 text-left">Duration</th>
                  <th className="px-4 py-2 text-left">Audio</th>
                  <th className="px-4 py-2"></th>
                </tr>
              </thead>
              <tbody>
                {calls.map((c) => (
                  <CallRow
                    key={c.call_id}
                    call={c}
                    systemName={systemMap[c.system_id ?? ""]?.name}
                    isAdmin={isAdmin}
                  />
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </div>
  );
}
