"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import {
  Search,
  Filter,
  Clock,
  CheckCircle,
  XCircle,
  Activity,
  GitBranch,
  Layers,
  ChevronLeft,
  ChevronRight,
  ArrowRight,
  ChevronDown,
  ChevronUp,
  RefreshCw,
  ToggleLeft,
  ToggleRight,
  WifiOff,
} from "lucide-react";
import { cn, formatDuration, formatRelativeTime } from "@/lib/utils";

type TraceStatus = "RUNNING" | "COMPLETED" | "ERROR";

interface Trace {
  id: string;
  name: string;
  status: TraceStatus;
  startedAt: string;
  endedAt: string | null;
  durationMs: number | null;
  tags: string[];
  metadata: Record<string, unknown>;
  _count: {
    decisionPoints: number;
    spans: number;
    events: number;
  };
}

interface TraceListProps {
  initialTraces: Trace[];
  initialTotal: number;
  initialTotalPages: number;
  initialPage: number;
}

type FilterStatus = "ALL" | TraceStatus;
type SortOption = "newest" | "oldest" | "longest" | "shortest" | "costliest";

const statusConfig: Record<TraceStatus, { label: string; icon: React.ComponentType<{ className?: string }>; color: string; bgColor: string }> = {
  RUNNING: {
    label: "Running",
    icon: Activity,
    color: "text-amber-400",
    bgColor: "bg-amber-500/10 border-amber-500/20",
  },
  COMPLETED: {
    label: "Completed",
    icon: CheckCircle,
    color: "text-emerald-400",
    bgColor: "bg-emerald-500/10 border-emerald-500/20",
  },
  ERROR: {
    label: "Error",
    icon: XCircle,
    color: "text-red-400",
    bgColor: "bg-red-500/10 border-red-500/20",
  },
};

const sortOptions: { value: SortOption; label: string }[] = [
  { value: "newest", label: "Newest" },
  { value: "oldest", label: "Oldest" },
  { value: "longest", label: "Longest duration" },
  { value: "shortest", label: "Shortest duration" },
  { value: "costliest", label: "Highest cost" },
];

