'use client';

import { useState } from 'react';
import { PageHeader } from '@/components/layout/page-header';
import { useAdminOrders, useAdminTrades } from '@/features/trading/hooks/use-trading';
import type { AdminOrder, AdminTrade } from '@/features/trading/api/trading.api';
import { Card, CardContent } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ChevronLeft, ChevronRight, Search } from 'lucide-react';
import { formatDecimal } from '@/lib/utils/format';
import { formatDateTime } from '@/lib/utils/date';

const orderStatusLabels: Record<string, { label: string; className: string }> = {
  PENDING: { label: '待成交', className: 'bg-yellow-100 text-yellow-700' },
  PARTIAL: { label: '部分成交', className: 'bg-blue-100 text-blue-700' },
  FILLED: { label: '已成交', className: 'bg-green-100 text-green-700' },
  CANCELLED: { label: '已取消', className: 'bg-gray-100 text-gray-600' },
};

const sourceLabels: Record<string, { label: string; className: string }> = {
  USER: { label: '用户', className: 'bg-gray-100 text-gray-700' },
  MARKET_MAKER: { label: '做市商', className: 'bg-purple-100 text-purple-700' },
  DEX_BOT: { label: 'DEX Bot', className: 'bg-blue-100 text-blue-700' },
  SYSTEM: { label: '系统', className: 'bg-gray-100 text-gray-600' },
};

