"use client";

import { useEffect, useState, useCallback } from "react";
import {
  RefreshCw,
  ExternalLink,
  Filter,
  Clock,
  CheckCircle2,
} from "lucide-react";
import type { ErrorEntry } from "@/lib/types/admin-panel";

type TimeWindow = "1h" | "6h" | "24h" | "7d";
type Severity = "low" | "medium" | "high" | "critical";

export function ErrorLogsClient() {
  const [errors, setErrors] = useState<ErrorEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [timeWindow, setTimeWindow] = useState<TimeWindow>("24h");
  const [severity, setSeverity] = useState<Severity | "">("");
  const [hasMore, setHasMore] = useState(false);
  const [offset, setOffset] = useState(0);
  const limit = 20;

  const fetchErrors = useCallback(
    async (reset = false) => {
      setLoading(true);
      try {
        const params = new URLSearchParams({
          timeWindow,
          limit: limit.toString(),
          offset: reset ? "0" : offset.toString(),
        });
        if (severity) params.set("severity", severity);

        const res = await fetch(`/api/staff/admin/errors?${params}`);
        if (res.ok) {
          const data = await res.json();
          if (reset) {
            setErrors(data.errors || []);
            setOffset(0);
          } else {
            setErrors((prev) => [...prev, ...(data.errors || [])]);
          }
          setHasMore(data.hasMore || false);
        }
      } catch (err) {
        console.error("Failed to fetch errors:", err);
      } finally {
        setLoading(false);
      }
    },
    [timeWindow, severity, offset],
  );

  useEffect(() => {
    fetchErrors(true);
  }, [fetchErrors]);

  const loadMore = () => {
    setOffset((prev) => prev + limit);
    fetchErrors(false);
  };

  const severityColors: Record<string, string> = {
    critical: "bg-red-100 text-red-800 border-red-200",
    high: "bg-orange-100 text-orange-800 border-orange-200",
    medium: "bg-yellow-100 text-yellow-800 border-yellow-200",
    low: "bg-blue-100 text-blue-800 border-blue-200",
  };

  return (
    <div className="space-y-6">
      {/* Filters */}
      <div className="bg-white border border-gray-200 rounded-lg p-4">
        <div className="flex flex-wrap items-center gap-4">
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-gray-400" />
            <select
              aria-label="Time window"
              value={timeWindow}
              onChange={(e) => setTimeWindow(e.target.value as TimeWindow)}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-primary"
            >
              <option value="1h">Last Hour</option>
              <option value="6h">Last 6 Hours</option>
              <option value="24h">Last 24 Hours</option>
              <option value="7d">Last 7 Days</option>
            </select>
          </div>

          <div className="flex items-center gap-2">
            <Filter className="w-4 h-4 text-gray-400" />
            <select
              aria-label="Filter by severity"
              value={severity}
              onChange={(e) => setSeverity(e.target.value as Severity | "")}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-primary"
            >
              <option value="">All Severities</option>
              <option value="critical">Critical</option>
              <option value="high">High</option>
              <option value="medium">Medium</option>
              <option value="low">Low</option>
            </select>
          </div>

          <button
            onClick={() => fetchErrors(true)}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 text-sm text-gray-600 hover:text-brand-primary hover:bg-gray-100 rounded-lg transition ml-auto"
          >
            <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
            Refresh
          </button>
        </div>
      </div>

      {/* Error List */}
      <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
        {errors.length === 0 && !loading ? (
          <div className="p-12 text-center">
            <CheckCircle2 className="w-12 h-12 text-green-500 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-gray-900">
              No Errors Found
            </h3>
            <p className="text-gray-500 mt-2">
              No errors in the selected time window. Great job!
            </p>
          </div>
        ) : (
          <div className="divide-y divide-gray-100">
            {errors.map((error) => (
              <div key={error.id} className="p-4 hover:bg-gray-50 transition">
                <div className="flex items-start justify-between gap-4">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span
                        className={`px-2 py-0.5 rounded text-xs font-medium border ${severityColors[error.severity] || "bg-gray-100"}`}
                      >
                        {error.severity}
                      </span>
                      {error.errorType && (
                        <span className="text-xs text-gray-500 font-mono">
                          {error.errorType}
                        </span>
                      )}
                    </div>
                    <p className="text-sm font-medium text-gray-900 line-clamp-2">
                      {error.errorMessage}
                    </p>
                    <div className="flex items-center gap-4 mt-2 text-xs text-gray-500">
                      <span>{error.route}</span>
                      {error.method && (
                        <span className="font-mono">{error.method}</span>
                      )}
                      {error.statusCode && <span>HTTP {error.statusCode}</span>}
                    </div>
                  </div>
                  <div className="flex flex-col items-end gap-2">
                    <span className="text-xs text-gray-500 whitespace-nowrap">
                      {new Date(error.timestamp).toLocaleString()}
                    </span>
                    {error.sentryUrl && (
                      <a
                        href={error.sentryUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-xs text-brand-primary hover:underline flex items-center gap-1"
                      >
                        Sentry <ExternalLink className="w-3 h-3" />
                      </a>
                    )}
                  </div>
                </div>
                {error.stackTrace && (
                  <div className="mt-3 p-2 bg-gray-900 rounded text-xs text-gray-300 font-mono overflow-x-auto">
                    {error.stackTrace}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {loading && errors.length === 0 && (
          <div className="p-12 text-center">
            <RefreshCw className="w-8 h-8 text-gray-400 animate-spin mx-auto" />
            <p className="text-gray-500 mt-4">Loading errors...</p>
          </div>
        )}

        {hasMore && (
          <div className="p-4 border-t border-gray-100">
            <button
              onClick={loadMore}
              disabled={loading}
              className="w-full py-2 text-sm text-brand-primary hover:bg-brand-primary/5 rounded-lg transition disabled:opacity-50"
            >
              {loading ? "Loading..." : "Load More"}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
