'use client';

import { PageHeader } from '@/components/layout/page-header';
import { Skeleton } from '@/components/ui/skeleton';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { AlertCircle, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useQueryClient } from '@tanstack/react-query';

import {
  useSystemAccountsSummary,
  useCategorizedAccounts,
  AccountCard,
  AccountsTable,
  SummaryCards,
} from '@/features/system-accounts';

export default function SystemAccountsPage() {
  const queryClient = useQueryClient();

  const {
    data: summary,
    isLoading: summaryLoading,
    error: summaryError,
  } = useSystemAccountsSummary();

  const {
    data: categorized,
    isLoading: accountsLoading,
    error: accountsError,
    total,
  } = useCategorizedAccounts();

  const isLoading = summaryLoading || accountsLoading;
  const hasError = summaryError || accountsError;

  const handleRefresh = () => {
    queryClient.invalidateQueries({ queryKey: ['system-accounts'] });
  };

  return (
    <div className="space-y-6">
      <PageHeader
        title="系统账户"
        description="查看系统账户余额和算力分布"
        actions={
          <Button
            variant="outline"
            size="sm"
            onClick={handleRefresh}
            disabled={isLoading}
          >
            <RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
            刷新
          </Button>
        }
      />

      {hasError && (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            加载系统账户数据失败，请稍后重试。
          </AlertDescription>
        </Alert>
      )}

      {/* Summary Cards */}
      <SummaryCards summary={summary} isLoading={summaryLoading} />

      {/* Main Content with Tabs */}
      <Tabs defaultValue="overview" className="space-y-4">
        <TabsList>
          <TabsTrigger value="overview">概览</TabsTrigger>
          <TabsTrigger value="all">全部账户</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-6">
          {/* Main Pools - Card Grid */}
          {categorized.mainPools.length > 0 && (
            <div>
              <h3 className="text-lg font-semibold mb-4">主要资金池</h3>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {accountsLoading
                  ? [...Array(3)].map((_, i) => (
                      <Card key={i}>
                        <CardContent className="p-6">
                          <Skeleton className="h-20 w-full" />
                        </CardContent>
                      </Card>
                    ))
                  : categorized.mainPools.map((account) => (
                      <AccountCard key={account.accountType} account={account} />
                    ))}
              </div>
            </div>
          )}

          {/* System Distribution Accounts - Table */}
          <AccountsTable
            title="系统分配账户"
            accounts={categorized.systemAccounts}
            isLoading={accountsLoading}
            showSyncInfo
          />

          {/* Fixed Accounts if any */}
          {categorized.fixedAccounts.length > 0 && (
            <AccountsTable
              title="固定账户"
              accounts={categorized.fixedAccounts}
              isLoading={accountsLoading}
              showSyncInfo
            />
          )}
        </TabsContent>

        <TabsContent value="all" className="space-y-6">
          {/* All Accounts in one table */}
          <AccountsTable
            title={`全部系统账户 (${total})`}
            accounts={[
              ...categorized.mainPools,
              ...categorized.systemAccounts,
              ...categorized.fixedAccounts,
              ...categorized.otherAccounts,
            ]}
            isLoading={accountsLoading}
            showSyncInfo
          />
        </TabsContent>
      </Tabs>
    </div>
  );
}
