import React from 'react';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { Info } from 'lucide-react';
import { TaskStatus } from '@/types/workflow';
import { TaskInfo } from '@/hooks/useWorkflow';

interface FundamentalDataViewProps {
  taskStates: Record<string, TaskStatus>;
  taskInfos: Record<string, TaskInfo>;
  taskOutputs: Record<string, string>;
}

export function FundamentalDataView({ taskStates, taskInfos, taskOutputs }: FundamentalDataViewProps) {
  console.log('[FundamentalDataView] Render. States:', Object.keys(taskStates).length, taskStates);
  
  // Filter tasks that look like data fetching tasks
  const dataTasks = Object.keys(taskStates).filter(taskId => 
    taskId.startsWith('fetch:') // Standardized task ID format: "fetch:provider_id"
  );

  if (dataTasks.length === 0) {
    return (
      <div className="text-center p-8 text-muted-foreground">
        No data providers detected in this workflow.
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      {dataTasks.map(taskId => {
        const status = taskStates[taskId];
        const output = taskOutputs[taskId];
        const info = taskInfos[taskId];
        
        // Dynamic name resolution: extract provider ID from task ID (e.g., "fetch:tushare" -> "Tushare")
        const providerId = taskId.replace('fetch:', '');
        const providerName = providerId.charAt(0).toUpperCase() + providerId.slice(1);

        return (
          <Card key={taskId} className="flex flex-col h-[400px]">
            <CardHeader className="pb-2 flex flex-row items-center justify-between space-y-0">
              <CardTitle className="text-lg font-medium truncate" title={providerName}>
                {providerName}
              </CardTitle>
              <StatusBadge status={status} message={info?.message} />
            </CardHeader>
            <CardContent className="flex-1 min-h-0 pt-2">
              <ScrollArea className="h-full w-full border rounded-md bg-muted/5 p-4">
                {status === 'Failed' && info?.message ? (
                    <div className="text-sm text-red-500 whitespace-pre-wrap break-words">
                        <p className="font-semibold mb-1">Error:</p>
                        {info.message}
                    </div>
                ) : output ? (
                  <pre className="text-xs font-mono whitespace-pre-wrap break-words text-foreground/80">
                    {tryFormatJson(output)}
                  </pre>
                ) : (
                  <div className="flex items-center justify-center h-full text-muted-foreground text-sm italic">
                    {status === 'Pending' || status === 'Running' || status === 'Scheduled' ? 'Waiting for data...' : 'No data returned'}
                  </div>
                )}
              </ScrollArea>
            </CardContent>
          </Card>
        );
      })}
    </div>
  );
}

function StatusBadge({ status, message }: { status: TaskStatus, message?: string }) {
    let badge = <Badge variant="outline">Pending</Badge>;

    switch (status) {
      case 'Completed':
        badge = <Badge variant="default" className="bg-green-600 hover:bg-green-700">Success</Badge>;
        break;
      case 'Failed':
        badge = <Badge variant="destructive">Failed</Badge>;
        break;
      case 'Running':
        badge = <Badge variant="secondary" className="animate-pulse text-blue-500">Fetching</Badge>;
        break;
      case 'Scheduled':
        badge = <Badge variant="outline" className="text-yellow-600 border-yellow-200 bg-yellow-50">Scheduled</Badge>;
        break;
      case 'Skipped':
        badge = <Badge variant="outline" className="text-gray-500">Skipped</Badge>;
        break;
      default:
        badge = <Badge variant="outline">{status}</Badge>;
    }

    if (message) {
      return (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <div className="flex items-center gap-2 cursor-help">
                {badge}
                <Info className="w-4 h-4 text-muted-foreground" />
              </div>
            </TooltipTrigger>
            <TooltipContent className="max-w-xs">
              <p>{message}</p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      );
    }

    return badge;
}

function tryFormatJson(str: string): string {
  try {
    // Only try to format if it looks like JSON object or array
    const trimmed = str.trim();
    if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || 
        (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
      const obj = JSON.parse(str);
      return JSON.stringify(obj, null, 2);
    }
    return str;
  } catch (e) {
    return str;
  }
}
