"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Activity,
  AlertTriangle,
  BarChart3,
  Clock,
  RefreshCw,
  Server,
  Shield,
  Zap,
} from "lucide-react";

interface CounterEntry {
  labels: Record<string, string>;
  value: number;
}

interface ResponseTimeEntry {
  category: string;
  p50: number;
  p95: number;
  p99: number;
  count: number;
  avg: number;
}

interface MetricsData {
  metrics: {
    uptime: { startedAt: string; uptimeSeconds: number };
    activeRequests: number;
    requests: { total: CounterEntry[]; errorRate: number };
    responseTimes: ResponseTimeEntry[];
    errors: CounterEntry[];
    logLevels: CounterEntry[];
  };
  sampling: Record<string, { rate: number; description: string }>;
  environment: string;
  logLevel: string;
}

function formatUptime(seconds: number): string {
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  if (days > 0) return `${days}d ${hours}h ${mins}m`;
  if (hours > 0) return `${hours}h ${mins}m`;
  return `${mins}m`;
}

function formatNumber(n: number): string {
  if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
  if (n >= 1000) return `${(n / 1000).toFixed(1)}K`;
  return n.toString();
}

export default function LoggingDashboardClient() {
  const [data, setData] = useState<MetricsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [autoRefresh, setAutoRefresh] = useState(true);

  const fetchMetrics = useCallback(async () => {
    try {
      const res = await fetch("/api/staff/dashboard/metrics");
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      setData(json);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to fetch metrics");
    } finally {
      setLoading(false);
    }
  }, []);

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

  useEffect(() => {
    if (!autoRefresh) return;
    const interval = setInterval(fetchMetrics, 10000);
    return () => clearInterval(interval);
  }, [autoRefresh, fetchMetrics]);

  if (loading && !data) {
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {Array.from({ length: 8 }).map((_, i) => (
          <div
            key={i}
            className="bg-white rounded-xl border border-gray-200 p-6 animate-pulse"
          >
            <div className="h-4 bg-gray-200 rounded w-1/2 mb-3" />
            <div className="h-8 bg-gray-200 rounded w-1/3" />
          </div>
        ))}
      </div>
    );
  }

  if (error && !data) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-xl p-6 text-center">
        <AlertTriangle className="w-8 h-8 text-red-500 mx-auto mb-2" />
        <p className="text-red-700 font-medium">Failed to load metrics</p>
        <p className="text-red-500 text-sm mt-1">{error}</p>
        <button
          onClick={fetchMetrics}
          className="mt-3 px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition text-sm font-medium"
        >
          Retry
        </button>
      </div>
    );
  }

  if (!data) return null;

  const { metrics, sampling, environment, logLevel } = data;

  // Aggregate totals
  const totalRequests = metrics.requests.total.reduce(
    (sum, e) => sum + e.value,
    0,
  );
  const totalErrors = metrics.errors.reduce((sum, e) => sum + e.value, 0);
  const total5xx = metrics.errors
    .filter((e) => e.labels.status === "5xx")
    .reduce((sum, e) => sum + e.value, 0);

  // Group requests by category
  const requestsByCategory = new Map<string, number>();
  metrics.requests.total.forEach((e) => {
    const cat = e.labels.category || "unknown";
    requestsByCategory.set(cat, (requestsByCategory.get(cat) || 0) + e.value);
  });

  // Log level totals
  const logLevelMap = new Map<string, number>();
  metrics.logLevels.forEach((e) => {
    logLevelMap.set(e.labels.level, e.value);
  });

  return (
    <div className="space-y-6">
      {/* Header controls */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <span
            className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold ${
              environment === "production"
                ? "bg-red-100 text-red-700"
                : "bg-green-100 text-green-700"
            }`}
          >
            <span
              className={`w-2 h-2 rounded-full ${environment === "production" ? "bg-red-500" : "bg-green-500"}`}
            />
            {environment}
          </span>
          <span className="text-xs text-gray-500">
            Log level: <strong className="text-gray-700">{logLevel}</strong>
          </span>
        </div>
        <div className="flex items-center gap-2">
          <label className="flex items-center gap-2 text-sm text-gray-600 cursor-pointer">
            <input
              type="checkbox"
              checked={autoRefresh}
              onChange={(e) => setAutoRefresh(e.target.checked)}
              className="rounded border-gray-300 text-brand-green focus:ring-brand-green"
            />
            Auto-refresh (10s)
          </label>
          <button
            onClick={fetchMetrics}
            className="p-2 text-gray-500 hover:text-brand-green hover:bg-gray-100 rounded-lg transition"
            title="Refresh now"
          >
            <RefreshCw className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Top-level stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard
          icon={<Server className="w-5 h-5" />}
          label="Uptime"
          value={formatUptime(metrics.uptime.uptimeSeconds)}
          color="blue"
        />
        <StatCard
          icon={<Activity className="w-5 h-5" />}
          label="Total Requests"
          value={formatNumber(totalRequests)}
          color="green"
        />
        <StatCard
          icon={<AlertTriangle className="w-5 h-5" />}
          label="Error Rate"
          value={`${metrics.requests.errorRate}%`}
          color={
            metrics.requests.errorRate > 5
              ? "red"
              : metrics.requests.errorRate > 1
                ? "yellow"
                : "green"
          }
        />
        <StatCard
          icon={<Zap className="w-5 h-5" />}
          label="Active Requests"
          value={metrics.activeRequests.toString()}
          color="purple"
        />
      </div>

      {/* Response Times */}
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-100 flex items-center gap-2">
          <Clock className="w-5 h-5 text-gray-400" />
          <h2 className="text-lg font-semibold text-brand-ink">
            Response Times
          </h2>
        </div>
        {metrics.responseTimes.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-50 text-gray-600">
                  <th className="text-left px-6 py-3 font-medium">Category</th>
                  <th className="text-right px-6 py-3 font-medium">Requests</th>
                  <th className="text-right px-6 py-3 font-medium">Avg</th>
                  <th className="text-right px-6 py-3 font-medium">p50</th>
                  <th className="text-right px-6 py-3 font-medium">p95</th>
                  <th className="text-right px-6 py-3 font-medium">p99</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {metrics.responseTimes
                  .sort((a, b) => b.count - a.count)
                  .map((rt) => (
                    <tr
                      key={rt.category}
                      className="hover:bg-gray-50 transition-colors"
                    >
                      <td className="px-6 py-3 font-mono text-xs text-gray-700">
                        {rt.category}
                      </td>
                      <td className="px-6 py-3 text-right text-gray-600">
                        {formatNumber(rt.count)}
                      </td>
                      <td className="px-6 py-3 text-right font-mono">
                        {rt.avg}ms
                      </td>
                      <td className="px-6 py-3 text-right font-mono">
                        {rt.p50}ms
                      </td>
                      <td className="px-6 py-3 text-right font-mono">
                        <span
                          className={
                            rt.p95 > 1000
                              ? "text-red-600 font-semibold"
                              : rt.p95 > 500
                                ? "text-yellow-600"
                                : ""
                          }
                        >
                          {rt.p95}ms
                        </span>
                      </td>
                      <td className="px-6 py-3 text-right font-mono">
                        <span
                          className={
                            rt.p99 > 2000
                              ? "text-red-600 font-semibold"
                              : rt.p99 > 1000
                                ? "text-yellow-600"
                                : ""
                          }
                        >
                          {rt.p99}ms
                        </span>
                      </td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="p-8 text-center text-gray-500 text-sm">
            No request data yet. Metrics populate as requests are served.
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Request Distribution */}
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-gray-100 flex items-center gap-2">
            <BarChart3 className="w-5 h-5 text-gray-400" />
            <h2 className="text-lg font-semibold text-brand-ink">
              Requests by Category
            </h2>
          </div>
          <div className="p-6 space-y-3">
            {requestsByCategory.size > 0 ? (
              [...requestsByCategory.entries()]
                .sort(([, a], [, b]) => b - a)
                .map(([category, count]) => {
                  const percentage =
                    totalRequests > 0 ? (count / totalRequests) * 100 : 0;
                  return (
                    <div key={category}>
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-xs font-mono text-gray-600">
                          {category}
                        </span>
                        <span className="text-xs text-gray-500">
                          {formatNumber(count)} ({percentage.toFixed(1)}%)
                        </span>
                      </div>
                      <div className="w-full bg-gray-100 rounded-full h-2">
                        <div
                          className="bg-brand-green rounded-full h-2 transition-all"
                          style={{ width: `${Math.max(percentage, 1)}%` }}
                        />
                      </div>
                    </div>
                  );
                })
            ) : (
              <p className="text-gray-500 text-sm text-center py-4">
                No data yet
              </p>
            )}
          </div>
        </div>

        {/* Log Level Distribution */}
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-gray-100 flex items-center gap-2">
            <Shield className="w-5 h-5 text-gray-400" />
            <h2 className="text-lg font-semibold text-brand-ink">Log Levels</h2>
          </div>
          <div className="p-6 space-y-3">
            {[
              "fatal",
              "error",
              "security",
              "warn",
              "info",
              "debug",
              "trace",
            ].map((level) => {
              const count = logLevelMap.get(level) || 0;
              const totalLogs = [...logLevelMap.values()].reduce(
                (a, b) => a + b,
                0,
              );
              const percentage = totalLogs > 0 ? (count / totalLogs) * 100 : 0;
              const colors: Record<string, string> = {
                fatal: "bg-red-600",
                error: "bg-red-500",
                security: "bg-orange-500",
                warn: "bg-yellow-500",
                info: "bg-blue-500",
                debug: "bg-gray-400",
                trace: "bg-gray-300",
              };

              return (
                <div key={level}>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-mono text-gray-600 uppercase">
                      {level}
                    </span>
                    <span className="text-xs text-gray-500">
                      {formatNumber(count)}
                    </span>
                  </div>
                  <div className="w-full bg-gray-100 rounded-full h-2">
                    <div
                      className={`${colors[level] || "bg-gray-400"} rounded-full h-2 transition-all`}
                      style={{
                        width: `${Math.max(percentage, count > 0 ? 1 : 0)}%`,
                      }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Sampling Configuration */}
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-100">
          <h2 className="text-lg font-semibold text-brand-ink">
            Log Sampling Configuration
          </h2>
          <p className="text-xs text-gray-500 mt-1">
            Controls which log levels are shipped to external drains
            (Loki/generic)
          </p>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-gray-50 text-gray-600">
                <th className="text-left px-6 py-3 font-medium">Level</th>
                <th className="text-right px-6 py-3 font-medium">
                  Sample Rate
                </th>
                <th className="text-left px-6 py-3 font-medium">Description</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {Object.entries(sampling).map(([level, config]) => (
                <tr key={level} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-3">
                    <span
                      className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-bold uppercase ${
                        level === "error" || level === "fatal"
                          ? "bg-red-100 text-red-700"
                          : level === "security"
                            ? "bg-orange-100 text-orange-700"
                            : level === "warn"
                              ? "bg-yellow-100 text-yellow-700"
                              : level === "info"
                                ? "bg-blue-100 text-blue-700"
                                : "bg-gray-100 text-gray-600"
                      }`}
                    >
                      {level}
                    </span>
                  </td>
                  <td className="px-6 py-3 text-right font-mono text-gray-700">
                    {Math.round(config.rate * 100)}%
                  </td>
                  <td className="px-6 py-3 text-gray-500 text-xs">
                    {config.description}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Errors breakdown */}
      {totalErrors > 0 && (
        <div className="bg-white rounded-xl border border-red-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-red-100 bg-red-50 flex items-center gap-2">
            <AlertTriangle className="w-5 h-5 text-red-500" />
            <h2 className="text-lg font-semibold text-red-700">
              Errors ({formatNumber(totalErrors)})
            </h2>
            {total5xx > 0 && (
              <span className="ml-auto text-xs bg-red-200 text-red-800 px-2 py-0.5 rounded-full font-bold">
                {total5xx} server errors (5xx)
              </span>
            )}
          </div>
          <div className="p-6">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {metrics.errors.map((e, i) => (
                <div key={i} className="bg-red-50 rounded-lg p-3">
                  <div className="text-xs text-red-600 font-mono">
                    {e.labels.category} / {e.labels.status}
                  </div>
                  <div className="text-lg font-bold text-red-700 mt-1">
                    {formatNumber(e.value)}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function StatCard({
  icon,
  label,
  value,
  color,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  color: "blue" | "green" | "red" | "yellow" | "purple";
}) {
  const colorClasses = {
    blue: "bg-blue-50 text-blue-600 border-blue-200",
    green: "bg-green-50 text-green-600 border-green-200",
    red: "bg-red-50 text-red-600 border-red-200",
    yellow: "bg-yellow-50 text-yellow-600 border-yellow-200",
    purple: "bg-purple-50 text-purple-600 border-purple-200",
  };

  const iconColorClasses = {
    blue: "text-blue-500",
    green: "text-green-500",
    red: "text-red-500",
    yellow: "text-yellow-500",
    purple: "text-purple-500",
  };

  return (
    <div className={`rounded-xl border p-5 ${colorClasses[color]}`}>
      <div className="flex items-center gap-2 mb-2">
        <span className={iconColorClasses[color]}>{icon}</span>
        <span className="text-xs font-medium text-gray-600">{label}</span>
      </div>
      <div className="text-2xl font-bold">{value}</div>
    </div>
  );
}
