"use client";

import { useEffect, useState, useMemo } from "react";
import {
  Download,
  Filter,
  Search,
  ChevronLeft,
  ChevronRight,
  Calendar,
} from "lucide-react";

import { getOrders } from "@/api/orders";
import type { Order } from "@/types/models";
import { cn } from "@/lib/utils";

type OrderStatus = "all" | "pending" | "filled" | "cancelled";

export default function Orders() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Filters
  const [statusFilter, setStatusFilter] = useState<OrderStatus>("all");
  const [symbolFilter, setSymbolFilter] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [searchQuery, setSearchQuery] = useState("");

  // Pagination
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 12;

  useEffect(() => {
    async function fetchOrders() {
      try {
        setLoading(true);
        const params: {
          status?: string;
          symbol?: string;
          startTime?: string;
          endTime?: string;
        } = {};

        if (statusFilter !== "all") {
          params.status = statusFilter;
        }
        if (symbolFilter) {
          params.symbol = symbolFilter.toUpperCase();
        }
        if (startDate) {
          params.startTime = new Date(startDate).toISOString();
        }
        if (endDate) {
          params.endTime = new Date(endDate).toISOString();
        }

        const data = await getOrders(params);
        setOrders(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to fetch orders");
      } finally {
        setLoading(false);
      }
    }

    fetchOrders();
  }, [statusFilter, symbolFilter, startDate, endDate]);

  const filteredOrders = useMemo(() => {
    let result = [...orders];

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

    result.sort(
      (a, b) =>
        new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
    );

    return result;
  }, [orders, searchQuery]);

  const totalPages = Math.ceil(filteredOrders.length / itemsPerPage);
  const paginatedOrders = useMemo(() => {
    const start = (currentPage - 1) * itemsPerPage;
    return filteredOrders.slice(start, start + itemsPerPage);
  }, [filteredOrders, currentPage]);

  const handleExport = () => {
    const csvContent = [
      ["Time", "Symbol", "Type", "Side", "Price", "Amount", "Status"].join(","),
      ...filteredOrders.map((order) =>
        [
          new Date(order.timestamp).toLocaleString(),
          order.symbol,
          order.type,
          order.side,
          order.price?.toFixed(2) ?? "Market",
          order.quantity,
          order.status,
        ].join(","),
      ),
    ].join("\\n");

    const blob = new Blob([csvContent], { type: "text/csv" });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `orders_${new Date().toISOString().split("T")[0]}.csv`;
    a.click();
    window.URL.revokeObjectURL(url);
  };

  const getStatusColor = (status: Order["status"]) => {
    switch (status) {
      case "filled":
        return "bg-[#00ffcc]/10 text-[#00ffcc] border-[#00ffcc]/20";
      case "pending":
      case "open":
        return "bg-[#ffb74d]/10 text-[#ffb74d] border-[#ffb74d]/20";
      case "cancelled":
      case "rejected":
        return "bg-[#ff5252]/10 text-[#ff5252] border-[#ff5252]/20";
      case "partially_filled":
        return "bg-blue-500/10 text-blue-400 border-blue-500/20";
      default:
        return "bg-[#a0a0a0]/10 text-[#a0a0a0] border-[#a0a0a0]/20";
    }
  };

  const getSideColor = (side: Order["side"]) => {
    return side === "buy" ? "text-[#00ffcc]" : "text-[#ff5252]";
  };

  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>
    );
  }

  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 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">
          <div className="flex flex-wrap gap-4 items-center">
            {/* Status Filter */}
            <div className="flex items-center gap-2 bg-[#121212] border border-[#2c2c2c] rounded-lg px-3 py-1.5">
              <Filter className="w-3.5 h-3.5 text-[#666666]" />
              <select
                value={statusFilter}
                onChange={(e) => {
                  setStatusFilter(e.target.value as OrderStatus);
                  setCurrentPage(1);
                }}
                className="bg-transparent text-xs font-bold text-[#e1e1e1] uppercase focus:outline-none cursor-pointer"
              >
                <option value="all">全部状态</option>
                <option value="pending">待处理</option>
                <option value="filled">已成交</option>
                <option value="cancelled">已取消</option>
              </select>
            </div>

            {/* Symbol Filter */}
            <div className="relative">
              <Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-[#666666]" />
              <input
                type="text"
                placeholder="交易对..."
                value={symbolFilter}
                onChange={(e) => {
                  setSymbolFilter(e.target.value);
                  setCurrentPage(1);
                }}
                className="bg-[#121212] border border-[#2c2c2c] rounded-lg pl-9 pr-3 py-1.5 text-xs font-bold text-[#e1e1e1] placeholder-[#666666] w-32 focus:outline-none focus:border-[#00ffcc] uppercase"
              />
            </div>

            {/* Date Range */}
            <div className="flex items-center gap-2">
              <div className="flex items-center gap-2 bg-[#121212] border border-[#2c2c2c] rounded-lg px-3 py-1.5">
                <Calendar className="w-3.5 h-3.5 text-[#666666]" />
                <input
                  type="text"
                  placeholder="YYYY-MM-DD"
                  value={startDate}
                  onChange={(e) => {
                    setStartDate(e.target.value);
                    setCurrentPage(1);
                  }}
                  className="bg-transparent text-[10px] font-bold text-[#e1e1e1] focus:outline-none w-[90px] placeholder:text-[#444444]"
                />
              </div>
              <span className="text-[#666666] text-[10px] font-bold">至</span>
              <div className="flex items-center gap-2 bg-[#121212] border border-[#2c2c2c] rounded-lg px-3 py-1.5">
                <input
                  type="text"
                  placeholder="YYYY-MM-DD"
                  value={endDate}
                  onChange={(e) => {
                    setEndDate(e.target.value);
                    setCurrentPage(1);
                  }}
                  className="bg-transparent text-[10px] font-bold text-[#e1e1e1] focus:outline-none w-[90px] placeholder:text-[#444444]"
                />
              </div>
            </div>
          </div>

          <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="搜索订单..."
                value={searchQuery}
                onChange={(e) => {
                  setSearchQuery(e.target.value);
                  setCurrentPage(1);
                }}
                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>

            {/* Export Button */}
            <button
              onClick={handleExport}
              className="flex items-center gap-2 bg-[#121212] border border-[#2c2c2c] hover:border-[#00ffcc] hover:text-[#00ffcc] text-[#a0a0a0] px-4 py-2 rounded-lg text-xs font-bold uppercase tracking-wider transition-all duration-200"
            >
              <Download className="w-4 h-4" />
              Export
            </button>
          </div>
        </div>
      </div>

      {/* Orders Table */}
      <div className="bg-[#1e1e1e] rounded-xl border border-[#2c2c2c] overflow-hidden shadow-2xl">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-[#121212] border-b border-[#2c2c2c]">
                <th className="px-6 py-4 text-left text-[10px] font-black text-[#666666] uppercase tracking-widest">
                  时间
                </th>
                <th className="px-6 py-4 text-left text-[10px] font-black text-[#666666] uppercase tracking-widest">
                  Symbol
                </th>
                <th className="px-6 py-4 text-left text-[10px] font-black text-[#666666] uppercase tracking-widest">
                  Type
                </th>
                <th className="px-6 py-4 text-left text-[10px] font-black text-[#666666] uppercase tracking-widest">
                  Side
                </th>
                <th className="px-6 py-4 text-right text-[10px] font-black text-[#666666] uppercase tracking-widest">
                  Price
                </th>
                <th className="px-6 py-4 text-right text-[10px] font-black text-[#666666] uppercase tracking-widest">
                  Quantity
                </th>
                <th className="px-6 py-4 text-center text-[10px] font-black text-[#666666] uppercase tracking-widest">
                  Status
                </th>
                <th className="px-6 py-4 text-right text-[10px] font-black text-[#666666] uppercase tracking-widest">
                  成交进度
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#2c2c2c]">
              {paginatedOrders.length === 0 ? (
                <tr>
                  <td
                    colSpan={8}
                    className="px-6 py-20 text-center text-[#666666] font-bold uppercase tracking-widest"
                  >
                    没有匹配的订单
                  </td>
                </tr>
              ) : (
                paginatedOrders.map((order) => (
                  <tr
                    key={order.id}
                    className="hover:bg-[#121212] transition-colors group cursor-default"
                  >
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="text-xs font-bold text-[#a0a0a0] group-hover:text-[#e1e1e1]">
                        {new Date(order.timestamp).toLocaleString()}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="text-sm font-black text-[#e1e1e1] group-hover:text-[#00ffcc]">
                        {order.symbol}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="text-[10px] font-black text-[#666666] uppercase">
                        {order.type}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span
                        className={cn(
                          "text-xs font-black uppercase italic tracking-tighter",
                          getSideColor(order.side),
                        )}
                      >
                        {order.side}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right">
                      <span className="text-sm font-mono font-bold text-[#e1e1e1]">
                        {order.price ? order.price.toFixed(2) : "市价"}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right">
                      <span className="text-sm font-mono font-bold text-[#e1e1e1]">
                        {order.quantity?.toFixed(4)}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-center">
                      <span
                        className={cn(
                          "inline-flex items-center px-2.5 py-1 rounded-md text-[10px] font-black uppercase tracking-wider border shadow-sm",
                          getStatusColor(order.status),
                        )}
                      >
                        {order.status}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right">
                      <div className="flex flex-col items-end">
                        <span className="text-xs font-bold text-[#a0a0a0]">
                          {(order.filledQuantity ?? 0).toFixed(4)}
                        </span>
                        <div className="w-20 h-1 bg-[#121212] rounded-full mt-1 overflow-hidden border border-[#2c2c2c]">
                          <div
                            className="h-full bg-[#00ffcc] rounded-full transition-all duration-500"
                            style={{
                              width: `${(order.filledQuantity! / order.quantity!) * 100}%`,
                            }}
                          />
                        </div>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="px-6 py-4 bg-[#121212] border-t border-[#2c2c2c] flex items-center justify-between">
            <span className="text-[10px] font-black text-[#666666] uppercase tracking-widest">
              显示 {(currentPage - 1) * itemsPerPage + 1} 至{" "}
              {Math.min(currentPage * itemsPerPage, filteredOrders.length)} /{" "}
              {filteredOrders.length} 条订单
            </span>
            <div className="flex items-center gap-4">
              <button
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="p-1.5 rounded-lg border border-[#2c2c2c] text-[#a0a0a0] hover:text-[#00ffcc] hover:border-[#00ffcc] disabled:opacity-30 disabled:hover:text-[#a0a0a0] disabled:hover:border-[#2c2c2c] transition-all"
              >
                <ChevronLeft className="w-5 h-5" />
              </button>
              <span className="text-xs font-black text-[#e1e1e1] uppercase">
                PAGE {currentPage} / {totalPages}
              </span>
              <button
                onClick={() =>
                  setCurrentPage((p) => Math.min(totalPages, p + 1))
                }
                disabled={currentPage === totalPages}
                className="p-1.5 rounded-lg border border-[#2c2c2c] text-[#a0a0a0] hover:text-[#00ffcc] hover:border-[#00ffcc] disabled:opacity-30 disabled:hover:text-[#a0a0a0] disabled:hover:border-[#2c2c2c] transition-all"
              >
                <ChevronRight className="w-5 h-5" />
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
