'use client';

import { useState } from 'react';
import { PageHeader } from '@/components/layout/page-header';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api/client';
import { formatDecimal, formatNumber, formatCompactNumber } from '@/lib/utils/format';
import { formatDate } from '@/lib/utils/date';
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { ChevronLeft, ChevronRight, Download } from 'lucide-react';
import type { PaginatedResponse } from '@/types/api';

interface DailyReport {
  id: string;
  reportDate: string;
  totalUsers: number;
  newUsers: number;
  adoptedUsers: number;
  newAdoptedUsers: number;
  totalContribution: string;
  newContribution: string;
  totalDistributed: string;
  dailyDistributed: string;
  totalBurned: string;
  dailyBurned: string;
  openPrice: string;
  closePrice: string;
  highPrice: string;
  lowPrice: string;
  totalVolume: string;
  dailyVolume: string;
}

export default function ReportsPage() {
  const [page, setPage] = useState(1);
  const [period, setPeriod] = useState('7');
  const pageSize = 30;

  const { data, isLoading } = useQuery({
    queryKey: ['reports', 'daily', page, period],
    queryFn: async () => {
      const response = await apiClient.get('/reports/daily', {
        params: { page, pageSize, days: period },
      });
      return response.data.data as PaginatedResponse<DailyReport>;
    },
  });

  return (
    <div className="space-y-6">
      <PageHeader
        title="报表统计"
        description="查看每日统计报表"
        actions={
          <Button variant="outline">
            <Download className="h-4 w-4 mr-2" />
            导出
          </Button>
        }
      />

      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="text-lg">每日报表</CardTitle>
          <Select value={period} onValueChange={setPeriod}>
            <SelectTrigger className="w-[150px]">
              <SelectValue placeholder="选择周期" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="7">近7天</SelectItem>
              <SelectItem value="30">近30天</SelectItem>
              <SelectItem value="90">近90天</SelectItem>
            </SelectContent>
          </Select>
        </CardHeader>
        <CardContent className="p-0 overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <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 className="text-right">当日分配</TableHead>
                <TableHead className="text-right">当日销毁</TableHead>
                <TableHead className="text-right">收盘价</TableHead>
                <TableHead className="text-right">当日成交量</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                [...Array(7)].map((_, i) => (
                  <TableRow key={i}>
                    {[...Array(11)].map((_, j) => (
                      <TableCell key={j}>
                        <Skeleton className="h-4 w-full" />
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              ) : data?.items.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={11} className="text-center py-8 text-muted-foreground">
                    暂无报表数据
                  </TableCell>
                </TableRow>
              ) : (
                data?.items.map((report) => (
                  <TableRow key={report.id}>
                    <TableCell>{formatDate(report.reportDate)}</TableCell>
                    <TableCell className="text-right">{formatNumber(report.totalUsers)}</TableCell>
                    <TableCell className="text-right text-green-600">+{formatNumber(report.newUsers)}</TableCell>
                    <TableCell className="text-right">{formatNumber(report.adoptedUsers)}</TableCell>
                    <TableCell className="text-right text-green-600">+{formatNumber(report.newAdoptedUsers)}</TableCell>
                    <TableCell className="text-right font-mono">{formatCompactNumber(report.totalContribution)}</TableCell>
                    <TableCell className="text-right font-mono text-green-600">
                      +{formatCompactNumber(report.newContribution)}
                    </TableCell>
                    <TableCell className="text-right font-mono">{formatDecimal(report.dailyDistributed, 8)}</TableCell>
                    <TableCell className="text-right font-mono">{formatDecimal(report.dailyBurned, 8)}</TableCell>
                    <TableCell className="text-right font-mono">{formatDecimal(report.closePrice, 8)}</TableCell>
                    <TableCell className="text-right font-mono">{formatCompactNumber(report.dailyVolume)}</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>
  );
}
