import { DataTable } from '@/components/ui/DataTable';
import type { ColumnDef } from '@tanstack/react-table';
import type { Run, RunResult } from '../services/backtestApiV2';
import { useNavigate, useParams } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { backtestApiV2 } from '../services/backtestApiV2';
import {
  CheckCircleIcon,
  XCircleIcon,
  PauseIcon,
  PlayIcon,
  ClockIcon,
} from '@heroicons/react/24/outline';

interface RunsListProps {
  runs: Run[];
  currentRunId?: string;
  onSelectRun: (runId: string) => void;
}

interface RunWithMetrics extends Run {
  metrics?: RunResult['metrics'];
  initialCapital?: number;
}

export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsListProps) {
  const navigate = useNavigate();
  const { id: backtestId } = useParams<{ id: string }>();
  const [runsWithMetrics, setRunsWithMetrics] = useState<RunWithMetrics[]>([]);
  const [loadingMetrics, setLoadingMetrics] = useState(false);
  
  // Fetch metrics for completed runs
  useEffect(() => {
    const fetchMetrics = async () => {
      setLoadingMetrics(true);
      const updatedRuns: RunWithMetrics[] = await Promise.all(
        runs.map(async (run) => {
          if (run.status === 'completed') {
            try {
              const results = await backtestApiV2.getRunResults(run.id);
              return { 
                ...run, 
                metrics: results.metrics,
                initialCapital: results.config?.initialCapital 
              };
            } catch (error) {
              console.error(`Failed to fetch metrics for run ${run.id}:`, error);
              return run;
            }
          }
          return run;
        })
      );
      setRunsWithMetrics(updatedRuns);
      setLoadingMetrics(false);
    };

    if (runs.length > 0) {
      fetchMetrics();
    }
  }, [runs]);
  
  const getStatusIcon = (status: Run['status']) => {
    switch (status) {
      case 'completed':
        return <CheckCircleIcon className="w-4 h-4 text-success" />;
      case 'failed':
        return <XCircleIcon className="w-4 h-4 text-error" />;
      case 'cancelled':
        return <XCircleIcon className="w-4 h-4 text-text-secondary" />;
      case 'running':
        return <PlayIcon className="w-4 h-4 text-primary-500" />;
      case 'paused':
        return <PauseIcon className="w-4 h-4 text-warning" />;
      case 'pending':
        return <ClockIcon className="w-4 h-4 text-text-secondary" />;
    }
  };

  const getStatusLabel = (status: Run['status']) => {
    return status.charAt(0).toUpperCase() + status.slice(1);
  };

  const formatPercentage = (value: number | undefined, decimals = 2) => {
    if (value === undefined || value === null) return '-';
    return `${(value * 100).toFixed(decimals)}%`;
  };

  const formatNumber = (value: number | undefined, decimals = 2) => {
    if (value === undefined || value === null) return '-';
    return value.toFixed(decimals);
  };

  const formatCurrency = (value: number | undefined) => {
    if (value === undefined || value === null) return '-';
    const prefix = value < 0 ? '-$' : '$';
    return `${prefix}${Math.abs(value).toFixed(2)}`;
  };

  const columns: ColumnDef<RunWithMetrics>[] = [
    {
      accessorKey: 'runNumber',
      header: 'Run #',
      size: 60,
      cell: ({ getValue, row }) => (
        <span className={`text-sm font-medium ${row.original.id === currentRunId ? 'text-primary-500' : 'text-text-primary'}`}>
          #{getValue() as number}
        </span>
      ),
    },
    {
      accessorKey: 'status',
      header: 'Status',
      size: 100,
      cell: ({ getValue }) => {
        const status = getValue() as Run['status'];
        return (
          <div className="flex items-center space-x-2">
            {getStatusIcon(status)}
            <span className="text-sm text-text-primary">{getStatusLabel(status)}</span>
          </div>
        );
      },
    },
    {
      accessorKey: 'progress',
      header: 'Progress',
      size: 120,
      cell: ({ row }) => {
        const progress = row.original.progress;
        const status = row.original.status;
        
        if (status === 'pending') return <span className="text-sm text-text-secondary">-</span>;
        if (status === 'completed') return <span className="text-sm text-success">Complete</span>;
        
        return (
          <div className="flex items-center space-x-2">
            <div className="flex-1 bg-surface-tertiary rounded-full h-2 overflow-hidden">
              <div
                className="bg-primary-500 h-2 transition-all duration-300"
                style={{ width: `${progress}%` }}
              />
            </div>
            <span className="text-xs text-text-secondary">{progress.toFixed(0)}%</span>
          </div>
        );
      },
    },
    {
      id: 'totalReturn',
      header: 'Return',
      size: 80,
      cell: ({ row }) => {
        const metrics = row.original.metrics;
        const value = metrics?.totalReturn;
        return (
          <span className={`text-sm font-medium ${
            value === undefined ? 'text-text-secondary' : 
            value >= 0 ? 'text-success' : 'text-error'
          }`}>
            {formatPercentage(value)}
          </span>
        );
      },
    },
    {
      id: 'sharpeRatio',
      header: 'Sharpe',
      size: 80,
      cell: ({ row }) => {
        const metrics = row.original.metrics;
        const value = metrics?.sharpeRatio;
        return (
          <span className={`text-sm font-medium ${
            value === undefined ? 'text-text-secondary' :
            value > 1 ? 'text-success' : 
            value > 0 ? 'text-warning' : 'text-error'
          }`}>
            {formatNumber(value)}
          </span>
        );
      },
    },
    {
      id: 'maxDrawdown',
      header: 'Max DD',
      size: 80,
      cell: ({ row }) => {
        const metrics = row.original.metrics;
        const value = metrics?.maxDrawdown;
        return (
          <span className={`text-sm font-medium ${
            value === undefined ? 'text-text-secondary' :
            value > -0.1 ? 'text-success' :
            value > -0.2 ? 'text-warning' : 'text-error'
          }`}>
            {formatPercentage(value)}
          </span>
        );
      },
    },
    {
      id: 'winRate',
      header: 'Win Rate',
      size: 80,
      cell: ({ row }) => {
        const metrics = row.original.metrics;
        const value = metrics?.winRate;
        return (
          <span className={`text-sm font-medium ${
            value === undefined ? 'text-text-secondary' :
            value > 0.5 ? 'text-success' : 'text-warning'
          }`}>
            {formatPercentage(value, 1)}
          </span>
        );
      },
    },
    {
      id: 'profitFactor',
      header: 'Profit Factor',
      size: 100,
      cell: ({ row }) => {
        const metrics = row.original.metrics;
        const value = metrics?.profitFactor;
        return (
          <span className={`text-sm font-medium ${
            value === undefined ? 'text-text-secondary' :
            value > 1.5 ? 'text-success' :
            value > 1 ? 'text-warning' : 'text-error'
          }`}>
            {formatNumber(value)}
          </span>
        );
      },
    },
    {
      id: 'totalProfit',
      header: 'Total Profit',
      size: 100,
      cell: ({ row }) => {
        const metrics = row.original.metrics;
        const value = metrics?.totalProfit;
        return (
          <span className={`text-sm font-medium ${
            value === undefined ? 'text-text-secondary' :
            value >= 0 ? 'text-success' : 'text-error'
          }`}>
            {formatCurrency(value)}
          </span>
        );
      },
    },
    {
      accessorKey: 'startedAt',
      header: 'Started',
      size: 160,
      cell: ({ getValue }) => {
        const date = getValue() as string | undefined;
        return (
          <span className="text-sm text-text-secondary">
            {date ? new Date(date).toLocaleString() : '-'}
          </span>
        );
      },
    },
  ];

  if (runs.length === 0) {
    return (
      <div className="bg-surface-secondary rounded-lg border border-border p-8 text-center">
        <p className="text-text-secondary">No runs yet. Create a new run to get started.</p>
      </div>
    );
  }

  return (
    <DataTable
      data={runsWithMetrics}
      columns={columns}
      onRowClick={(run) => {
        navigate(`/backtests/${backtestId}/run/${run.id}`);
        onSelectRun(run.id);
      }}
      className="bg-surface-secondary rounded-lg border border-border"
      height={400}
      loading={loadingMetrics}
    />
  );
}