'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Button from '../ui/Button';
import Input from '../ui/Input';
import { createScheduleRaceFormPresenter } from '@/lib/presenters/factories';
import type {
  ScheduleRaceFormData,
  ScheduledRaceViewModel,
  LeagueOptionViewModel,
} from '@/lib/presenters/ScheduleRaceFormPresenter';

interface ScheduleRaceFormProps {
  preSelectedLeagueId?: string;
  onSuccess?: (race: ScheduledRaceViewModel) => void;
  onCancel?: () => void;
}

export default function ScheduleRaceForm({
  preSelectedLeagueId,
  onSuccess,
  onCancel
}: ScheduleRaceFormProps) {
  const router = useRouter();
  const [leagues, setLeagues] = useState<LeagueOptionViewModel[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [formData, setFormData] = useState<ScheduleRaceFormData>({
    leagueId: preSelectedLeagueId || '',
    track: '',
    car: '',
    sessionType: 'race',
    scheduledDate: '',
    scheduledTime: '',
  });

  const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    const loadLeagues = async () => {
      const allLeagues = await loadScheduleRaceFormLeagues();
      setLeagues(allLeagues);
    };
    void loadLeagues();
  }, []);

  const validateForm = (): boolean => {
    const errors: Record<string, string> = {};

    if (!formData.leagueId) {
      errors.leagueId = 'League is required';
    }

    if (!formData.track.trim()) {
      errors.track = 'Track is required';
    }

    if (!formData.car.trim()) {
      errors.car = 'Car is required';
    }

    if (!formData.scheduledDate) {
      errors.scheduledDate = 'Date is required';
    }

    if (!formData.scheduledTime) {
      errors.scheduledTime = 'Time is required';
    }

    // Validate future date
    if (formData.scheduledDate && formData.scheduledTime) {
      const scheduledDateTime = new Date(`${formData.scheduledDate}T${formData.scheduledTime}`);
      const now = new Date();
      
      if (scheduledDateTime <= now) {
        errors.scheduledDate = 'Date must be in the future';
      }
    }

    setValidationErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const createdRace = await scheduleRaceFromForm(formData);

      if (onSuccess) {
        onSuccess(createdRace);
      } else {
        router.push(`/races/${createdRace.id}`);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create race');
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // Clear validation error for this field
    if (validationErrors[field]) {
      setValidationErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit} className="space-y-6">
        {error && (
        <div className="p-4 rounded-lg bg-red-500/10 border border-red-500/30 text-red-400">
          {error}
        </div>
      )}

      {/* Companion App Notice */}
      <div className="p-4 rounded-lg bg-iron-gray border border-charcoal-outline">
        <div className="flex items-start gap-3">
          <div className="flex items-center gap-2 flex-1">
            <input
              type="checkbox"
              disabled
              className="w-4 h-4 rounded border-charcoal-outline bg-deep-graphite text-primary-blue opacity-50 cursor-not-allowed"
            />
            <label className="text-sm text-gray-400">
              Use Companion App
            </label>
            <button
              type="button"
              className="text-gray-500 hover:text-gray-400 transition-colors"
              title="Companion automation available in production. For alpha, races are created manually."
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </button>
          </div>
        </div>
        <p className="text-xs text-gray-500 mt-2 ml-6">
          Companion automation available in production. For alpha, races are created manually.
        </p>
      </div>

      {/* League Selection */}
      <div>
        <label className="block text-sm font-medium text-gray-300 mb-2">
          League *
        </label>
        <select
          value={formData.leagueId}
          onChange={(e) => handleChange('leagueId', e.target.value)}
          disabled={!!preSelectedLeagueId}
          className={`
            w-full px-4 py-2 bg-deep-graphite border rounded-lg text-white
            focus:outline-none focus:ring-2 focus:ring-primary-blue
            disabled:opacity-50 disabled:cursor-not-allowed
            ${validationErrors.leagueId ? 'border-red-500' : 'border-charcoal-outline'}
          `}
        >
          <option value="">Select a league</option>
          {leagues.map((league: LeagueOptionViewModel) => (
            <option key={league.id} value={league.id}>
              {league.name}
            </option>
          ))}
        </select>
        {validationErrors.leagueId && (
          <p className="mt-1 text-sm text-red-400">{validationErrors.leagueId}</p>
        )}
      </div>

      {/* Track */}
      <div>
        <label className="block text-sm font-medium text-gray-300 mb-2">
          Track *
        </label>
        <Input
          type="text"
          value={formData.track}
          onChange={(e) => handleChange('track', e.target.value)}
          placeholder="e.g., Spa-Francorchamps"
          className={validationErrors.track ? 'border-red-500' : ''}
        />
        {validationErrors.track && (
          <p className="mt-1 text-sm text-red-400">{validationErrors.track}</p>
        )}
        <p className="mt-1 text-xs text-gray-500">Enter the iRacing track name</p>
      </div>

      {/* Car */}
      <div>
        <label className="block text-sm font-medium text-gray-300 mb-2">
          Car *
        </label>
        <Input
          type="text"
          value={formData.car}
          onChange={(e) => handleChange('car', e.target.value)}
          placeholder="e.g., Porsche 911 GT3 R"
          className={validationErrors.car ? 'border-red-500' : ''}
        />
        {validationErrors.car && (
          <p className="mt-1 text-sm text-red-400">{validationErrors.car}</p>
        )}
        <p className="mt-1 text-xs text-gray-500">Enter the iRacing car name</p>
      </div>

      {/* Session Type */}
      <div>
        <label className="block text-sm font-medium text-gray-300 mb-2">
          Session Type *
        </label>
        <select
          value={formData.sessionType}
          onChange={(e) => handleChange('sessionType', e.target.value)}
          className="w-full px-4 py-2 bg-deep-graphite border border-charcoal-outline rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary-blue"
        >
          <option value="practice">Practice</option>
          <option value="qualifying">Qualifying</option>
          <option value="race">Race</option>
        </select>
      </div>

      {/* Date and Time */}
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-2">
            Date *
          </label>
          <Input
            type="date"
            value={formData.scheduledDate}
            onChange={(e) => handleChange('scheduledDate', e.target.value)}
            className={validationErrors.scheduledDate ? 'border-red-500' : ''}
          />
          {validationErrors.scheduledDate && (
            <p className="mt-1 text-sm text-red-400">{validationErrors.scheduledDate}</p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-300 mb-2">
            Time *
          </label>
          <Input
            type="time"
            value={formData.scheduledTime}
            onChange={(e) => handleChange('scheduledTime', e.target.value)}
            className={validationErrors.scheduledTime ? 'border-red-500' : ''}
          />
          {validationErrors.scheduledTime && (
            <p className="mt-1 text-sm text-red-400">{validationErrors.scheduledTime}</p>
          )}
        </div>
      </div>

      {/* Actions */}
      <div className="flex gap-3">
        <Button
          type="submit"
          variant="primary"
          disabled={loading}
          className="flex-1"
        >
          {loading ? 'Creating...' : 'Schedule Race'}
        </Button>
        
        {onCancel && (
          <Button
            type="button"
            variant="secondary"
            onClick={onCancel}
            disabled={loading}
          >
            Cancel
          </Button>
        )}
        </div>
      </form>
    </>
  );
}