"use client";

import { useState, useEffect, useCallback } from "react";
import {
  AlertTriangle,
  AlertCircle,
  Info,
  Clock,
  CheckCircle,
  XCircle,
  RefreshCw,
  Bell,
  User,
  ExternalLink,
} from "lucide-react";

type IncidentSeverity = "critical" | "warning" | "info";
type IncidentStatus = "open" | "acknowledged" | "resolved";

interface Incident {
  id: string;
  type: string;
  severity: IncidentSeverity;
  title: string;
  description: string;
  component: string;
  status: IncidentStatus;
  acknowledgedBy: string | null;
  acknowledgedAt: string | null;
  resolvedAt: string | null;
  metadata: Record<string, unknown>;
  createdAt: string;
  updatedAt: string;
}

interface IncidentStats {
  total: number;
  open: number;
  acknowledged: number;
  resolved: number;
  bySeverity: Record<IncidentSeverity, number>;
  avgResolutionTimeMs: number | null;
}

interface IncidentResponse {
  incidents: Incident[];
  stats: IncidentStats;
}

// Severity badge component
function SeverityBadge({ severity }: { severity: IncidentSeverity }) {
  const config = {
    critical: {
      bg: "bg-red-100",
      text: "text-red-700",
      icon: AlertCircle,
      label: "Critical",
    },
    warning: {
      bg: "bg-yellow-100",
      text: "text-yellow-700",
      icon: AlertTriangle,
      label: "Warning",
    },
    info: {
      bg: "bg-blue-100",
      text: "text-blue-700",
      icon: Info,
      label: "Info",
    },
  };

  const { bg, text, icon: Icon, label } = config[severity];

  return (
    <span
      className={`inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-full ${bg} ${text}`}
    >
      <Icon className="h-3 w-3" />
      {label}
    </span>
  );
}

// Status badge component
function StatusBadge({ status }: { status: IncidentStatus }) {
  const config = {
    open: {
      bg: "bg-red-100",
      text: "text-red-700",
      label: "Open",
    },
    acknowledged: {
      bg: "bg-yellow-100",
      text: "text-yellow-700",
      label: "Acknowledged",
    },
    resolved: {
      bg: "bg-green-100",
      text: "text-green-700",
      label: "Resolved",
    },
  };

  const { bg, text, label } = config[status];

  return (
    <span
      className={`inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-full ${bg} ${text}`}
    >
      {label}
    </span>
  );
}

// Time ago helper
function getTimeAgo(dateString: string): string {
  const now = new Date();
  const date = new Date(dateString);
  const diffMs = now.getTime() - date.getTime();

  const minutes = Math.floor(diffMs / (1000 * 60));
  const hours = Math.floor(diffMs / (1000 * 60 * 60));
  const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));

  if (days > 0) return `${days}d ago`;
  if (hours > 0) return `${hours}h ago`;
  if (minutes > 0) return `${minutes}m ago`;
  return "Just now";
}

// Format duration
function formatDuration(ms: number): string {
  const hours = Math.floor(ms / (1000 * 60 * 60));
  const minutes = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60));

  if (hours > 24) {
    const days = Math.floor(hours / 24);
    return `${days}d ${hours % 24}h`;
  }
  if (hours > 0) return `${hours}h ${minutes}m`;
  return `${minutes}m`;
}

