"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Activity,
  AlertTriangle,
  CheckCircle,
  Clock,
  TrendingDown,
  TrendingUp,
  RefreshCw,
  Gauge,
  Layers,
} from "lucide-react";

// SLO Types
type TimePeriod = "1h" | "24h" | "7d" | "30d";

interface SLOMetrics {
  uptime: {
    current: number;
    target: number;
    period: TimePeriod;
    totalRequests: number;
    successfulRequests: number;
    failedRequests: number;
  };
  errorBudget: {
    total: number;
    consumed: number;
    remaining: number;
    burnRate: number;
    periodDays: number;
  };
  messageFailureRate: {
    current: number;
    target: number;
    sent: number;
    failed: number;
    trend: number[];
  };
  webhookLatency: {
    p50: number;
    p95: number;
    p99: number;
    target: number;
    samples: number;
  };
  queueDepth: {
    current: number;
    max: number;
    pending: number;
    failed: number;
    dlq: number;
    trend: number[];
  };
  systemHealth: {
    overall: string;
    components: Array<{
      name: string;
      status: string;
      responseTime: number;
    }>;
  };
}

interface SLOResponse {
  metrics: SLOMetrics;
  targets: {
    uptime: number;
    errorBudget: number;
    messageDelivery: number;
    webhookLatency: number;
    queueDepth: number;
  };
  period: TimePeriod;
  calculatedAt: string;
}

// SLO Gauge Component
function SLOGauge({
  current,
  target,
  label,
  size = "default",
}: {
  current: number;
  target: number;
  label: string;
  size?: "small" | "default";
}) {
  const isMet = current >= target;
  const percentage = Math.min(100, current);
  const circumference = 2 * Math.PI * 40;
  const strokeDashoffset = circumference - (percentage / 100) * circumference;

  const sizeClass = size === "small" ? "w-20 h-20" : "w-24 h-24";
  const textSize = size === "small" ? "text-lg" : "text-2xl";

  return (
    <div className="relative flex flex-col items-center">
      <svg className={sizeClass} viewBox="0 0 96 96">
        {/* Background circle */}
        <circle
          className="stroke-gray-200"
          strokeWidth="8"
          fill="none"
          r="40"
          cx="48"
          cy="48"
        />
        {/* Progress circle */}
        <circle
          className={`transition-all duration-500 ${
            isMet ? "stroke-green-500" : "stroke-red-500"
          }`}
          strokeWidth="8"
          fill="none"
          r="40"
          cx="48"
          cy="48"
          strokeLinecap="round"
          strokeDasharray={circumference}
          strokeDashoffset={strokeDashoffset}
          transform="rotate(-90 48 48)"
        />
        {/* Target line */}
        <circle
          className="stroke-gray-400 stroke-dashed"
          strokeWidth="1"
          fill="none"
          r="40"
          cx="48"
          cy="48"
          strokeDasharray={`${(target / 100) * circumference} ${circumference}`}
          transform="rotate(-90 48 48)"
        />
      </svg>
      <div className="absolute inset-0 flex flex-col items-center justify-center">
        <span
          className={`${textSize} font-bold ${isMet ? "text-green-600" : "text-red-600"}`}
        >
          {current.toFixed(1)}%
        </span>
        <span className="text-xs text-gray-500">{label}</span>
      </div>
    </div>
  );
}

// Error Budget Bar
function ErrorBudgetBar({
  total,
  consumed,
  remaining,
  burnRate,
}: {
  total: number;
  consumed: number;
  remaining: number;
  burnRate: number;
}) {
  const consumedPercent = total > 0 ? (consumed / total) * 100 : 0;
  const isHealthy = burnRate <= 1;
  const isCritical = burnRate > 2;

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between text-sm">
        <span className="text-gray-600">Error Budget</span>
        <span
          className={`font-medium ${
            isHealthy
              ? "text-green-600"
              : isCritical
                ? "text-red-600"
                : "text-yellow-600"
          }`}
        >
          {remaining} / {total} remaining
        </span>
      </div>

      {/* Budget bar */}
      <div className="h-3 bg-gray-200 rounded-full overflow-hidden">
        <div
          className={`h-full rounded-full transition-all duration-500 ${
            isHealthy
              ? "bg-green-500"
              : isCritical
                ? "bg-red-500"
                : "bg-yellow-500"
          }`}
          style={{ width: `${Math.min(100, consumedPercent)}%` }}
        />
      </div>

      {/* Burn rate indicator */}
      <div className="flex items-center justify-between text-xs text-gray-500">
        <span>Burn Rate: {burnRate.toFixed(2)}x</span>
        {burnRate > 1 && (
          <span className="flex items-center gap-1 text-red-600">
            <TrendingUp className="h-3 w-3" />
            Consuming too fast
          </span>
        )}
        {burnRate <= 1 && burnRate > 0 && (
          <span className="flex items-center gap-1 text-green-600">
            <TrendingDown className="h-3 w-3" />
            Sustainable pace
          </span>
        )}
      </div>
    </div>
  );
}

