import React, {useEffect, useState} from 'react';
import {BacktestClient} from '../../generated/ManagingApi';
import useApiUrlStore from '../../app/store/apiStore';
import Table from '../../components/mollecules/Table/Table';
import {BundleBacktestRequest} from '../../generated/ManagingApiTypes';
import Toast from '../../components/mollecules/Toast/Toast';
import BundleRequestModal from './BundleRequestModal';

const BundleRequestsTable = () => {
  const { apiUrl } = useApiUrlStore();
  const [data, setData] = useState<BundleBacktestRequest[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedBundle, setSelectedBundle] = useState<BundleBacktestRequest | null>(null);

  const fetchData = () => {
    setLoading(true);
    setError(null);
    const client = new BacktestClient({} as any, apiUrl);
    client.backtest_GetBundleBacktestRequests()
      .then((res) => setData(res))
      .catch((e) => setError(e.message || 'Failed to fetch bundle requests'))
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line
  }, [apiUrl]);

  const handleDelete = async (id: string) => {
    setDeletingId(id);
    const toast = new Toast('Deleting bundle request...', true);
    try {
      const client = new BacktestClient({} as any, apiUrl);
      await client.backtest_DeleteBundleBacktestRequest(id);
      toast.update('success', 'Bundle request deleted');
      fetchData();
    } catch (e: any) {
      toast.update('error', e.message || 'Failed to delete bundle request');
    } finally {
      setDeletingId(null);
    }
  };

  // Helper to get badge color
  const getStatusBadgeColor = (status: string) => {
    switch (status) {
      case 'Pending':
        return 'badge-warning';
      case 'Running':
        return 'badge-info';
      case 'Completed':
        return 'badge-success';
      case 'Failed':
        return 'badge-error';
      case 'Cancelled':
        return 'badge-neutral';
      default:
        return 'badge-neutral';
    }
  };

  const columns = [
    {
      Header: 'Request ID',
      accessor: 'requestId',
      Cell: ({ value }: { value: string }) => (
        <span className="font-mono text-xs cursor-pointer" title="Copy RequestId" onClick={() => {navigator.clipboard.writeText(value); new Toast('Copied RequestId!', false);}}>{value}</span>
      ),
    },
    {
      Header: 'Name',
      accessor: 'name',
    },
    {
      Header: 'Progress & Status',
      accessor: 'completedBacktests',
      Cell: ({ row }: any) => {
        const completed = row.original.completedBacktests || 0;
        const total = row.original.totalBacktests || 1;
        const failed = row.original.failedBacktests || 0;
        const status = row.original.status;
        const percent = Math.round((completed / total) * 100);
        // Progress color
        const getProgressColor = (p: number) => {
          if (status === 'Failed') return 'progress-error';
          if (status === 'Completed') return 'progress-success';
          if (p <= 25) return 'progress-error';
          if (p <= 50) return 'progress-warning';
          if (p <= 75) return 'progress-info';
          return 'progress-success';
        };
        return (
          <div className="flex flex-col gap-2">
            <div className="flex items-center justify-between">
              <span className={`badge badge-sm ${getStatusBadgeColor(status)}`}>{status}</span>
              <div className="text-xs">
                {completed} / {total} {failed > 0 && <span className="text-error ml-1">({failed} failed)</span>}
              </div>
            </div>
            <progress className={`progress w-40 ${getProgressColor(percent)}`} value={percent} max="100" />
          </div>
        );
      },
    },
    {
      Header: 'Created At',
      accessor: 'createdAt',
      Cell: ({ value }: { value: string }) => value ? new Date(value).toLocaleString() : '-',
    },
    {
      Header: 'Completed At',
      accessor: 'completedAt',
      Cell: ({ value }: { value: string }) => value ? new Date(value).toLocaleString() : '-',
    },
    {
      Header: 'Actions',
      accessor: 'actions',
      disableSortBy: true,
      Cell: ({ row }: any) => (
        <div className="flex gap-2">
          <button
            className="btn btn-xs btn-outline"
            onClick={() => {
              setSelectedBundle(row.original);
              setModalOpen(true);
            }}
          >
            View
          </button>
          <button
            className="btn btn-xs btn-error"
            onClick={() => handleDelete(row.original.requestId)}
            disabled={deletingId === row.original.requestId}
          >
            {deletingId === row.original.requestId ? 'Deleting...' : 'Delete'}
          </button>
        </div>
      ),
    },
  ];

  if (loading) return <div className="text-center">Loading bundle requests...</div>;
  if (error) return <div className="text-error">{error}</div>;

  return (
    <div className="w-full">
      <h2 className="text-lg font-bold mb-2">Bundle Backtest Requests</h2>
      <Table columns={columns} data={data} showPagination={true} />
      <BundleRequestModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        bundle={selectedBundle}
      />
    </div>
  );
};

export default BundleRequestsTable; 