// Individual incident card
function IncidentCard({
  incident,
  onAcknowledge,
  onResolve,
  isActioning,
}: {
  incident: Incident;
  onAcknowledge: (id: string) => void;
  onResolve: (id: string) => void;
  isActioning: boolean;
}) {
  const isPulsing =
    incident.status === "open" && incident.severity === "critical";

  return (
    <div
      className={`border rounded-xl p-4 transition-all ${
        incident.severity === "critical"
          ? "border-red-200 bg-red-50"
          : incident.severity === "warning"
            ? "border-yellow-200 bg-yellow-50"
            : "border-blue-200 bg-blue-50"
      } ${isPulsing ? "animate-pulse" : ""}`}
    >
      {/* Header */}
      <div className="flex items-start justify-between mb-3">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            <SeverityBadge severity={incident.severity} />
            <StatusBadge status={incident.status} />
          </div>
          <h4 className="font-medium text-gray-900">{incident.title}</h4>
        </div>
        <div className="flex items-center gap-1 text-xs text-gray-500">
          <Clock className="h-3 w-3" />
          {getTimeAgo(incident.createdAt)}
        </div>
      </div>

      {/* Description */}
      <p className="text-sm text-gray-600 mb-3">{incident.description}</p>

      {/* Metadata */}
      <div className="flex items-center gap-4 text-xs text-gray-500 mb-3">
        <span className="flex items-center gap-1">
          <span className="font-medium">Component:</span>
          {incident.component}
        </span>
        <span className="flex items-center gap-1">
          <span className="font-medium">Type:</span>
          {incident.type.replace(/_/g, " ")}
        </span>
      </div>

      {/* Acknowledged info */}
      {incident.acknowledgedBy && (
        <div className="flex items-center gap-2 text-xs text-gray-500 mb-3 p-2 bg-white/50 rounded">
          <User className="h-3 w-3" />
          <span>
            Acknowledged by{" "}
            <span className="font-medium">{incident.acknowledgedBy}</span>
            {incident.acknowledgedAt &&
              ` ${getTimeAgo(incident.acknowledgedAt)}`}
          </span>
        </div>
      )}

      {/* Actions */}
      {incident.status !== "resolved" && (
        <div className="flex items-center gap-2 pt-3 border-t border-gray-200/50">
          {incident.status === "open" && (
            <button
              onClick={() => onAcknowledge(incident.id)}
              disabled={isActioning}
              className="flex-1 inline-flex items-center justify-center gap-1 px-3 py-2 text-sm font-medium text-yellow-700 bg-yellow-100 rounded-lg hover:bg-yellow-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              <Bell className="h-4 w-4" />
              Acknowledge
            </button>
          )}
          <button
            onClick={() => onResolve(incident.id)}
            disabled={isActioning}
            className="flex-1 inline-flex items-center justify-center gap-1 px-3 py-2 text-sm font-medium text-green-700 bg-green-100 rounded-lg hover:bg-green-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <CheckCircle className="h-4 w-4" />
            Resolve
          </button>
        </div>
      )}
    </div>
  );
}

// Stats summary component
function IncidentStatsSummary({ stats }: { stats: IncidentStats }) {
  return (
    <div className="grid grid-cols-4 gap-3 mb-4">
      <div className="bg-red-50 rounded-lg p-3 text-center">
        <div className="text-2xl font-bold text-red-600">{stats.open}</div>
        <div className="text-xs text-red-700">Open</div>
      </div>
      <div className="bg-yellow-50 rounded-lg p-3 text-center">
        <div className="text-2xl font-bold text-yellow-600">
          {stats.acknowledged}
        </div>
        <div className="text-xs text-yellow-700">Acknowledged</div>
      </div>
      <div className="bg-green-50 rounded-lg p-3 text-center">
        <div className="text-2xl font-bold text-green-600">
          {stats.resolved}
        </div>
        <div className="text-xs text-green-700">Resolved</div>
      </div>
      <div className="bg-gray-50 rounded-lg p-3 text-center">
        <div className="text-2xl font-bold text-gray-600">
          {stats.avgResolutionTimeMs
            ? formatDuration(stats.avgResolutionTimeMs)
            : "-"}
        </div>
        <div className="text-xs text-gray-700">Avg Resolution</div>
      </div>
    </div>
  );
}

// Loading skeleton
function LoadingSkeleton() {
  return (
    <div className="animate-pulse space-y-4">
      <div className="h-6 w-48 bg-gray-200 rounded" />
      <div className="grid grid-cols-4 gap-3">
        {[1, 2, 3, 4].map((i) => (
          <div key={i} className="h-16 bg-gray-200 rounded-lg" />
        ))}
      </div>
      <div className="space-y-3">
        {[1, 2, 3].map((i) => (
          <div key={i} className="h-32 bg-gray-200 rounded-xl" />
        ))}
      </div>
    </div>
  );
}

// Empty state
function EmptyState() {
  return (
    <div className="text-center py-8">
      <CheckCircle className="h-12 w-12 mx-auto mb-3 text-green-500" />
      <h4 className="font-medium text-gray-900 mb-1">All Clear</h4>
      <p className="text-sm text-gray-500">No active incidents at the moment</p>
    </div>
  );
}

