import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Badge } from "@/components/ui/badge"
import { CheckCircle2, XCircle, Loader2, Code } from "lucide-react"
import { useWorkflowStore } from "@/stores/useWorkflowStore"
import { TaskStatus } from "@/types/workflow"

export function FinancialTable() {
    const { tasks, dag } = useWorkflowStore();
    
    // Identify DataFetch tasks dynamically from DAG
    const fetchTasks = dag?.nodes.filter(n => n.type === 'DataFetch') || [];

    return (
        <div className="space-y-6">
            {/* 1. Data Provider Status Cards */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {fetchTasks.map(node => {
                    const taskState = tasks[node.id];
                    const status = taskState?.status || 'Pending';
                    
                    return (
                        <Card key={node.id} className="flex flex-col">
                            <CardHeader className="pb-2">
                                <div className="flex justify-between items-start">
                                    <CardTitle className="text-sm font-medium">{node.label}</CardTitle>
                                    <StatusBadge status={status} />
                                </div>
                            </CardHeader>
                            <CardContent className="flex-1 flex flex-col text-xs">
                                <div className="text-muted-foreground mb-2 flex-1">
                                    {taskState?.message || "Waiting to start..."}
                                </div>
                                
                                {/* Mock Raw Data Preview if Completed */}
                                {status === 'Completed' && (
                                    <div className="mt-auto pt-2 border-t">
                                        <div className="text-[10px] uppercase font-mono text-muted-foreground mb-1">Raw Response Preview</div>
                                        <ScrollArea className="h-[80px] w-full rounded border bg-muted/50 p-2 font-mono text-[10px]">
                                            {`{
  "symbol": "AAPL",
  "currency": "USD",
  "data": [
    { "period": "2023", "rev": 383285000000 },
    { "period": "2022", "rev": 394328000000 }
  ]
}`}
                                        </ScrollArea>
                                    </div>
                                )}
                            </CardContent>
                        </Card>
                    );
                })}
            </div>

            {/* 2. Consolidated Financial Table (Mock) */}
            <Card>
                <CardHeader>
                    <CardTitle>Consolidated Income Statement</CardTitle>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableCaption>Aggregated from all successful providers.</TableCaption>
                        <TableHeader>
                            <TableRow>
                                <TableHead className="w-[200px]">Metric</TableHead>
                                <TableHead>TTM</TableHead>
                                <TableHead>2023</TableHead>
                                <TableHead>2022</TableHead>
                                <TableHead>2021</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            <TableRow>
                                <TableCell className="font-medium">Revenue</TableCell>
                                <TableCell>10.5B</TableCell>
                                <TableCell>10.0B</TableCell>
                                <TableCell>9.2B</TableCell>
                                <TableCell>8.5B</TableCell>
                            </TableRow>
                            <TableRow>
                                <TableCell className="font-medium">Gross Profit</TableCell>
                                <TableCell>4.2B</TableCell>
                                <TableCell>4.0B</TableCell>
                                <TableCell>3.6B</TableCell>
                                <TableCell>3.2B</TableCell>
                            </TableRow>
                            <TableRow>
                                <TableCell className="font-medium">Net Income</TableCell>
                                <TableCell>2.1B</TableCell>
                                <TableCell>2.0B</TableCell>
                                <TableCell>1.8B</TableCell>
                                <TableCell>1.5B</TableCell>
                            </TableRow>
                        </TableBody>
                    </Table>
                </CardContent>
            </Card>
        </div>
    )
}

function StatusBadge({ status }: { status: TaskStatus }) {
    switch (status) {
        case 'Running': 
            return <Badge variant="outline" className="border-blue-500 text-blue-500"><Loader2 className="h-3 w-3 mr-1 animate-spin" /> Fetching</Badge>;
        case 'Completed': 
            return <Badge variant="outline" className="border-green-500 text-green-500"><CheckCircle2 className="h-3 w-3 mr-1" /> Success</Badge>;
        case 'Failed': 
            return <Badge variant="destructive"><XCircle className="h-3 w-3 mr-1" /> Failed</Badge>;
        default: 
            return <Badge variant="secondary" className="text-muted-foreground">Pending</Badge>;
    }
}