// Latency Stats
function LatencyStats({
  p50,
  p95,
  p99,
  target,
}: {
  p50: number;
  p95: number;
  p99: number;
  target: number;
}) {
  const p95Met = p95 <= target;

  return (
    <div className="grid grid-cols-3 gap-4">
      <div className="text-center p-3 bg-gray-50 rounded-lg">
        <div className="text-xs text-gray-500 mb-1">p50</div>
        <div className="text-lg font-semibold text-gray-900">{p50}ms</div>
      </div>
      <div
        className={`text-center p-3 rounded-lg ${
          p95Met ? "bg-green-50" : "bg-red-50"
        }`}
      >
        <div className="text-xs text-gray-500 mb-1">p95</div>
        <div
          className={`text-lg font-semibold ${
            p95Met ? "text-green-700" : "text-red-700"
          }`}
        >
          {p95}ms
        </div>
        <div className="text-xs text-gray-400">target: {target}ms</div>
      </div>
      <div className="text-center p-3 bg-gray-50 rounded-lg">
        <div className="text-xs text-gray-500 mb-1">p99</div>
        <div className="text-lg font-semibold text-gray-900">{p99}ms</div>
      </div>
    </div>
  );
}

// Queue Depth Indicator
function QueueDepthIndicator({
  current,
  max,
  pending,
  failed,
  dlq,
}: {
  current: number;
  max: number;
  pending: number;
  failed: number;
  dlq: number;
}) {
  const utilizationPercent = max > 0 ? (current / max) * 100 : 0;
  const isHealthy = utilizationPercent < 50;
  const isCritical = utilizationPercent > 80;

  return (
    <div className="space-y-3">
      {/* Main gauge */}
      <div className="flex items-center gap-4">
        <Layers
          className={`h-6 w-6 ${
            isHealthy
              ? "text-green-500"
              : isCritical
                ? "text-red-500"
                : "text-yellow-500"
          }`}
        />
        <div className="flex-1">
          <div className="flex items-center justify-between mb-1">
            <span className="text-sm text-gray-600">Queue Depth</span>
            <span className="text-sm font-medium">
              {current} / {max}
            </span>
          </div>
          <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
            <div
              className={`h-full rounded-full transition-all ${
                isHealthy
                  ? "bg-green-500"
                  : isCritical
                    ? "bg-red-500"
                    : "bg-yellow-500"
              }`}
              style={{ width: `${Math.min(100, utilizationPercent)}%` }}
            />
          </div>
        </div>
      </div>

      {/* Breakdown */}
      <div className="grid grid-cols-3 gap-2 text-center">
        <div className="p-2 bg-blue-50 rounded">
          <div className="text-lg font-semibold text-blue-700">{pending}</div>
          <div className="text-xs text-blue-600">Pending</div>
        </div>
        <div className="p-2 bg-yellow-50 rounded">
          <div className="text-lg font-semibold text-yellow-700">{failed}</div>
          <div className="text-xs text-yellow-600">Failed</div>
        </div>
        <div className={`p-2 rounded ${dlq > 0 ? "bg-red-50" : "bg-gray-50"}`}>
          <div
            className={`text-lg font-semibold ${dlq > 0 ? "text-red-700" : "text-gray-700"}`}
          >
            {dlq}
          </div>
          <div
            className={`text-xs ${dlq > 0 ? "text-red-600" : "text-gray-600"}`}
          >
            DLQ
          </div>
        </div>
      </div>
    </div>
  );
}

// Loading skeleton
function LoadingSkeleton() {
  return (
    <div className="animate-pulse space-y-6">
      <div className="flex items-center justify-between">
        <div className="h-6 w-48 bg-gray-200 rounded" />
        <div className="h-8 w-32 bg-gray-200 rounded" />
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div className="h-32 bg-gray-200 rounded-lg" />
        <div className="h-32 bg-gray-200 rounded-lg" />
      </div>
      <div className="h-24 bg-gray-200 rounded-lg" />
      <div className="h-24 bg-gray-200 rounded-lg" />
    </div>
  );
}