export function IncidentPanel() {
  const [data, setData] = useState<IncidentResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [actioningId, setActioningId] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/staff/incidents", {
        credentials: "include",
      });

      if (!response.ok) {
        throw new Error("Failed to fetch incidents");
      }

      const result = await response.json();
      setData(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    // Auto-refresh every 30 seconds for incidents (more frequent)
    const interval = setInterval(fetchData, 30000);
    return () => clearInterval(interval);
  }, [fetchData]);

  const handleAcknowledge = async (id: string) => {
    setActioningId(id);
    try {
      const response = await fetch("/api/staff/incidents", {
        method: "PATCH",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, action: "acknowledge" }),
      });

      if (!response.ok) {
        throw new Error("Failed to acknowledge incident");
      }

      await fetchData();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to acknowledge");
    } finally {
      setActioningId(null);
    }
  };

  const handleResolve = async (id: string) => {
    setActioningId(id);
    try {
      const response = await fetch("/api/staff/incidents", {
        method: "PATCH",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, action: "resolve" }),
      });

      if (!response.ok) {
        throw new Error("Failed to resolve incident");
      }

      await fetchData();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to resolve");
    } finally {
      setActioningId(null);
    }
  };

  if (loading) {
    return (
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <LoadingSkeleton />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <div className="text-center py-8">
          <XCircle className="h-8 w-8 mx-auto mb-2 text-red-500" />
          <p className="text-gray-600">{error}</p>
          <button
            onClick={fetchData}
            className="mt-4 inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-green rounded-lg hover:bg-green-700"
          >
            <RefreshCw className="h-4 w-4" />
            Retry
          </button>
        </div>
      </div>
    );
  }

  if (!data) return null;

  const { incidents, stats } = data;
  const hasActiveIncidents = incidents.length > 0;
  const hasCritical = incidents.some(
    (i) => i.severity === "critical" && i.status === "open",
  );

  return (
    <div
      className={`bg-white rounded-2xl shadow-sm border p-6 ${
        hasCritical ? "border-red-300" : "border-gray-100"
      }`}
    >
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div
            className={`p-2 rounded-lg ${
              hasCritical
                ? "bg-red-100"
                : hasActiveIncidents
                  ? "bg-yellow-100"
                  : "bg-green-100"
            }`}
          >
            {hasCritical ? (
              <AlertCircle className="h-5 w-5 text-red-600" />
            ) : hasActiveIncidents ? (
              <AlertTriangle className="h-5 w-5 text-yellow-600" />
            ) : (
              <CheckCircle className="h-5 w-5 text-green-600" />
            )}
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              Active Incidents
            </h3>
            <p className="text-sm text-gray-500">
              {hasActiveIncidents
                ? `${incidents.length} incident${incidents.length > 1 ? "s" : ""} requiring attention`
                : "All systems operational"}
            </p>
          </div>
        </div>

        <button
          onClick={fetchData}
          className="p-1.5 text-gray-500 hover:text-gray-700 rounded-lg hover:bg-gray-100"
          title="Refresh"
        >
          <RefreshCw className="h-4 w-4" />
        </button>
      </div>

      {/* Stats */}
      <IncidentStatsSummary stats={stats} />

      {/* Incidents list */}
      {hasActiveIncidents ? (
        <div className="space-y-3">
          {incidents.map((incident) => (
            <IncidentCard
              key={incident.id}
              incident={incident}
              onAcknowledge={handleAcknowledge}
              onResolve={handleResolve}
              isActioning={actioningId === incident.id}
            />
          ))}
        </div>
      ) : (
        <EmptyState />
      )}

      {/* On-call link */}
      {hasCritical && (
        <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2 text-sm text-red-700">
              <Bell className="h-4 w-4" />
              <span className="font-medium">Critical incident active</span>
            </div>
            <a
              href="mailto:oncall@mawidi.com"
              className="inline-flex items-center gap-1 text-sm text-red-600 hover:text-red-800"
            >
              Contact On-Call <ExternalLink className="h-3 w-3" />
            </a>
          </div>
        </div>
      )}
    </div>
  );
}

export default IncidentPanel;