export function TraceList({
  initialTraces,
  initialTotal,
  initialTotalPages,
  initialPage,
}: TraceListProps) {
  const searchParams = useSearchParams();
  const [traces, setTraces] = useState<Trace[]>(initialTraces);
  const [total, setTotal] = useState(initialTotal);
  const [totalPages, setTotalPages] = useState(initialTotalPages);
  const [currentPage, setCurrentPage] = useState(initialPage);
  const [isLoading, setIsLoading] = useState(false);

  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<FilterStatus>("ALL");
  const [sortFilter, setSortFilter] = useState<SortOption>("newest");
  const [tagsFilter, setTagsFilter] = useState("");
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");

  const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);
  const [autoRefresh, setAutoRefresh] = useState(false);
  const [sseConnected, setSseConnected] = useState(false);
  const [newTracesCount, setNewTracesCount] = useState(0);

  const updateUrlParams = useCallback(() => {
    const params = new URLSearchParams(searchParams.toString());

    if (statusFilter !== "ALL") {
      params.set("status", statusFilter);
    } else {
      params.delete("status");
    }

    if (searchQuery) {
      params.set("search", searchQuery);
    } else {
      params.delete("search");
    }

    if (sortFilter !== "newest") {
      params.set("sort", sortFilter);
    } else {
      params.delete("sort");
    }

    if (tagsFilter) {
      params.set("tags", tagsFilter);
    } else {
      params.delete("tags");
    }

    if (dateFrom) {
      params.set("dateFrom", dateFrom);
    } else {
      params.delete("dateFrom");
    }

    if (dateTo) {
      params.set("dateTo", dateTo);
    } else {
      params.delete("dateTo");
    }

    params.set("page", currentPage.toString());

    const newUrl = `${window.location.pathname}?${params.toString()}`;
    window.history.replaceState({}, "", newUrl);
  }, [searchParams, statusFilter, searchQuery, sortFilter, tagsFilter, dateFrom, dateTo, currentPage]);

  const fetchTraces = useCallback(async () => {
    setIsLoading(true);
    try {
      const params = new URLSearchParams();
      params.set("page", currentPage.toString());
      params.set("limit", "50");

      if (statusFilter !== "ALL") {
        params.set("status", statusFilter);
      }
      if (searchQuery) {
        params.set("search", searchQuery);
      }
      if (sortFilter !== "newest") {
        params.set("sort", sortFilter);
      }
      if (tagsFilter) {
        params.set("tags", tagsFilter);
      }
      if (dateFrom) {
        params.set("dateFrom", dateFrom);
      }
      if (dateTo) {
        params.set("dateTo", dateTo);
      }

      const res = await fetch(`/api/traces?${params.toString()}`, { cache: "no-store" });

      if (!res.ok) {
        throw new Error(`Failed to fetch traces: ${res.status}`);
      }

      const data = await res.json();
      setTraces(data.traces);
      setTotal(data.total);
      setTotalPages(data.totalPages);
      setNewTracesCount(0);
    } catch (error) {
      console.error("Error fetching traces:", error);
    } finally {
      setIsLoading(false);
    }
  }, [currentPage, statusFilter, searchQuery, sortFilter, tagsFilter, dateFrom, dateTo]);

  useEffect(() => {
    const status = searchParams.get("status") as FilterStatus | null;
    const search = searchParams.get("search") ?? "";
    const sort = (searchParams.get("sort") as SortOption | null) ?? "newest";
    const tags = searchParams.get("tags") ?? "";
    const from = searchParams.get("dateFrom") ?? "";
    const to = searchParams.get("dateTo") ?? "";
    const page = parseInt(searchParams.get("page") ?? "1", 10);

    setStatusFilter(status ?? "ALL");
    setSearchQuery(search);
    setSortFilter(sort);
    setTagsFilter(tags);
    setDateFrom(from);
    setDateTo(to);
    setCurrentPage(page);

    const savedAutoRefresh = localStorage.getItem("agentlens-auto-refresh");
    setAutoRefresh(savedAutoRefresh === "true");
  }, [searchParams]);

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

  useEffect(() => {
    fetchTraces();
  }, [currentPage, fetchTraces]);

  useEffect(() => {
    if (!autoRefresh) return;

    const interval = setInterval(() => {
      fetchTraces();
    }, 5000);

    return () => clearInterval(interval);
  }, [autoRefresh, fetchTraces]);

  useEffect(() => {
    localStorage.setItem("agentlens-auto-refresh", autoRefresh.toString());
  }, [autoRefresh]);

  useEffect(() => {
    const eventSource = new EventSource("/api/traces/stream");

    eventSource.onopen = () => {
      setSseConnected(true);
    };

    eventSource.onerror = () => {
      setSseConnected(false);
    };

    eventSource.addEventListener("trace-update", (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.type === "new") {
          setNewTracesCount((prev) => prev + 1);
        } else if (data.type === "updated") {
          setNewTracesCount((prev) => prev + 1);
        }
      } catch (error) {
        console.error("Error parsing SSE message:", error);
      }
    });

    eventSource.addEventListener("heartbeat", () => {
      setSseConnected(true);
    });

    return () => {
      eventSource.close();
      setSseConnected(false);
    };
  }, []);

  const filteredTraces = traces.filter((trace) => {
    const matchesSearch =
      trace.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      trace.tags.some((tag) =>
        tag.toLowerCase().includes(searchQuery.toLowerCase())
      );
    const matchesStatus =
      statusFilter === "ALL" || trace.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const filterChips: { value: FilterStatus; label: string }[] = [
    { value: "ALL", label: "All" },
    { value: "RUNNING", label: "Running" },
    { value: "COMPLETED", label: "Completed" },
    { value: "ERROR", label: "Error" },
  ];

  const handlePageChange = (newPage: number) => {
    setCurrentPage(newPage);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  if (traces.length === 0) {
    return <EmptyState />;
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div className="flex items-center gap-3">
          <div>
            <h1 className="text-2xl font-bold text-neutral-100">Traces</h1>
            <p className="text-neutral-400 mt-1">
              {total} trace{total !== 1 ? "s" : ""} captured
            </p>
          </div>
          <div
            className={cn(
              "flex items-center gap-1.5 text-xs font-medium",
              sseConnected ? "text-emerald-400" : "text-neutral-500"
            )}
          >
            {sseConnected ? (
              <>
                <div className="relative">
                  <div className="w-2 h-2 rounded-full bg-emerald-400" />
                  <div className="absolute inset-0 w-2 h-2 rounded-full bg-emerald-400 animate-ping" />
                </div>
                <span className="ml-1">Live</span>
              </>
            ) : (
              <>
                <WifiOff className="w-3.5 h-3.5" />
                <span className="ml-1">Offline</span>
              </>
            )}
          </div>
        </div>
        <button
          onClick={() => setAutoRefresh(!autoRefresh)}
          className={cn(
            "flex items-center gap-2 px-3 py-2 rounded-lg border text-sm font-medium transition-colors",
            autoRefresh
              ? "bg-emerald-500/10 border-emerald-500/30 text-emerald-400"
              : "bg-neutral-900 border-neutral-800 text-neutral-400 hover:border-neutral-700"
          )}
        >
          {autoRefresh ? (
            <>
              <ToggleRight className="w-4 h-4" />
              Auto-refresh ON
            </>
          ) : (
            <>
              <ToggleLeft className="w-4 h-4" />
              Auto-refresh OFF
            </>
          )}
        </button>
      </div>

      {/* New Traces Banner */}
      {newTracesCount > 0 && (
        <div className="flex items-center justify-between gap-4 px-4 py-3 bg-blue-500/10 border border-blue-500/20 text-blue-400 rounded-lg">
          <span className="text-sm font-medium">
            {newTracesCount} new trace{newTracesCount !== 1 ? "s" : ""} available
          </span>
          <button
            onClick={() => fetchTraces()}
            className="flex items-center gap-1.5 px-3 py-1.5 bg-blue-500/20 hover:bg-blue-500/30 text-blue-300 text-sm font-medium rounded-lg transition-colors"
          >
            <RefreshCw className={cn("w-3.5 h-3.5", isLoading && "animate-spin")} />
            Refresh
          </button>
        </div>
      )}

      {/* Search and Filter */}
      <div className="flex flex-col gap-4">
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-neutral-500" />
            <input
              type="text"
              placeholder="Search traces..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-3 bg-neutral-900 border border-neutral-800 rounded-lg text-neutral-100 placeholder-neutral-500 focus:outline-none focus:border-emerald-500/50 focus:ring-1 focus:ring-emerald-500/50 transition-all"
            />
          </div>
          <div className="flex items-center gap-2">
            <Filter className="w-5 h-5 text-neutral-500" />
            <div className="flex gap-2">
              {filterChips.map((chip) => (
                <button
                  key={chip.value}
                  onClick={() => setStatusFilter(chip.value)}
                  className={cn(
                    "px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200",
                    statusFilter === chip.value
                      ? "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30"
                      : "bg-neutral-900 text-neutral-400 border border-neutral-800 hover:border-neutral-700"
                  )}
                >
                  {chip.label}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Advanced Filters */}
        <div className="border-t border-neutral-800 pt-4">
          <button
            onClick={() => setShowAdvancedFilters(!showAdvancedFilters)}
            className="flex items-center gap-2 text-sm text-neutral-400 hover:text-neutral-300 transition-colors"
          >
            {showAdvancedFilters ? (
              <ChevronUp className="w-4 h-4" />
            ) : (
              <ChevronDown className="w-4 h-4" />
            )}
            Advanced Filters
          </button>

          {showAdvancedFilters && (
            <div className="mt-4 grid grid-cols-1 sm:grid-cols-3 gap-4">
              <div className="space-y-2">
                <label className="text-xs text-neutral-500 font-medium">Sort by</label>
                <select
                  value={sortFilter}
                  onChange={(e) => setSortFilter(e.target.value as SortOption)}
                  className="w-full bg-neutral-900 border border-neutral-700 rounded-lg px-3 py-2 text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 transition-all"
                >
                  {sortOptions.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>

              <div className="space-y-2">
                <label className="text-xs text-neutral-500 font-medium">Date from</label>
                <input
                  type="date"
                  value={dateFrom}
                  onChange={(e) => setDateFrom(e.target.value)}
                  className="w-full bg-neutral-900 border border-neutral-700 rounded-lg px-3 py-2 text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 transition-all"
                />
              </div>

              <div className="space-y-2">
                <label className="text-xs text-neutral-500 font-medium">Date to</label>
                <input
                  type="date"
                  value={dateTo}
                  onChange={(e) => setDateTo(e.target.value)}
                  className="w-full bg-neutral-900 border border-neutral-700 rounded-lg px-3 py-2 text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 transition-all"
                />
              </div>

              <div className="sm:col-span-3 space-y-2">
                <label className="text-xs text-neutral-500 font-medium">Tags (comma-separated)</label>
                <input
                  type="text"
                  placeholder="e.g., production, critical, api"
                  value={tagsFilter}
                  onChange={(e) => setTagsFilter(e.target.value)}
                  className="w-full bg-neutral-900 border border-neutral-700 rounded-lg px-3 py-2 text-sm text-neutral-100 placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 transition-all"
                />
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Trace List */}
      <div className="space-y-3">
        {filteredTraces.map((trace) => (
          <TraceCard key={trace.id} trace={trace} />
        ))}
      </div>

      {/* Empty Filtered State */}
      {filteredTraces.length === 0 && traces.length > 0 && (
        <div className="text-center py-12">
          <p className="text-neutral-400">
            No traces match your search criteria
          </p>
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between pt-6 border-t border-neutral-800">
          <p className="text-sm text-neutral-500">
            Page {currentPage} of {totalPages}
          </p>
          <div className="flex gap-2">
            <button
              disabled={currentPage <= 1}
              onClick={() => handlePageChange(Math.max(1, currentPage - 1))}
              className="p-2 rounded-lg border border-neutral-800 text-neutral-400 hover:text-neutral-100 hover:border-neutral-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              <ChevronLeft className="w-5 h-5" />
            </button>
            <button
              disabled={currentPage >= totalPages}
              onClick={() => handlePageChange(Math.min(totalPages, currentPage + 1))}
              className="p-2 rounded-lg border border-neutral-800 text-neutral-400 hover:text-neutral-100 hover:border-neutral-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              <ChevronRight className="w-5 h-5" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function TraceCard({ trace }: { trace: Trace }) {
  const status = statusConfig[trace.status];
  const StatusIcon = status.icon;

  return (
    <Link href={`/dashboard/traces/${trace.id}`}>
      <div className="group p-5 bg-neutral-900 border border-neutral-800 rounded-xl hover:border-emerald-500/30 hover:bg-neutral-800/50 transition-all duration-200 cursor-pointer">
        <div className="flex flex-col lg:flex-row lg:items-center gap-4">
          {/* Left: Name and Status */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-3 mb-2">
              <h3 className="font-semibold text-neutral-100 truncate group-hover:text-emerald-400 transition-colors">
                {trace.name}
              </h3>
              <div
                className={cn(
                  "flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-xs font-medium",
                  status.bgColor,
                  status.color
                )}
              >
                <StatusIcon className="w-3.5 h-3.5" />
                {status.label}
              </div>
            </div>
            <div className="flex items-center gap-4 text-sm text-neutral-500">
              <span className="flex items-center gap-1.5">
                <Clock className="w-4 h-4" />
                {formatRelativeTime(trace.startedAt)}
              </span>
              <span className="flex items-center gap-1.5">
                <Activity className="w-4 h-4" />
                {formatDuration(trace.durationMs)}
              </span>
            </div>
          </div>

          {/* Middle: Stats */}
          <div className="flex items-center gap-6">
            <div className="flex items-center gap-2">
              <div className="p-1.5 rounded-md bg-emerald-500/10">
                <GitBranch className="w-4 h-4 text-emerald-400" />
              </div>
              <div className="flex flex-col">
                <span className="text-xs text-neutral-500">Decisions</span>
                <span className="text-sm font-medium text-neutral-200">
                  {trace._count.decisionPoints}
                </span>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <div className="p-1.5 rounded-md bg-blue-500/10">
                <Layers className="w-4 h-4 text-blue-400" />
              </div>
              <div className="flex flex-col">
                <span className="text-xs text-neutral-500">Spans</span>
                <span className="text-sm font-medium text-neutral-200">
                  {trace._count.spans}
                </span>
              </div>
            </div>
          </div>

          {/* Right: Tags and Arrow */}
          <div className="flex items-center gap-4">
            {trace.tags.length > 0 && (
              <div className="flex items-center gap-1.5">
                {trace.tags.slice(0, 3).map((tag) => (
                  <span
                    key={tag}
                    className="px-2 py-1 rounded-md bg-neutral-800 text-neutral-400 text-xs"
                  >
                    {tag}
                  </span>
                ))}
                {trace.tags.length > 3 && (
                  <span className="px-2 py-1 rounded-md bg-neutral-800 text-neutral-500 text-xs">
                    +{trace.tags.length - 3}
                  </span>
                )}
              </div>
            )}
            <ArrowRight className="w-5 h-5 text-neutral-600 group-hover:text-emerald-400 group-hover:translate-x-1 transition-all" />
          </div>
        </div>
      </div>
    </Link>
  );
}

function EmptyState() {
  return (
    <div className="flex flex-col items-center justify-center py-20 text-center">
      <div className="w-20 h-20 rounded-2xl bg-neutral-900 border border-neutral-800 flex items-center justify-center mb-6">
        <Activity className="w-10 h-10 text-neutral-600" />
      </div>
      <h2 className="text-xl font-semibold text-neutral-100 mb-2">
        No traces yet
      </h2>
      <p className="text-neutral-400 max-w-md mb-8">
        Install the SDK to start capturing traces from your AI agents
      </p>

      <div className="w-full max-w-2xl">
        <div className="rounded-xl overflow-hidden border border-neutral-800 bg-neutral-900">
          <div className="px-4 py-3 border-b border-neutral-800 flex items-center gap-2">
            <div className="flex gap-2">
              <div className="w-3 h-3 rounded-full bg-neutral-700" />
              <div className="w-3 h-3 rounded-full bg-neutral-700" />
              <div className="w-3 h-3 rounded-full bg-neutral-700" />
            </div>
            <span className="ml-4 text-sm text-neutral-500">example.py</span>
          </div>
          <pre className="p-6 overflow-x-auto text-sm text-left">
            <code className="text-neutral-300">
              <span className="text-purple-400">from</span>{" "}
              <span className="text-neutral-300">agentlens</span>{" "}
              <span className="text-purple-400">import</span>{" "}
              <span className="text-emerald-300">init</span>
              <span className="text-neutral-300">,</span>{" "}
              <span className="text-emerald-300">trace</span>
              {"\n"}
              {"\n"}
              <span className="text-emerald-300">init</span>
              <span className="text-neutral-300">(</span>
              {"\n"}
              {"    "}
              <span className="text-orange-300">api_key</span>
              <span className="text-neutral-300">=</span>
              <span className="text-emerald-300">&quot;your-api-key&quot;</span>
              {"\n"}
              <span className="text-neutral-300">)</span>
              {"\n"}
              {"\n"}
              <span className="text-purple-400">@trace</span>
              {"\n"}
              <span className="text-purple-400">def</span>{" "}
              <span className="text-emerald-300">my_agent</span>
              <span className="text-neutral-300">():</span>
              {"\n"}
              {"    "}
              <span className="text-purple-400">return</span>{" "}
              <span className="text-emerald-300">
                &quot;Hello, AgentLens!&quot;
              </span>
            </code>
          </pre>
        </div>
      </div>

      <a
        href="https://agentlens.vectry.tech/docs"
        target="_blank"
        rel="noopener noreferrer"
        className="mt-8 inline-flex items-center gap-2 px-6 py-3 bg-emerald-500 hover:bg-emerald-400 text-neutral-950 font-semibold rounded-lg transition-colors"
      >
        View Documentation
        <ArrowRight className="w-4 h-4" />
      </a>
    </div>
  );
}
