import { useState } from 'react';
import type { Run } from '../services/backtestApiV2';
import {
  PlayIcon,
  PauseIcon,
  StopIcon,
  ForwardIcon,
  BackwardIcon,
} from '@heroicons/react/24/solid';

interface RunControlsProps {
  run: Run;
  onPause: () => void;
  onResume: () => void;
  onCancel: () => void;
  onSpeedChange: (speed: number) => void;
}

export function RunControls({
  run,
  onPause,
  onResume,
  onCancel,
  onSpeedChange,
}: RunControlsProps) {
  const [speedMultiplier, setSpeedMultiplier] = useState(run.speedMultiplier);

  const handleSpeedChange = (speed: number) => {
    setSpeedMultiplier(speed);
    onSpeedChange(speed);
  };

  const speedOptions = [
    { value: 0.1, label: '0.1x' },
    { value: 0.5, label: '0.5x' },
    { value: 1, label: '1x' },
    { value: 2, label: '2x' },
    { value: 5, label: '5x' },
    { value: 10, label: '10x' },
    { value: 50, label: '50x' },
    { value: 100, label: '100x' },
    { value: 1000, label: 'Max' },
  ];

  const formatDate = (date?: string) => {
    if (!date) return '-';
    return new Date(date).toLocaleString();
  };

  const formatDuration = () => {
    if (!run.startedAt) return '00:00';
    const start = new Date(run.startedAt).getTime();
    const current = Date.now();
    const duration = current - start;
    
    const seconds = Math.floor(duration / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    
    if (hours > 0) {
      return `${hours.toString().padStart(2, '0')}:${(minutes % 60).toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
    } else {
      return `${minutes.toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
    }
  };

  return (
    <div className="bg-surface-secondary rounded-lg border border-border p-4">
      <h3 className="text-base font-medium text-text-primary mb-4">Run Control</h3>
      
      <div className="space-y-4">
        {/* Progress Bar */}
        <div>
          <div className="flex justify-between text-sm text-text-secondary mb-1">
            <span>Progress</span>
            <span>{run.progress.toFixed(1)}%</span>
          </div>
          <div className="w-full bg-background rounded-full h-3 overflow-hidden">
            <div
              className="bg-primary-500 h-3 transition-all duration-300 relative"
              style={{ width: `${run.progress}%` }}
            >
              <div className="absolute inset-0 bg-gradient-to-r from-primary-500 to-primary-400 opacity-50"></div>
            </div>
          </div>
        </div>

        {/* Control Buttons */}
        <div className="flex items-center space-x-2">
          {run.status === 'running' ? (
            <button
              onClick={onPause}
              className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-warning text-white rounded-md text-sm font-medium hover:bg-warning/90 transition-colors"
            >
              <PauseIcon className="w-4 h-4" />
              Pause
            </button>
          ) : run.status === 'paused' ? (
            <button
              onClick={onResume}
              className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-success text-white rounded-md text-sm font-medium hover:bg-success/90 transition-colors"
            >
              <PlayIcon className="w-4 h-4" />
              Resume
            </button>
          ) : null}

          {(run.status === 'running' || run.status === 'paused') && (
            <button
              onClick={onCancel}
              className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-error text-white rounded-md text-sm font-medium hover:bg-error/90 transition-colors"
            >
              <StopIcon className="w-4 h-4" />
              Cancel
            </button>
          )}
        </div>

        {/* Speed Control */}
        {run.status === 'running' && (
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-2">
              Playback Speed
            </label>
            <div className="flex items-center space-x-2">
              <button
                onClick={() => {
                  const currentIndex = speedOptions.findIndex(s => s.value === speedMultiplier);
                  if (currentIndex > 0) {
                    handleSpeedChange(speedOptions[currentIndex - 1].value);
                  }
                }}
                className="p-1 rounded hover:bg-surface-tertiary transition-colors"
                disabled={speedMultiplier <= 0.1}
              >
                <BackwardIcon className="w-4 h-4 text-text-secondary" />
              </button>
              
              <select
                value={speedMultiplier}
                onChange={(e) => handleSpeedChange(parseFloat(e.target.value))}
                className="flex-1 px-3 py-1.5 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
              >
                {speedOptions.map(option => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
              
              <button
                onClick={() => {
                  const currentIndex = speedOptions.findIndex(s => s.value === speedMultiplier);
                  if (currentIndex < speedOptions.length - 1) {
                    handleSpeedChange(speedOptions[currentIndex + 1].value);
                  }
                }}
                className="p-1 rounded hover:bg-surface-tertiary transition-colors"
                disabled={speedMultiplier >= 1000}
              >
                <ForwardIcon className="w-4 h-4 text-text-secondary" />
              </button>
            </div>
          </div>
        )}

        {/* Run Info */}
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div>
            <span className="text-text-secondary">Status:</span>
            <span className="ml-2 text-text-primary font-medium">
              {run.status.charAt(0).toUpperCase() + run.status.slice(1)}
            </span>
          </div>
          <div>
            <span className="text-text-secondary">Duration:</span>
            <span className="ml-2 text-text-primary font-medium">
              {formatDuration()}
            </span>
          </div>
          {run.currentSimulationDate && (
            <div className="col-span-2">
              <span className="text-text-secondary">Current Date:</span>
              <span className="ml-2 text-text-primary font-medium">
                {formatDate(run.currentSimulationDate)}
              </span>
            </div>
          )}
          {run.error && (
            <div className="col-span-2">
              <span className="text-text-secondary">Error:</span>
              <span className="ml-2 text-error text-xs">
                {run.error}
              </span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}