import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { DataTable } from '@/components/ui/DataTable/DataTable';
import type { ColumnDef } from '@tanstack/react-table';
import { PlusIcon } from '@heroicons/react/24/solid';
import { backtestApiV2, type Backtest } from './services/backtestApiV2';
import { CreateBacktestDialog } from './components/CreateBacktestDialog';

export function BacktestListPageV2() {
  const navigate = useNavigate();
  const [backtests, setBacktests] = useState<Backtest[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showCreateDialog, setShowCreateDialog] = useState(false);

  const loadBacktests = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const data = await backtestApiV2.listBacktests();
      setBacktests(data);
    } catch (err) {
      setError('Failed to load backtests');
      console.error(err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadBacktests();
  }, []);

  const handleCreateBacktest = async (config: Omit<Backtest, 'id' | 'createdAt' | 'updatedAt'>) => {
    try {
      const newBacktest = await backtestApiV2.createBacktest(config);
      await loadBacktests();
      setShowCreateDialog(false);
      navigate(`/backtests/${newBacktest.id}`);
    } catch (err) {
      setError('Failed to create backtest');
      console.error(err);
    }
  };

  const columns: ColumnDef<Backtest>[] = [
    {
      accessorKey: 'name',
      header: 'Name',
      size: 200,
      cell: ({ row }) => (
        <div className="font-medium text-text-primary">
          {row.original.name}
        </div>
      ),
    },
    {
      accessorKey: 'strategy',
      header: 'Strategy',
      size: 150,
      cell: ({ row }) => (
        <span className="capitalize text-text-primary">
          {row.original.strategy}
        </span>
      ),
    },
    {
      accessorKey: 'symbols',
      header: 'Symbols',
      size: 200,
      cell: ({ row }) => (
        <div className="text-sm text-text-secondary">
          {row.original.symbols.join(', ')}
        </div>
      ),
    },
    {
      accessorKey: 'dateRange',
      header: 'Date Range',
      size: 200,
      cell: ({ row }) => (
        <div className="text-sm text-text-secondary">
          {new Date(row.original.startDate).toLocaleDateString()} - {new Date(row.original.endDate).toLocaleDateString()}
        </div>
      ),
    },
    {
      accessorKey: 'initialCapital',
      header: 'Initial Capital',
      size: 150,
      cell: ({ row }) => (
        <div className="text-sm text-text-primary font-mono">
          ${row.original.initialCapital.toLocaleString()}
        </div>
      ),
    },
    {
      accessorKey: 'createdAt',
      header: 'Created',
      size: 180,
      cell: ({ row }) => (
        <div className="text-sm text-text-secondary">
          {new Date(row.original.createdAt).toLocaleString()}
        </div>
      ),
    },
  ];

  return (
    <div className="flex flex-col h-full space-y-6">
      <div className="flex-shrink-0 flex justify-between items-center">
        <div>
          <h1 className="text-lg font-bold text-text-primary mb-2">Backtests</h1>
          <p className="text-text-secondary text-sm">
            Create and manage backtest configurations
          </p>
        </div>
        <button
          onClick={() => setShowCreateDialog(true)}
          className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors flex items-center space-x-2"
        >
          <PlusIcon className="w-4 h-4" />
          <span>New Backtest</span>
        </button>
      </div>

      {error && (
        <div className="bg-error/10 border border-error text-error px-4 py-3 rounded-lg text-sm">
          {error}
        </div>
      )}

      <div className="flex-1 min-h-0">
        <DataTable
          data={backtests}
          columns={columns}
          loading={isLoading}
          onRowClick={(row) => navigate(`/backtests/${row.id}`)}
          height={600}
        />
      </div>

      {showCreateDialog && (
        <CreateBacktestDialog
          onClose={() => setShowCreateDialog(false)}
          onCreate={handleCreateBacktest}
        />
      )}
    </div>
  );
}