"use client";

import { useEffect, useState } from "react";
import {
  Plus,
  Building2,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Edit2,
  Trash2,
  TestTube,
  ExternalLink,
  Key,
  Server,
  X,
} from "lucide-react";

import {
  getExchanges,
  createExchange,
  updateExchange,
  deleteExchange,
  testExchangeConnection,
} from "@/api/exchanges";
import type { Exchange, ExchangeCreateRequest } from "@/types/models";
import { cn } from "@/lib/utils";

interface ExchangeFormData {
  name: string;
  type: "binance" | "okx" | "bybit" | "custom";
  apiKey: string;
  apiSecret: string;
  passphrase?: string;
  testnet: boolean;
}

const initialFormData: ExchangeFormData = {
  name: "",
  type: "binance",
  apiKey: "",
  apiSecret: "",
  passphrase: "",
  testnet: false,
};

export default function Exchanges() {
  const [exchanges, setExchanges] = useState<Exchange[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [editingExchange, setEditingExchange] = useState<Exchange | null>(null);
  const [selectedExchange, setSelectedExchange] = useState<Exchange | null>(
    null,
  );
  const [formData, setFormData] = useState<ExchangeFormData>(initialFormData);
  const [testingId, setTestingId] = useState<string | null>(null);
  const [testResult, setTestResult] = useState<{
    success: boolean;
    message: string;
  } | null>(null);
  const [submitting, setSubmitting] = useState(false);

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

  async function fetchExchanges() {
    try {
      setLoading(true);
      const data = await getExchanges();
      setExchanges(data);
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "Failed to fetch exchanges",
      );
    } finally {
      setLoading(false);
    }
  }

  const handleOpenModal = (exchange?: Exchange) => {
    if (exchange) {
      setEditingExchange(exchange);
      setFormData({
        name: exchange.name,
        type: exchange.type,
        apiKey: "",
        apiSecret: "",
        passphrase: exchange.passphrase || "",
        testnet: exchange.testnet,
      });
    } else {
      setEditingExchange(null);
      setFormData(initialFormData);
    }
    setIsModalOpen(true);
    setTestResult(null);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setEditingExchange(null);
    setFormData(initialFormData);
    setTestResult(null);
  };

  const handleOpenDetailModal = (exchange: Exchange) => {
    setSelectedExchange(exchange);
    setIsDetailModalOpen(true);
  };

  const handleCloseDetailModal = () => {
    setIsDetailModalOpen(false);
    setSelectedExchange(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      if (editingExchange) {
        await updateExchange(editingExchange.id, formData);
      } else {
        await createExchange(formData as ExchangeCreateRequest);
      }
      await fetchExchanges();
      handleCloseModal();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to save exchange");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("确认删除此交易所配置?")) return;
    try {
      await deleteExchange(id);
      await fetchExchanges();
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "Failed to delete exchange",
      );
    }
  };

  const handleTestConnection = async (id: string) => {
    setTestingId(id);
    setTestResult(null);
    try {
      const result = await testExchangeConnection(id);
      setTestResult(result);
    } catch (err) {
      setTestResult({
        success: false,
        message: err instanceof Error ? err.message : "连接测试失败",
      });
    } finally {
      setTestingId(null);
    }
  };

  const maskApiKey = (key: string) => {
    if (key.length <= 8) return "****";
    return `${key.slice(0, 4)}****${key.slice(-4)}`;
  };

  const getStatusIcon = (status: Exchange["status"]) => {
    switch (status) {
      case "connected":
        return <CheckCircle2 className="w-5 h-5 text-[#00ffcc]" />;
      case "error":
        return <AlertCircle className="w-5 h-5 text-[#ff5252]" />;
      default:
        return <XCircle className="w-5 h-5 text-[#a0a0a0]" />;
    }
  };

  const getStatusText = (status: Exchange["status"]) => {
    switch (status) {
      case "connected":
        return "已连接";
      case "error":
        return "错误";
      default:
        return "未连接";
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-[#a0a0a0] animate-pulse font-bold uppercase tracking-widest">
          查询交易所节点...
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-black text-[#e1e1e1] tracking-tight">
            交易所配置
          </h1>
          <p className="text-[#666666] text-xs font-bold uppercase tracking-wider mt-1">
            管理您的 API 网关和连接节点
          </p>
        </div>
        <button
          onClick={() => handleOpenModal()}
          className="bg-[#00ffcc] hover:bg-[#00e6b8] text-[#121212] px-4 py-2 rounded-lg text-xs font-black uppercase tracking-widest transition-all duration-200 shadow-[0_0_15px_rgba(0,255,204,0.3)]"
        >
          <Plus className="w-4 h-4 inline-block mr-2" />
          添加交易所
        </button>
      </div>

      {error && (
        <div className="bg-[#ff5252]/10 border border-[#ff5252]/20 rounded-xl p-4 text-[#ff5252] font-bold text-sm">
          <AlertCircle className="w-4 h-4 inline-block mr-2" />
          {error}
        </div>
      )}

      {/* Exchange Cards Grid */}
      {exchanges.length === 0 ? (
        <div className="bg-[#1e1e1e] border border-dashed border-[#2c2c2c] rounded-2xl p-16 text-center">
          <Building2 className="w-16 h-16 text-[#2c2c2c] mx-auto mb-6" />
          <h3 className="text-[#e1e1e1] text-lg font-black uppercase tracking-tight mb-2">
            无交易所节点
          </h3>
          <p className="text-[#666666] font-bold uppercase text-[10px] tracking-widest mb-6">
            初始化您的第一个 API 桥接以开始交易
          </p>
          <button
            onClick={() => handleOpenModal()}
            className="border border-[#2c2c2c] text-[#a0a0a0] hover:text-[#00ffcc] hover:border-[#00ffcc] px-6 py-3 rounded-xl text-xs font-black uppercase tracking-widest transition-all"
          >
            <Plus className="w-4 h-4 inline-block mr-2" />
            添加节点
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {exchanges.map((exchange) => (
            <div
              key={exchange.id}
              className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-2xl p-6 hover:border-[#00ffcc]/30 transition-all duration-300 group shadow-xl"
            >
              {/* Card Header */}
              <div className="flex items-start justify-between mb-6">
                <div className="flex items-center gap-4">
                  <div className="w-12 h-12 bg-[#121212] border border-[#2c2c2c] rounded-xl flex items-center justify-center group-hover:border-[#00ffcc]/50 transition-colors">
                    <Building2 className="w-6 h-6 text-[#00ffcc]" />
                  </div>
                  <div>
                    <h3 className="text-[#e1e1e1] font-black tracking-tight group-hover:text-[#00ffcc] transition-colors">
                      {exchange.name}
                    </h3>
                    <p className="text-[#666666] text-[10px] font-black uppercase tracking-widest">
                      {exchange.type}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-1">
                  {getStatusIcon(exchange.status)}
                </div>
              </div>

              {/* Card Body */}
              <div className="space-y-3 mb-6 bg-[#121212] p-4 rounded-xl border border-transparent group-hover:border-[#2c2c2c] transition-all">
                <div className="flex items-center gap-3 text-xs font-bold uppercase tracking-tight">
                  <Key className="w-3.5 h-3.5 text-[#666666]" />
                  <span className="text-[#666666] w-16">API 密钥:</span>
                  <span className="text-[#e1e1e1] font-mono tracking-tighter">
                    {maskApiKey(exchange.apiKey)}
                  </span>
                </div>
                <div className="flex items-center gap-3 text-xs font-bold uppercase tracking-tight">
                  <Server className="w-3.5 h-3.5 text-[#666666]" />
                  <span className="text-[#666666] w-16">状态:</span>
                  <span
                    className={cn(
                      "font-black tracking-widest",
                      exchange.status === "connected"
                        ? "text-[#00ffcc]"
                        : exchange.status === "error"
                          ? "text-[#ff5252]"
                          : "text-[#a0a0a0]",
                    )}
                  >
                    {getStatusText(exchange.status)}
                  </span>
                </div>
                {exchange.testnet && (
                  <div className="flex items-center gap-3 text-xs font-bold uppercase tracking-tight">
                    <TestTube className="w-3.5 h-3.5 text-[#ffb74d]" />
                    <span className="text-[#ffb74d] font-black">
                      测试网模式
                    </span>
                  </div>
                )}
              </div>

              {/* Card Actions */}
              <div className="flex items-center gap-2 pt-4 border-t border-[#2c2c2c]">
                <button
                  onClick={() => handleTestConnection(exchange.id)}
                  disabled={testingId === exchange.id}
                  className="flex-1 bg-[#121212] border border-[#2c2c2c] text-[#a0a0a0] hover:text-[#00ffcc] hover:border-[#00ffcc] py-2 rounded-lg text-[10px] font-black uppercase tracking-widest transition-all disabled:opacity-30"
                >
                  {testingId === exchange.id ? "测试中..." : "测试连接"}
                </button>
                <button
                  onClick={() => handleOpenDetailModal(exchange)}
                  className="p-2 bg-[#121212] border border-[#2c2c2c] text-[#a0a0a0] hover:text-[#e1e1e1] rounded-lg transition-all"
                >
                  <ExternalLink className="w-4 h-4" />
                </button>
                <button
                  onClick={() => handleOpenModal(exchange)}
                  className="p-2 bg-[#121212] border border-[#2c2c2c] text-[#a0a0a0] hover:text-[#00ffcc] rounded-lg transition-all"
                >
                  <Edit2 className="w-4 h-4" />
                </button>
                <button
                  onClick={() => handleDelete(exchange.id)}
                  className="p-2 bg-[#121212] border border-[#2c2c2c] text-[#666666] hover:text-[#ff5252] hover:border-[#ff5252]/30 rounded-lg transition-all"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>

              {/* Test Result */}
              {testResult && testingId === null && (
                <div
                  className={cn(
                    "mt-3 p-3 rounded-lg text-[10px] font-black uppercase tracking-widest border",
                    testResult.success
                      ? "bg-[#00ffcc]/5 text-[#00ffcc] border-[#00ffcc]/20"
                      : "bg-[#ff5252]/5 text-[#ff5252] border-[#ff5252]/20",
                  )}
                >
                  {testResult.message}
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Add/Edit Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-2xl p-8 w-full max-w-md shadow-2xl animate-in zoom-in-95 duration-200">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-xl font-black text-[#e1e1e1] tracking-tight uppercase">
                {editingExchange ? "编辑节点" : "添加节点"}
              </h2>
              <button
                onClick={handleCloseModal}
                className="text-[#666666] hover:text-[#e1e1e1]"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="block text-[#666666] text-[10px] font-black uppercase tracking-widest mb-2">
                  显示名称
                </label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) =>
                    setFormData({ ...formData, name: e.target.value })
                  }
                  className="w-full bg-[#121212] border border-[#2c2c2c] rounded-xl px-4 py-3 text-[#e1e1e1] font-bold focus:border-[#00ffcc] focus:outline-none transition-all"
                  placeholder="例如: 主 Binance"
                  required
                />
              </div>

              <div>
                <label className="block text-[#666666] text-[10px] font-black uppercase tracking-widest mb-2">
                  提供商类型
                </label>
                <select
                  value={formData.type}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      type: e.target.value as Exchange["type"],
                    })
                  }
                  className="w-full bg-[#121212] border border-[#2c2c2c] rounded-xl px-4 py-3 text-[#e1e1e1] font-bold focus:border-[#00ffcc] focus:outline-none transition-all appearance-none cursor-pointer"
                  required
                >
                  <option value="binance">Binance</option>
                  <option value="okx">OKX</option>
                  <option value="bybit">Bybit</option>
                  <option value="custom">自定义引擎</option>
                </select>
              </div>

              <div>
                <label className="block text-[#666666] text-[10px] font-black uppercase tracking-widest mb-2">
                  API 密钥 {editingExchange && "(已锁定)"}
                </label>
                <input
                  type="password"
                  value={formData.apiKey}
                  onChange={(e) =>
                    setFormData({ ...formData, apiKey: e.target.value })
                  }
                  className="w-full bg-[#121212] border border-[#2c2c2c] rounded-xl px-4 py-3 text-[#e1e1e1] font-bold focus:border-[#00ffcc] focus:outline-none transition-all"
                  placeholder="输入密钥"
                  required={!editingExchange}
                />
              </div>

              <div>
                <label className="block text-[#666666] text-[10px] font-black uppercase tracking-widest mb-2">
                  API 私钥 {editingExchange && "(已锁定)"}
                </label>
                <input
                  type="password"
                  value={formData.apiSecret}
                  onChange={(e) =>
                    setFormData({ ...formData, apiSecret: e.target.value })
                  }
                  className="w-full bg-[#121212] border border-[#2c2c2c] rounded-xl px-4 py-3 text-[#e1e1e1] font-bold focus:border-[#00ffcc] focus:outline-none transition-all"
                  placeholder="输入私钥"
                  required={!editingExchange}
                />
              </div>

              <div className="flex items-center gap-3 bg-[#121212] p-4 rounded-xl border border-[#2c2c2c]">
                <input
                  type="checkbox"
                  id="testnet"
                  checked={formData.testnet}
                  onChange={(e) =>
                    setFormData({ ...formData, testnet: e.target.checked })
                  }
                  className="w-5 h-5 rounded-md border-[#2c2c2c] bg-transparent text-[#00ffcc] focus:ring-[#00ffcc] transition-all cursor-pointer"
                />
                <label
                  htmlFor="testnet"
                  className="text-[#e1e1e1] text-xs font-bold uppercase tracking-wider cursor-pointer"
                >
                  启用测试网基础设施
                </label>
              </div>

              <div className="flex gap-4 pt-6">
                <button
                  type="button"
                  onClick={handleCloseModal}
                  className="flex-1 border border-[#2c2c2c] text-[#666666] hover:text-[#e1e1e1] py-3 rounded-xl text-xs font-black uppercase tracking-widest transition-all"
                >
                  取消
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  className="flex-1 bg-[#00ffcc] hover:bg-[#00e6b8] text-[#121212] py-3 rounded-xl text-xs font-black uppercase tracking-widest transition-all shadow-lg"
                >
                  {submitting
                    ? "保存中..."
                    : editingExchange
                      ? "更新节点"
                      : "激活"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Detail Modal */}
      {isDetailModalOpen && selectedExchange && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-2xl p-8 w-full max-w-md shadow-2xl animate-in fade-in zoom-in-95 duration-200">
            <div className="flex items-center justify-between mb-8">
              <h2 className="text-xl font-black text-[#e1e1e1] tracking-tight uppercase">
                节点规格
              </h2>
              <button
                onClick={handleCloseDetailModal}
                className="text-[#666666] hover:text-[#ff5252] transition-colors"
              >
                <X className="w-6 h-6" />
              </button>
            </div>

            <div className="space-y-6">
              <div className="flex items-center gap-6 pb-6 border-b border-[#2c2c2c]">
                <div className="w-16 h-16 bg-[#121212] border border-[#2c2c2c] rounded-2xl flex items-center justify-center shadow-inner">
                  <Building2 className="w-8 h-8 text-[#00ffcc]" />
                </div>
                <div>
                  <h3 className="text-[#e1e1e1] font-black text-xl tracking-tight">
                    {selectedExchange.name}
                  </h3>
                  <p className="text-[#666666] text-xs font-black uppercase tracking-widest">
                    {selectedExchange.type} 节点
                  </p>
                </div>
              </div>

              <div className="space-y-4 bg-[#121212] p-6 rounded-2xl border border-[#2c2c2c]">
                {[
                  { label: "节点 ID", value: selectedExchange.id, mono: true },
                  {
                    label: "API 密钥",
                    value: maskApiKey(selectedExchange.apiKey),
                    mono: true,
                  },
                  {
                    label: "状态",
                    value: getStatusText(selectedExchange.status),
                    color:
                      selectedExchange.status === "connected"
                        ? "text-[#00ffcc]"
                        : "text-[#ff5252]",
                  },
                  {
                    label: "网络",
                    value: selectedExchange.testnet ? "测试网" : "生产环境",
                    color: selectedExchange.testnet
                      ? "text-[#ffb74d]"
                      : "text-[#a0a0a0]",
                  },
                  {
                    label: "初始化时间",
                    value: new Date(
                      selectedExchange.createdAt,
                    ).toLocaleDateString(),
                  },
                ].map((item, idx) => (
                  <div
                    key={idx}
                    className="flex justify-between items-center group"
                  >
                    <span className="text-[#666666] text-[10px] font-black uppercase tracking-widest">
                      {item.label}
                    </span>
                    <span
                      className={cn(
                        "text-xs font-black uppercase",
                        item.mono ? "font-mono" : "",
                        item.color || "text-[#e1e1e1]",
                      )}
                    >
                      {item.value}
                    </span>
                  </div>
                ))}
              </div>

              <div className="flex gap-4 pt-4">
                <button
                  onClick={() => {
                    handleCloseDetailModal();
                    handleOpenModal(selectedExchange);
                  }}
                  className="flex-1 border border-[#2c2c2c] text-[#a0a0a0] hover:text-[#00ffcc] hover:border-[#00ffcc] py-4 rounded-xl text-xs font-black uppercase tracking-widest transition-all"
                >
                  <Edit2 className="w-4 h-4 inline-block mr-2" />
                  编辑节点
                </button>
                <button
                  onClick={() => handleTestConnection(selectedExchange.id)}
                  disabled={testingId === selectedExchange.id}
                  className="flex-1 bg-[#121212] border border-[#2c2c2c] text-[#00ffcc] hover:bg-[#00ffcc]/10 py-4 rounded-xl text-xs font-black uppercase tracking-widest transition-all disabled:opacity-30"
                >
                  <TestTube className="w-4 h-4 inline-block mr-2" />
                  {testingId === selectedExchange.id ? "探测中..." : "探测连接"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
