import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { UploadDropzone } from '../../components/UploadDropzone/UploadDropzone';
import { VoiceSelector } from '../../components/VoiceSelector';
import { useCreateJob } from '../../hooks/useJob';
import { useToastContext } from '../../contexts/ToastContext';
import type { JobCreateRequest, TTSPreferences } from '../../types/api';

const jobSchema = z.object({
  title: z.string().min(1, 'Title is required'),
  sourceIsEnglish: z.boolean(),
  languageHint: z.string().optional(),
  captions_vtt: z.boolean(),
  audio_description_vtt: z.boolean(),
  audio_description_mp3: z.boolean(),
  languages: z.array(z.string()),
  transcreation: z.array(z.string()),
});

type JobFormData = z.infer<typeof jobSchema>;

export function NewJob() {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [createdJob, setCreatedJob] = useState<string | null>(null);
  const [showVoiceSettings, setShowVoiceSettings] = useState(false);
  const [ttsPreferences, setTtsPreferences] = useState<TTSPreferences>({
    provider: 'gemini',
    default_voice: 'Kore',
    voices_per_language: {},
    model: 'flash',
    speed: 1.0,
    style_preset: 'neutral',
    custom_style_prompt: undefined
  });
  const navigate = useNavigate();
  const toast = useToastContext();
  const createJobMutation = useCreateJob();

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors }
  } = useForm<JobFormData>({
    resolver: zodResolver(jobSchema),
    defaultValues: {
      sourceIsEnglish: true,
      languageHint: '',
      captions_vtt: true,
      audio_description_vtt: true,
      audio_description_mp3: true,
      languages: [],
      transcreation: [],
    }
  });

  const languages = watch('languages');
  const transcreation = watch('transcreation');
  const sourceIsEnglish = watch('sourceIsEnglish');
  const audioDescriptionMp3 = watch('audio_description_mp3');

  const onSubmit = async (data: JobFormData) => {
    if (!selectedFile) {
      toast.toastOnly.error('Please select a video file');
      return;
    }

    const jobData: JobCreateRequest = {
      title: data.title,
      source_is_english: data.sourceIsEnglish,
      language_hint: data.sourceIsEnglish ? undefined : data.languageHint || undefined,
      requested_outputs: {
        captions_vtt: data.captions_vtt,
        audio_description_vtt: data.audio_description_vtt,
        audio_description_mp3: data.audio_description_mp3,
        languages: data.languages,
        transcreation: data.transcreation,
        tts_preferences: data.audio_description_mp3 ? ttsPreferences : undefined,
      }
    };

    try {
      setUploadProgress(0);
      
      const job = await createJobMutation.mutateAsync({ 
        data: jobData, 
        file: selectedFile,
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          setUploadProgress(percentCompleted);
        }
      });
      
      setCreatedJob(job.id);
      
      // Auto-redirect after 3 seconds or when user clicks
      setTimeout(() => {
        if (createdJob) {
          navigate(`/jobs/${job.id}`);
        }
      }, 3000);
    } catch (error) {
      console.error('Job creation failed:', error);

      // Provide specific error messages based on error type
      const err = error as any;
      let errorMessage = 'Failed to create job. ';

      if (err.code === 'ERR_NETWORK') {
        errorMessage += 'Network error - cannot reach server. Please check your connection.';
      } else if (err.code === 'ECONNABORTED' || err.message?.includes('timeout')) {
        errorMessage += 'Upload timeout. Your file may be too large or connection too slow.';
      } else if (err.response?.status === 413) {
        errorMessage += 'File is too large. Maximum file size is 500MB.';
      } else if (err.response?.status === 400) {
        const detail = err.response?.data?.detail;
        if (detail?.includes('video')) {
          errorMessage += 'Invalid file type. Please upload a video file (MP4, MOV, etc).';
        } else {
          errorMessage += detail || 'Invalid request data. Please check all fields.';
        }
      } else if (err.response?.status === 401) {
        errorMessage += 'Session expired. Please log in again.';
      } else if (err.response?.status === 403) {
        errorMessage += 'You do not have permission to create jobs.';
      } else if (err.response?.status === 500) {
        errorMessage += 'Server error. Please try again or contact support.';
      } else if (err.message) {
        errorMessage += err.message;
      } else {
        errorMessage += 'Unknown error. Please try again.';
      }

      toast.toastOnly.error(errorMessage);
      setUploadProgress(0);
    }
  };

  const addLanguage = (lang: string) => {
    if (!languages.includes(lang)) {
      setValue('languages', [...languages, lang]);
    }
  };

  const removeLanguage = (lang: string) => {
    setValue('languages', languages.filter(l => l !== lang));
    setValue('transcreation', transcreation.filter(l => l !== lang));
  };

  // Removed toggleTranscreation - not currently used

  // Success state
  if (createdJob) {
    return (
      <div className="container mx-auto px-4 py-8 max-w-2xl">
        <div className="text-center py-12">
          <div className="mx-auto flex items-center justify-center w-16 h-16 bg-green-100 rounded-full mb-4">
            <svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mb-2">Job Created Successfully!</h1>
          <p className="text-gray-600 mb-6">
            Your video has been uploaded and processing will begin shortly.
          </p>
          <div className="space-y-3">
            <button
              onClick={() => navigate(`/jobs/${createdJob}`)}
              className="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
            >
              View Job Details
              <svg className="ml-2 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </button>
            <div>
              <button
                onClick={() => {
                  setCreatedJob(null);
                  setSelectedFile(null);
                  setUploadProgress(0);
                }}
                className="text-gray-600 hover:text-gray-800"
              >
                Create Another Job
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8 max-w-2xl">
      <h1 className="text-3xl font-bold text-gray-900 mb-8">Create New Job</h1>
      
      {/* Progress Bar */}
      {createJobMutation.isPending && (
        <div className="mb-6 bg-white border border-gray-200 rounded-lg p-4">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-gray-700">Uploading...</span>
            <span className="text-sm text-gray-500">{uploadProgress}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div 
              className="bg-blue-600 h-2 rounded-full transition-all duration-300"
              style={{ width: `${uploadProgress}%` }}
            />
          </div>
        </div>
      )}
      
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
        {/* Video Upload */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Video File
          </label>
          <UploadDropzone
            onFileSelect={setSelectedFile}
            disabled={createJobMutation.isPending}
          />
          {selectedFile && (
            <p className="mt-2 text-sm text-gray-600">
              Selected: {selectedFile.name} ({Math.round(selectedFile.size / (1024 * 1024))}MB)
            </p>
          )}
        </div>

        {/* Job Title */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Job Title
          </label>
          <input
            type="text"
            {...register('title')}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="Enter a descriptive title for this video"
          />
          {errors.title && (
            <p className="mt-1 text-sm text-red-600">{errors.title.message}</p>
          )}
        </div>

        {/* Original Video Language */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Original Video Language
          </label>
          <div className="space-y-2">
            <label className="flex items-center">
              <input
                type="radio"
                name="sourceIsEnglish"
                checked={sourceIsEnglish === true}
                onChange={() => setValue('sourceIsEnglish', true)}
                className="mr-2"
              />
              <span>English</span>
            </label>
            <label className="flex items-center">
              <input
                type="radio"
                name="sourceIsEnglish"
                checked={sourceIsEnglish === false}
                onChange={() => setValue('sourceIsEnglish', false)}
                className="mr-2"
              />
              <span>Different language (auto-detect)</span>
            </label>
          </div>
        </div>

        {/* Language Hint - only shown when "Different language" is selected */}
        {!sourceIsEnglish && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Language Hint
              <span className="text-gray-500 font-normal ml-1">(optional - helps improve detection accuracy)</span>
            </label>
            <select
              {...register('languageHint')}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">Auto-detect (no hint)</option>
              <option value="es">Spanish</option>
              <option value="fr">French</option>
              <option value="de">German</option>
              <option value="pt">Portuguese</option>
              <option value="it">Italian</option>
              <option value="ja">Japanese</option>
              <option value="zh">Chinese</option>
              <option value="ko">Korean</option>
              <option value="ar">Arabic</option>
              <option value="ru">Russian</option>
              <option value="nl">Dutch</option>
            </select>
          </div>
        )}

        {/* Requested Outputs */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Requested Outputs
          </label>
          <div className="space-y-2">
            <label className="flex items-center">
              <input
                type="checkbox"
                {...register('captions_vtt')}
                className="mr-2"
              />
              <span>Closed Captions (VTT)</span>
            </label>
            <label className="flex items-center">
              <input
                type="checkbox"
                {...register('audio_description_vtt')}
                className="mr-2"
              />
              <span>Audio Description Script (VTT)</span>
            </label>
            <label className="flex items-center">
              <input
                type="checkbox"
                {...register('audio_description_mp3')}
                className="mr-2"
              />
              <span>Audio Description Voiceover (MP3)</span>
            </label>
          </div>
        </div>

        {/* Voice Settings - Collapsible */}
        {audioDescriptionMp3 && (
          <div className="border border-gray-200 rounded-lg overflow-hidden">
            <button
              type="button"
              onClick={() => setShowVoiceSettings(!showVoiceSettings)}
              className="w-full flex items-center justify-between px-4 py-3 bg-gray-50 hover:bg-gray-100 transition-colors"
            >
              <div className="flex items-center gap-2">
                <svg
                  className={`w-4 h-4 text-gray-500 transition-transform ${showVoiceSettings ? 'rotate-90' : ''}`}
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
                <span className="text-sm font-medium text-gray-700">Voice Settings</span>
              </div>
              <span className="text-xs text-gray-500">
                {showVoiceSettings ? 'Click to collapse' : 'Click to customize TTS voice'}
              </span>
            </button>
            {showVoiceSettings && (
              <div className="p-4 border-t border-gray-200">
                <VoiceSelector
                  selectedLanguages={['en', ...languages]}
                  preferences={ttsPreferences}
                  onChange={setTtsPreferences}
                  disabled={createJobMutation.isPending}
                />
              </div>
            )}
          </div>
        )}

        {/* Target Languages */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Target Languages
          </label>
          <div className="flex flex-wrap gap-2 mb-2">
            {languages.map(lang => (
              <span key={lang} className="bg-blue-100 text-blue-800 px-2 py-1 rounded-md text-sm flex items-center">
                {lang}
                <button
                  type="button"
                  onClick={() => removeLanguage(lang)}
                  className="ml-1 text-blue-600 hover:text-blue-800"
                >
                  ×
                </button>
              </span>
            ))}
          </div>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => addLanguage('es')}
              className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50"
            >
              + Spanish
            </button>
            <button
              type="button"
              onClick={() => addLanguage('fr')}
              className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50"
            >
              + French
            </button>
            <button
              type="button"
              onClick={() => addLanguage('de')}
              className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50"
            >
              + German
            </button>
          </div>
        </div>

        {/* Transcreation Options - HIDDEN: Not fully implemented */}
        {/* {languages.length > 0 && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Transcreation (Cultural Adaptation)
            </label>
            <p className="text-sm text-gray-500 mb-2">
              Select languages that need cultural adaptation instead of direct translation
            </p>
            <div className="space-y-2">
              {languages.map(lang => (
                <label key={lang} className="flex items-center">
                  <input
                    type="checkbox"
                    checked={transcreation.includes(lang)}
                    onChange={() => toggleTranscreation(lang)}
                    className="mr-2"
                  />
                  <span>Transcreate to {lang}</span>
                </label>
              ))}
            </div>
          </div>
        )} */}

        {/* Submit Button */}
        <div className="pt-4">
          <button
            type="submit"
            disabled={!selectedFile || createJobMutation.isPending}
            className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {createJobMutation.isPending ? 'Creating Job...' : 'Create Job'}
          </button>
        </div>
      </form>
    </div>
  );
}