'use client';

import { useState } from 'react';
import { PageHeader } from '@/components/layout/page-header';
import { useP2pTransfers } from '@/features/users/hooks/use-users';
import { Card, CardContent, CardHeader, CardTitle } 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 { Badge } from '@/components/ui/badge';
import { ChevronLeft, ChevronRight, Search, ArrowRightLeft, Coins, Hash } from 'lucide-react';
import { formatDecimal } from '@/lib/utils/format';
import { formatDateTime } from '@/lib/utils/date';

export default function P2pTransfersPage() {
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [searchInput, setSearchInput] = useState('');
  const pageSize = 20;

  const { data, isLoading } = useP2pTransfers({ page, pageSize, search: search || undefined });

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

  return (
    <div className="space-y-6">
      <PageHeader title="P2P划转记录" description="查看所有用户间积分值划转记录及手续费汇总" />

      {/* 汇总统计 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">累计手续费收入</CardTitle>
            <Coins className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <Skeleton className="h-8 w-32" />
            ) : (
              <div className="text-2xl font-bold text-green-600">
                {formatDecimal(data?.summary.totalFee || '0', 2)}
              </div>
            )}
            <p className="text-xs text-muted-foreground mt-1">积分值</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">累计划转金额</CardTitle>
            <ArrowRightLeft className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <Skeleton className="h-8 w-32" />
            ) : (
              <div className="text-2xl font-bold">
                {formatDecimal(data?.summary.totalAmount || '0', 2)}
              </div>
            )}
            <p className="text-xs text-muted-foreground mt-1">积分值</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">成功划转笔数</CardTitle>
            <Hash className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <Skeleton className="h-8 w-32" />
            ) : (
              <div className="text-2xl font-bold">
                {data?.summary.totalCount || 0}
              </div>
            )}
            <p className="text-xs text-muted-foreground mt-1">笔</p>
          </CardContent>
        </Card>
      </div>

      {/* 搜索 */}
      <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={() => { setSearch(''); setSearchInput(''); setPage(1); }} variant="ghost">
                清除
              </Button>
            )}
          </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>备注</TableHead>
                <TableHead>时间</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                [...Array(5)].map((_, i) => (
                  <TableRow key={i}>
                    {[...Array(7)].map((_, j) => (
                      <TableCell key={j}>
                        <Skeleton className="h-4 w-full" />
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              ) : !data?.items.length ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                    暂无划转记录
                  </TableCell>
                </TableRow>
              ) : (
                data.items.map((record) => (
                  <TableRow key={record.transferNo}>
                    <TableCell className="font-mono text-xs">{record.transferNo}</TableCell>
                    <TableCell>
                      <div className="flex flex-col">
                        <span className="font-medium text-sm">{record.fromNickname || record.fromPhone || '-'}</span>
                        <span className="text-xs text-muted-foreground font-mono">{record.fromAccountSequence}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col">
                        <span className="font-medium text-sm">{record.toNickname || record.toPhone}</span>
                        <span className="text-xs text-muted-foreground font-mono">{record.toAccountSequence}</span>
                      </div>
                    </TableCell>
                    <TableCell className="text-right font-mono">{formatDecimal(record.amount, 2)}</TableCell>
                    <TableCell className="text-right font-mono text-orange-600">{formatDecimal(record.fee || '0', 2)}</TableCell>
                    <TableCell className="text-sm text-muted-foreground max-w-[120px] truncate">{record.memo || '-'}</TableCell>
                    <TableCell className="text-sm">{formatDateTime(record.createdAt)}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>

          {data && data.totalPages > 1 && (
            <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>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
