"use client";

import { useEffect, useState, useMemo } from "react";
import {
  Search,
  ArrowUpDown,
  Wallet,
  TrendingUp,
  Activity,
  Clock,
  Play,
  Pause,
  AlertCircle,
  XCircle,
} from "lucide-react";

import { getAgents } from "@/api/agents";
import type { AgentStatus } from "@/types/models";
import { cn } from "@/lib/utils";

type AgentFilter = "all" | "active" | "resting" | "danger" | "bankrupt";
type SortField = "name" | "balance" | "winRate" | "tradesCount" | "lastUpdated";
type SortOrder = "asc" | "desc";

interface ExtendedAgentStatus extends AgentStatus {
  balance?: number;
  winRate?: number;
  recentActivity?: string;
}

export default function Agents() {
  const [agents, setAgents] = useState<ExtendedAgentStatus[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Filters
  const [filter, setFilter] = useState<AgentFilter>("all");
  const [searchQuery, setSearchQuery] = useState("");

  // Sort
  const [sortField, setSortField] = useState<SortField>("lastUpdated");
  const [sortOrder, setSortOrder] = useState<SortOrder>("desc");

  useEffect(() => {
    async function fetchAgents() {
      try {
        setLoading(true);
        const data = await getAgents();
        const extendedData: ExtendedAgentStatus[] = data.map((agent) => ({
          ...agent,
          balance: 0,
          winRate: 0,
          recentActivity: agent.lastUpdated,
        }));
        setAgents(extendedData);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to fetch agents");
      } finally {
        setLoading(false);
      }
    }

    fetchAgents();
  }, []);

  const filteredAgents = useMemo(() => {
    let result = [...agents];

    if (filter !== "all") {
      result = result.filter((agent) => {
        switch (filter) {
          case "active":
            return agent.status === "running";
          case "resting":
            return agent.status === "paused" || agent.status === "stopped";
          case "danger":
            return agent.profitLossPercent < -10;
          case "bankrupt":
            return (agent.balance ?? 0) < 100;
          default:
            return true;
        }
      });
    }

    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      result = result.filter(
        (agent) =>
          agent.name.toLowerCase().includes(query) ||
          agent.id.toLowerCase().includes(query) ||
          agent.symbol.toLowerCase().includes(query),
      );
    }

    result.sort((a, b) => {
      let comparison = 0;
      switch (sortField) {
        case "name":
          comparison = a.name.localeCompare(b.name);
          break;
        case "balance":
          comparison = (a.balance ?? 0) - (b.balance ?? 0);
          break;
        case "winRate":
          comparison = (a.winRate ?? 0) - (b.winRate ?? 0);
          break;
        case "tradesCount":
          comparison = a.tradesCount - b.tradesCount;
          break;
        case "lastUpdated":
          comparison =
            new Date(a.lastUpdated).getTime() -
            new Date(b.lastUpdated).getTime();
          break;
      }
      return sortOrder === "asc" ? comparison : -comparison;
    });

    return result;
  }, [agents, filter, searchQuery, sortField, sortOrder]);

  const getStatusConfig = (status: AgentStatus["status"]) => {
    switch (status) {
      case "running":
        return {
          icon: Play,
          color: "text-[#00ffcc]",
          bgColor: "bg-[#00ffcc]/10",
          borderColor: "border-[#00ffcc]/20",
          label: "Active",
        };
      case "paused":
        return {
          icon: Pause,
          color: "text-[#ffb74d]",
          bgColor: "bg-[#ffb74d]/10",
          borderColor: "border-[#ffb74d]/20",
          label: "Resting",
        };
      case "stopped":
        return {
          icon: XCircle,
          color: "text-[#a0a0a0]",
          bgColor: "bg-[#a0a0a0]/10",
          borderColor: "border-[#a0a0a0]/20",
          label: "Stopped",
        };
      case "error":
        return {
          icon: AlertCircle,
          color: "text-[#ff5252]",
          bgColor: "bg-[#ff5252]/10",
          borderColor: "border-[#ff5252]/20",
          label: "Error",
        };
      default:
        return {
          icon: Activity,
          color: "text-[#a0a0a0]",
          bgColor: "bg-[#a0a0a0]/10",
          borderColor: "border-[#a0a0a0]/20",
          label: "Unknown",
        };
    }
  };

  const getAvatarColor = (id: string | undefined) => {
    const colors = [
      "bg-blue-600",
      "bg-purple-600",
      "bg-pink-600",
      "bg-indigo-600",
      "bg-cyan-600",
      "bg-emerald-600",
      "bg-orange-600",
      "bg-rose-600",
    ];
    if (!id) return colors[0];
    let hash = 0;
    for (let i = 0; i < id.length; i++) {
      hash = id.charCodeAt(i) + ((hash << 5) - hash);
    }
    return colors[Math.abs(hash) % colors.length];
  };

  const formatTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return "Just now";
    if (diffMins < 60) return `${diffMins}m ago`;
    if (diffHours < 24) return `${diffHours}h ago`;
    return `${diffDays}d ago`;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-[#a0a0a0] animate-pulse">
          Scanning agent network...
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-[#ff5252] font-bold">Error: {error}</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Filters and Search Bar */}
      <div className="bg-[#1e1e1e] rounded-xl border border-[#2c2c2c] p-4 shadow-xl">
        <div className="flex flex-col lg:flex-row gap-4 items-start lg:items-center justify-between">
          {/* Filter Tabs */}
          <div className="flex flex-wrap gap-2">
            {(
              [
                { key: "all", label: "全部代理" },
                { key: "active", label: "活跃" },
                { key: "resting", label: "休眠" },
                { key: "danger", label: "危险" },
                { key: "bankrupt", label: "破产" },
              ] as { key: AgentFilter; label: string }[]
            ).map(({ key, label }) => (
              <button
                key={key}
                onClick={() => setFilter(key)}
                className={cn(
                  "px-4 py-2 rounded-lg text-xs font-bold uppercase tracking-wider transition-all duration-200",
                  filter === key
                    ? "bg-[#00ffcc] text-[#121212]"
                    : "bg-[#121212] text-[#a0a0a0] border border-[#2c2c2c] hover:bg-[#2c2c2c] hover:text-[#e1e1e1]",
                )}
              >
                {label}
              </button>
            ))}
          </div>

          {/* Search and Sort */}
          <div className="flex items-center gap-3 w-full lg:w-auto">
            {/* Search */}
            <div className="relative flex-1 lg:flex-none">
              <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-[#666666]" />
              <input
                type="text"
                placeholder="Search agents..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="bg-[#121212] border border-[#2c2c2c] rounded-lg pl-9 pr-3 py-2 text-sm text-[#e1e1e1] placeholder-[#666666] w-full lg:w-48 focus:outline-none focus:border-[#00ffcc]"
              />
            </div>

            {/* Sort Dropdown */}
            <div className="relative">
              <select
                value={`${sortField}-${sortOrder}`}
                onChange={(e) => {
                  const [field, order] = e.target.value.split("-") as [
                    SortField,
                    SortOrder,
                  ];
                  setSortField(field);
                  setSortOrder(order);
                }}
                className="bg-[#121212] border border-[#2c2c2c] rounded-lg pl-3 pr-8 py-2 text-sm text-[#e1e1e1] appearance-none cursor-pointer focus:outline-none focus:border-[#00ffcc] font-medium"
              >
                <option value="lastUpdated-desc">Latest Activity</option>
                <option value="lastUpdated-asc">Oldest Activity</option>
                <option value="name-asc">Name A-Z</option>
                <option value="name-desc">Name Z-A</option>
                <option value="balance-desc">Balance High-Low</option>
                <option value="balance-asc">Balance Low-High</option>
                <option value="winRate-desc">Win Rate High-Low</option>
                <option value="tradesCount-desc">Trades High-Low</option>
              </select>
              <ArrowUpDown className="w-4 h-4 absolute right-2 top-1/2 -translate-y-1/2 text-[#666666] pointer-events-none" />
            </div>
          </div>
        </div>
      </div>

      {/* Agent Cards Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        {filteredAgents.length === 0 ? (
          <div className="col-span-full py-20 text-center bg-[#1e1e1e] border border-dashed border-[#2c2c2c] rounded-xl">
            <div className="text-[#666666] font-bold uppercase tracking-widest">
              No matching agents found
            </div>
          </div>
        ) : (
          filteredAgents.map((agent) => {
            const statusConfig = getStatusConfig(agent.status);
            const StatusIcon = statusConfig.icon;
            const avatarColor = getAvatarColor(agent.id);
            const isProfitable = agent.profitLoss >= 0;

            return (
              <div
                key={agent.id}
                className="bg-[#1e1e1e] rounded-xl border border-[#2c2c2c] p-4 hover:border-[#00ffcc]/30 transition-all duration-300 group shadow-lg"
              >
                {/* Header: Avatar and Status */}
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center gap-3">
                    {/* Avatar */}
                    <div
                      className={cn(
                        "w-12 h-12 rounded-xl flex items-center justify-center text-[#e1e1e1] font-black text-xl shadow-inner transition-transform group-hover:scale-110",
                        avatarColor,
                      )}
                    >
                      {agent.name.charAt(0).toUpperCase()}
                    </div>
                    <div>
                      <h3 className="text-sm font-black text-[#e1e1e1] tracking-tight group-hover:text-[#00ffcc] transition-colors">
                        {agent.name}
                      </h3>
                      <p className="text-[10px] text-[#666666] font-mono uppercase">
                        {agent.id.slice(0, 12)}
                      </p>
                    </div>
                  </div>
                  <span
                    className={cn(
                      "inline-flex items-center gap-1 px-2.5 py-1 rounded-md text-[10px] font-black uppercase tracking-wider border",
                      statusConfig.bgColor,
                      statusConfig.color,
                      statusConfig.borderColor,
                    )}
                  >
                    <StatusIcon className="w-3 h-3" />
                    {statusConfig.label}
                  </span>
                </div>

                {/* Stats Grid */}
                <div className="space-y-3 mb-4">
                  {/* Row 1: Balance & Win Rate */}
                  <div className="flex items-center justify-between py-2 border-b border-[#2c2c2c]">
                    <div className="flex items-center gap-2">
                      <Wallet className="w-3.5 h-3.5 text-[#666666]" />
                      <span className="text-[10px] font-bold uppercase tracking-tighter text-[#666666]">
                        Balance
                      </span>
                    </div>
                    <p className="text-sm font-black text-[#e1e1e1]">
                      ${agent.balance?.toFixed(2) ?? "0.00"}
                    </p>
                  </div>

                  <div className="flex items-center justify-between py-2 border-b border-[#2c2c2c]">
                    <div className="flex items-center gap-2">
                      <TrendingUp className="w-3.5 h-3.5 text-[#666666]" />
                      <span className="text-[10px] font-bold uppercase tracking-tighter text-[#666666]">
                        Win Rate
                      </span>
                    </div>
                    <p className="text-sm font-black text-[#e1e1e1]">
                      {agent.winRate?.toFixed(1) ?? "0.0"}%
                    </p>
                  </div>

                  {/* Row 3: P&L */}
                  <div className="flex items-center justify-between py-2 border-b border-[#2c2c2c]">
                    <div className="flex items-center gap-2">
                      <Activity className="w-3.5 h-3.5 text-[#666666]" />
                      <span className="text-[10px] font-bold uppercase tracking-tighter text-[#666666]">
                        P&L
                      </span>
                    </div>
                    <p
                      className={cn(
                        "text-sm font-black",
                        isProfitable ? "text-[#00ffcc]" : "text-[#ff5252]",
                      )}
                    >
                      {isProfitable ? "+" : ""}
                      {agent.profitLoss?.toFixed(2) ?? "0.00"}
                    </p>
                  </div>

                  {/* Row 4: Trades */}
                  <div className="flex items-center justify-between py-2">
                    <div className="flex items-center gap-2">
                      <Clock className="w-3.5 h-3.5 text-[#666666]" />
                      <span className="text-[10px] font-bold uppercase tracking-tighter text-[#666666]">
                        Trades
                      </span>
                    </div>
                    <p className="text-sm font-black text-[#e1e1e1]">
                      {agent.tradesCount}
                    </p>
                  </div>
                </div>

                {/* Footer: Symbol and Activity */}
                <div className="flex items-center justify-between pt-3 border-t border-[#2c2c2c]">
                  <span className="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-black uppercase tracking-widest bg-[#00ffcc]/10 text-[#00ffcc]">
                    {agent.symbol}
                  </span>
                  <span className="text-[10px] text-[#666666] font-bold uppercase">
                    {formatTimeAgo(agent.recentActivity ?? agent.lastUpdated)}
                  </span>
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* Results Count */}
      <div className="text-center text-[10px] text-[#666666] font-black uppercase tracking-widest pt-4">
        Showing {filteredAgents.length} of {agents.length} specialized agents
      </div>
    </div>
  );
}
