import React, { useMemo } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { transformFinancialData, TimeSeriesFinancialDto } from '@/lib/financial-data-transformer';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Loader2, AlertCircle } from "lucide-react";

interface FinancialTableProps {
  data: unknown[];
  status: 'idle' | 'fetching' | 'complete' | 'error';
}

export function FinancialTable({ data, status }: FinancialTableProps) {
  const tableData = useMemo(() => {
    if (!Array.isArray(data)) return { headers: [], rows: [] };
    return transformFinancialData(data as TimeSeriesFinancialDto[]);
  }, [data]);

  if (status === 'idle') {
    return (
      <div className="flex items-center justify-center h-[200px] text-muted-foreground border rounded-lg border-dashed">
        Waiting to start analysis...
      </div>
    );
  }

  if (status === 'fetching') {
    return (
      <div className="flex flex-col items-center justify-center h-[300px] text-muted-foreground border rounded-lg gap-4">
        <Loader2 className="h-8 w-8 animate-spin" />
        <p>Fetching financial data from Tushare, YFinance, and AlphaVantage...</p>
      </div>
    );
  }

  if (status === 'error') {
    return (
      <div className="flex items-center justify-center h-[200px] text-destructive border rounded-lg border-destructive/50 bg-destructive/10 gap-2">
        <AlertCircle className="h-5 w-5" />
        <span>Error fetching data. Please try again.</span>
      </div>
    );
  }

  if (tableData.rows.length === 0) {
    return (
      <div className="flex items-center justify-center h-[200px] text-muted-foreground border rounded-lg">
        No financial data available.
      </div>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Financial Statements</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[200px]">Metric</TableHead>
                {tableData.headers.map(year => (
                  <TableHead key={year} className="text-right">{year}</TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {tableData.rows.map((row, idx) => (
                <TableRow key={idx}>
                  <TableCell className="font-medium">{row.metric}</TableCell>
                  {tableData.headers.map(year => (
                    <TableCell key={year} className="text-right">
                      {row[year] !== undefined 
                        ? typeof row[year] === 'number' 
                          ? (row[year] as number).toLocaleString(undefined, { maximumFractionDigits: 2 }) 
                          : row[year] 
                        : '-'}
                    </TableCell>
                  ))}
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
        <div className="mt-4 text-xs text-muted-foreground">
            * Data aggregated from multiple sources. Duplicate metrics from different sources are currently overwritten by the latest received.
        </div>
      </CardContent>
    </Card>
  );
}