export default function ExchangeRecordsPage() {
  const [tab, setTab] = useState<'orders' | 'trades'>('orders');

  // 订单 tab 状态
  const [ordersPage, setOrdersPage] = useState(1);
  const [orderType, setOrderType] = useState<string>('ALL');
  const [orderStatus, setOrderStatus] = useState<string>('ALL');
  const [orderSource, setOrderSource] = useState<string>('ALL');

  // 成交 tab 状态
  const [tradesPage, setTradesPage] = useState(1);
  const [tradeSource, setTradeSource] = useState<string>('ALL');

  // 共享搜索状态
  const [searchInput, setSearchInput] = useState('');
  const [search, setSearch] = useState('');

  const pageSize = 20;

  const { data: ordersData, isLoading: ordersLoading } = useAdminOrders({
    page: ordersPage,
    pageSize,
    type: orderType === 'ALL' ? undefined : orderType as 'BUY' | 'SELL',
    status: orderStatus === 'ALL' ? undefined : orderStatus as any,
    source: orderSource === 'ALL' ? undefined : orderSource as any,
    search: search || undefined,
  });

  const { data: tradesData, isLoading: tradesLoading } = useAdminTrades({
    page: tradesPage,
    pageSize,
    source: tradeSource === 'ALL' ? undefined : tradeSource as any,
    search: search || undefined,
  });

  const handleSearch = () => {
    setSearch(searchInput);
    setOrdersPage(1);
    setTradesPage(1);
  };

  const handleClearSearch = () => {
    setSearchInput('');
    setSearch('');
    setOrdersPage(1);
    setTradesPage(1);
  };

  const handleTabChange = (value: string) => {
    setTab(value as 'orders' | 'trades');
  };

  const renderBadge = (text: string, className: string) => (
    <span className={`inline-flex items-center px-2 py-1 rounded text-xs font-medium ${className}`}>
      {text}
    </span>
  );

  const renderSkeletonRows = (cols: number) =>
    [...Array(5)].map((_, i) => (
      <TableRow key={i}>
        {[...Array(cols)].map((_, j) => (
          <TableCell key={j}><Skeleton className="h-4 w-full" /></TableCell>
        ))}
      </TableRow>
    ));

  const renderPagination = (
    data: { total: number; totalPages: number } | undefined,
    page: number,
    setPage: (p: number) => void,
  ) => {
    if (!data || data.totalPages <= 1) return null;
    return (
      <div className="flex items-center justify-between p-4 border-t">
        <p className="text-sm text-muted-foreground">
          共 {data.total} 条，第 {page} / {data.totalPages} 页
        </p>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={() => setPage(page - 1)} disabled={page <= 1}>
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <Button variant="outline" size="sm" onClick={() => setPage(page + 1)} disabled={page >= data.totalPages}>
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>
      </div>
    );
  };

  return (
    <div className="space-y-6">
      <PageHeader title="兑换记录" description="查看全部积分股兑换订单与成交明细" />

      {/* 搜索栏 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex gap-2">
            <Input
              placeholder="搜索账号、订单号、成交号..."
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
              className="max-w-md"
            />
            <Button onClick={handleSearch} variant="outline">
              <Search className="h-4 w-4 mr-2" />
              搜索
            </Button>
            {search && (
              <Button onClick={handleClearSearch} variant="ghost">
                清除
              </Button>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Tabs */}
      <Tabs value={tab} onValueChange={handleTabChange}>
        <TabsList>
          <TabsTrigger value="orders">订单记录</TabsTrigger>
          <TabsTrigger value="trades">成交明细</TabsTrigger>
        </TabsList>

        {/* 订单记录 Tab */}
        <TabsContent value="orders" className="space-y-4">
          {/* 筛选栏 */}
          <Card>
            <CardContent className="p-4">
              <div className="flex gap-3 flex-wrap">
                <Select value={orderType} onValueChange={(v) => { setOrderType(v); setOrdersPage(1); }}>
                  <SelectTrigger className="w-[120px]">
                    <SelectValue placeholder="类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ALL">全部类型</SelectItem>
                    <SelectItem value="BUY">买入</SelectItem>
                    <SelectItem value="SELL">卖出</SelectItem>
                  </SelectContent>
                </Select>

                <Select value={orderStatus} onValueChange={(v) => { setOrderStatus(v); setOrdersPage(1); }}>
                  <SelectTrigger className="w-[130px]">
                    <SelectValue placeholder="状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ALL">全部状态</SelectItem>
                    <SelectItem value="PENDING">待成交</SelectItem>
                    <SelectItem value="PARTIAL">部分成交</SelectItem>
                    <SelectItem value="FILLED">已成交</SelectItem>
                    <SelectItem value="CANCELLED">已取消</SelectItem>
                  </SelectContent>
                </Select>

                <Select value={orderSource} onValueChange={(v) => { setOrderSource(v); setOrdersPage(1); }}>
                  <SelectTrigger className="w-[130px]">
                    <SelectValue placeholder="来源" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ALL">全部来源</SelectItem>
                    <SelectItem value="USER">用户</SelectItem>
                    <SelectItem value="MARKET_MAKER">做市商</SelectItem>
                    <SelectItem value="DEX_BOT">DEX Bot</SelectItem>
                    <SelectItem value="SYSTEM">系统</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* 订单表格 */}
          <Card>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>订单号</TableHead>
                    <TableHead>账号</TableHead>
                    <TableHead>类型</TableHead>
                    <TableHead>状态</TableHead>
                    <TableHead>来源</TableHead>
                    <TableHead className="text-right">价格</TableHead>
                    <TableHead className="text-right">数量</TableHead>
                    <TableHead className="text-right">已成交</TableHead>
                    <TableHead className="text-right">金额</TableHead>
                    <TableHead>时间</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {ordersLoading ? renderSkeletonRows(10) : !ordersData?.data?.length ? (
                    <TableRow>
                      <TableCell colSpan={10} className="text-center py-8 text-muted-foreground">
                        暂无订单记录
                      </TableCell>
                    </TableRow>
                  ) : (
                    ordersData.data.map((order: AdminOrder) => {
                      const status = orderStatusLabels[order.status] || { label: order.status, className: '' };
                      const source = sourceLabels[order.source] || { label: order.source, className: '' };
                      return (
                        <TableRow key={order.id}>
                          <TableCell className="font-mono text-xs max-w-[120px] truncate" title={order.orderNo}>
                            {order.orderNo}
                          </TableCell>
                          <TableCell className="font-mono text-xs">{order.accountSequence}</TableCell>
                          <TableCell>
                            {renderBadge(
                              order.type === 'BUY' ? '买入' : '卖出',
                              order.type === 'BUY' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700',
                            )}
                          </TableCell>
                          <TableCell>{renderBadge(status.label, status.className)}</TableCell>
                          <TableCell>{renderBadge(source.label, source.className)}</TableCell>
                          <TableCell className="text-right font-mono text-sm">{formatDecimal(order.price, 8)}</TableCell>
                          <TableCell className="text-right font-mono text-sm">{formatDecimal(order.quantity, 2)}</TableCell>
                          <TableCell className="text-right font-mono text-sm">{formatDecimal(order.filledQuantity, 2)}</TableCell>
                          <TableCell className="text-right font-mono text-sm">{formatDecimal(order.totalAmount, 2)}</TableCell>
                          <TableCell className="text-sm whitespace-nowrap">{formatDateTime(order.createdAt)}</TableCell>
                        </TableRow>
                      );
                    })
                  )}
                </TableBody>
              </Table>
              {renderPagination(ordersData, ordersPage, setOrdersPage)}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 成交明细 Tab */}
        <TabsContent value="trades" className="space-y-4">
          {/* 筛选栏 */}
          <Card>
            <CardContent className="p-4">
              <div className="flex gap-3">
                <Select value={tradeSource} onValueChange={(v) => { setTradeSource(v); setTradesPage(1); }}>
                  <SelectTrigger className="w-[130px]">
                    <SelectValue placeholder="来源" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ALL">全部来源</SelectItem>
                    <SelectItem value="USER">用户</SelectItem>
                    <SelectItem value="MARKET_MAKER">做市商</SelectItem>
                    <SelectItem value="DEX_BOT">DEX Bot</SelectItem>
                    <SelectItem value="SYSTEM">系统</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* 成交表格 */}
          <Card>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>成交号</TableHead>
                    <TableHead>买方</TableHead>
                    <TableHead>卖方</TableHead>
                    <TableHead className="text-right">价格</TableHead>
                    <TableHead className="text-right">有效数量</TableHead>
                    <TableHead className="text-right">原始数量</TableHead>
                    <TableHead className="text-right">销毁量</TableHead>
                    <TableHead className="text-right">成交额</TableHead>
                    <TableHead className="text-right">手续费</TableHead>
                    <TableHead>时间</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {tradesLoading ? renderSkeletonRows(10) : !tradesData?.data?.length ? (
                    <TableRow>
                      <TableCell colSpan={10} className="text-center py-8 text-muted-foreground">
                        暂无成交记录
                      </TableCell>
                    </TableRow>
                  ) : (
                    tradesData.data.map((trade: AdminTrade) => (
                      <TableRow key={trade.id}>
                        <TableCell className="font-mono text-xs max-w-[120px] truncate" title={trade.tradeNo}>
                          {trade.tradeNo}
                        </TableCell>
                        <TableCell className="font-mono text-xs">{trade.buyerSequence}</TableCell>
                        <TableCell className="font-mono text-xs">{trade.sellerSequence}</TableCell>
                        <TableCell className="text-right font-mono text-sm">{formatDecimal(trade.price, 8)}</TableCell>
                        <TableCell className="text-right font-mono text-sm">{formatDecimal(trade.quantity, 2)}</TableCell>
                        <TableCell className="text-right font-mono text-sm">{formatDecimal(trade.originalQuantity, 2)}</TableCell>
                        <TableCell className="text-right font-mono text-sm text-orange-600">{formatDecimal(trade.burnQuantity, 2)}</TableCell>
                        <TableCell className="text-right font-mono text-sm">{formatDecimal(trade.amount, 2)}</TableCell>
                        <TableCell className="text-right font-mono text-sm text-orange-600">{formatDecimal(trade.fee, 2)}</TableCell>
                        <TableCell className="text-sm whitespace-nowrap">{formatDateTime(trade.createdAt)}</TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
              {renderPagination(tradesData, tradesPage, setTradesPage)}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