export function SLODashboard() {
  const [data, setData] = useState<SLOResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [period, setPeriod] = useState<TimePeriod>("24h");

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch(
        `/api/staff/analytics/slo-metrics?period=${period}`,
        {
          credentials: "include",
        },
      );

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

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

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  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">
          <AlertTriangle 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 { metrics } = data;
  const overallHealthy =
    metrics.uptime.current >= metrics.uptime.target &&
    metrics.errorBudget.burnRate <= 1;

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div
            className={`p-2 rounded-lg ${
              overallHealthy ? "bg-green-100" : "bg-red-100"
            }`}
          >
            {overallHealthy ? (
              <CheckCircle className="h-5 w-5 text-green-600" />
            ) : (
              <AlertTriangle className="h-5 w-5 text-red-600" />
            )}
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              SLO Dashboard
            </h3>
            <p className="text-sm text-gray-500">
              {overallHealthy ? "All SLOs on target" : "SLO breaches detected"}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <select
            value={period}
            onChange={(e) => setPeriod(e.target.value as TimePeriod)}
            className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500"
          >
            <option value="1h">Last 1 hour</option>
            <option value="24h">Last 24 hours</option>
            <option value="7d">Last 7 days</option>
            <option value="30d">Last 30 days</option>
          </select>
          <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>
      </div>

      {/* Primary SLO Gauges */}
      <div className="grid grid-cols-2 gap-6 mb-6">
        <div className="flex flex-col items-center p-4 bg-gray-50 rounded-xl">
          <SLOGauge
            current={metrics.uptime.current}
            target={metrics.uptime.target}
            label="Uptime"
          />
          <div className="mt-2 text-xs text-gray-500 text-center">
            {metrics.uptime.successfulRequests.toLocaleString()} /{" "}
            {metrics.uptime.totalRequests.toLocaleString()} requests
          </div>
        </div>

        <div className="flex flex-col items-center p-4 bg-gray-50 rounded-xl">
          <SLOGauge
            current={metrics.messageFailureRate.current}
            target={metrics.messageFailureRate.target}
            label="Messages"
          />
          <div className="mt-2 text-xs text-gray-500 text-center">
            {metrics.messageFailureRate.sent -
              metrics.messageFailureRate.failed}{" "}
            / {metrics.messageFailureRate.sent} delivered
          </div>
        </div>
      </div>

      {/* Error Budget */}
      <div className="mb-6 p-4 bg-gray-50 rounded-xl">
        <div className="flex items-center gap-2 mb-3">
          <Gauge className="h-4 w-4 text-gray-500" />
          <span className="text-sm font-medium text-gray-700">
            Error Budget ({metrics.errorBudget.periodDays} day window)
          </span>
        </div>
        <ErrorBudgetBar
          total={metrics.errorBudget.total}
          consumed={metrics.errorBudget.consumed}
          remaining={metrics.errorBudget.remaining}
          burnRate={metrics.errorBudget.burnRate}
        />
      </div>

      {/* Webhook Latency */}
      <div className="mb-6">
        <div className="flex items-center gap-2 mb-3">
          <Clock className="h-4 w-4 text-gray-500" />
          <span className="text-sm font-medium text-gray-700">
            Webhook Latency
          </span>
          <span className="text-xs text-gray-400">
            ({metrics.webhookLatency.samples} samples)
          </span>
        </div>
        <LatencyStats
          p50={metrics.webhookLatency.p50}
          p95={metrics.webhookLatency.p95}
          p99={metrics.webhookLatency.p99}
          target={metrics.webhookLatency.target}
        />
      </div>

      {/* Queue Depth */}
      <div className="p-4 bg-gray-50 rounded-xl">
        <QueueDepthIndicator
          current={metrics.queueDepth.current}
          max={metrics.queueDepth.max}
          pending={metrics.queueDepth.pending}
          failed={metrics.queueDepth.failed}
          dlq={metrics.queueDepth.dlq}
        />
      </div>

      {/* System Health Summary */}
      <div className="mt-6 pt-4 border-t border-gray-100">
        <div className="flex items-center gap-2 mb-2">
          <Activity className="h-4 w-4 text-gray-500" />
          <span className="text-sm font-medium text-gray-700">
            System Components
          </span>
        </div>
        <div className="flex flex-wrap gap-2">
          {metrics.systemHealth.components.map((component) => (
            <span
              key={component.name}
              className={`inline-flex items-center gap-1 px-2 py-1 text-xs rounded-full ${
                component.status === "operational"
                  ? "bg-green-100 text-green-700"
                  : component.status === "degraded"
                    ? "bg-yellow-100 text-yellow-700"
                    : "bg-red-100 text-red-700"
              }`}
            >
              <span
                className={`h-1.5 w-1.5 rounded-full ${
                  component.status === "operational"
                    ? "bg-green-500"
                    : component.status === "degraded"
                      ? "bg-yellow-500"
                      : "bg-red-500"
                }`}
              />
              {component.name}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

export default SLODashboard;
