import { useState, useEffect } from 'react';
import { useNavigate, Link, useSearchParams } 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 { LanguageSelector } from '../../components/LanguageSelector';
import { MultiUploadFileList } from '../../components/MultiUploadFileList';
import { UploadProgressList } from '../../components/UploadProgressList';
import { useCreateJob, useBrief } from '../../hooks/useJob';
import { useMultiUpload } from '../../hooks/useMultiUpload';
import { useToastContext } from '../../contexts/ToastContext';
import { generateTitleFromFilename } from '../../lib/fileUtils';
import { useClients, useProjects, useCreateProject } from '../../hooks/useClients';
import { useUsers } from '../../hooks/useUsers';
import type { JobCreateRequest, TTSPreferences, AccessibleVideoMethod } from '../../types/api';

const jobSchema = z.object({
  title: z.string().optional(), // Optional - only required for single-file mode, validated manually
  captions_vtt: z.boolean(),
  audio_description_vtt: z.boolean(),
  audio_description_mp3: z.boolean(),
  accessible_video_mp4: z.boolean(),
  sdh_vtt: z.boolean(),
  languages: z.array(z.string()),
  translation_mode: z.enum(['traditional']),
});

type JobFormData = z.infer<typeof jobSchema>;

export function NewJob() {
  const [searchParams] = useSearchParams();
  const briefId = searchParams.get('brief_id');

  // Single upload state (for 1 file)
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [createdJob, setCreatedJob] = useState<string | null>(null);

  // Multi upload state (for 2+ files)
  const multiUpload = useMultiUpload({ maxConcurrent: 3 });

  // Shared state
  const [brandContext, setBrandContext] = useState('');
  const [deadline, setDeadline] = useState('');
  const [selectedClientId, setSelectedClientId] = useState('');
  const [selectedProjectId, setSelectedProjectId] = useState('');
  const { data: clients = [] } = useClients();
  const { data: projects = [], refetch: refetchProjects } = useProjects(selectedClientId);

  // Inline create-project form state
  const [showCreateProject, setShowCreateProject] = useState(false);
  const [newProjectName, setNewProjectName] = useState('');
  const [newProjectLanguages, setNewProjectLanguages] = useState<string[]>([]);
  const [newProjectLinguistId, setNewProjectLinguistId] = useState('');
  const [newProjectReviewerId, setNewProjectReviewerId] = useState('');
  const createProjectMutation = useCreateProject(selectedClientId);
  const { data: linguistUsersData } = useUsers({ role: 'linguist', active_only: true });
  const { data: reviewerUsersData } = useUsers({ role: 'reviewer', active_only: true });
  const linguistUsers = linguistUsersData?.users ?? [];
  const reviewerUsers = reviewerUsersData?.users ?? [];
  const [teamLinguistId, setTeamLinguistId] = useState('');
  const [teamReviewerId, setTeamReviewerId] = useState('');
  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,
    stability: undefined,
    similarity_boost: undefined,
  });
  const [accessibleVideoMethod, setAccessibleVideoMethod] = useState<AccessibleVideoMethod>('pause_insert');

  const navigate = useNavigate();
  const toast = useToastContext();
  const createJobMutation = useCreateJob();

  // Determine mode based on total selected files
  const totalSelectedFiles = selectedFile ? 1 : multiUpload.files.length;
  const isMultiMode = totalSelectedFiles >= 2;
  const isUploading = createJobMutation.isPending || multiUpload.isUploading;

  // Warn before tab close/navigate away while upload is in progress (T-15)
  useEffect(() => {
    if (!isUploading) return;
    const handler = (e: BeforeUnloadEvent) => {
      e.preventDefault();
      e.returnValue = '';
    };
    window.addEventListener('beforeunload', handler);
    return () => window.removeEventListener('beforeunload', handler);
  }, [isUploading]);

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors }
  } = useForm<JobFormData>({
    resolver: zodResolver(jobSchema),
    defaultValues: {
      title: '',
      captions_vtt: true,
      audio_description_vtt: true,
      audio_description_mp3: true,
      accessible_video_mp4: false,
      sdh_vtt: false,
      languages: [],
      translation_mode: 'traditional',
    }
  });

  const languages = watch('languages');
  const audioDescriptionMp3 = watch('audio_description_mp3');
  const accessibleVideoMp4 = watch('accessible_video_mp4');

  // Pre-fill from brief if brief_id query param is present
  const { data: briefData } = useBrief(briefId ?? '');
  useEffect(() => {
    if (!briefData) return;
    setValue('languages', briefData.languages ?? []);
    setValue('captions_vtt', briefData.requested_outputs.captions_vtt);
    setValue('audio_description_vtt', briefData.requested_outputs.audio_description_vtt);
    setValue('audio_description_mp3', briefData.requested_outputs.audio_description_mp3);
    setValue('sdh_vtt', briefData.requested_outputs.sdh_vtt ?? false);
    if (briefData.deadline) {
      setDeadline(briefData.deadline.substring(0, 10));
    }
    if (briefData.project_id) {
      setSelectedProjectId(briefData.project_id);
    }
  }, [briefData, setValue]);

  // Handle file selection from dropzone
  const handleFilesSelect = (files: File[]) => {
    if (files.length === 1 && multiUpload.files.length === 0) {
      // Single file mode
      setSelectedFile(files[0]);
      // Pre-fill title with filename
      setValue('title', generateTitleFromFilename(files[0].name));
    } else {
      // Multi-file mode - clear single file and add to multi
      if (selectedFile) {
        // Move existing single file to multi-upload
        multiUpload.addFiles([selectedFile]);
        setSelectedFile(null);
      }
      multiUpload.addFiles(files);
    }
  };

  // Handle removing single file
  const handleRemoveSingleFile = () => {
    setSelectedFile(null);
    setValue('title', '');
  };

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

    if (!data.title || data.title.trim() === '') {
      toast.toastOnly.error('Please enter a job title');
      return;
    }

    if (!selectedClientId) {
      toast.toastOnly.error('Please select a client');
      return;
    }
    if (!selectedProjectId) {
      toast.toastOnly.error('Please select a project');
      return;
    }

    const jobData: JobCreateRequest = {
      title: data.title,
      requested_outputs: {
        captions_vtt: data.captions_vtt,
        audio_description_vtt: data.audio_description_vtt,
        audio_description_mp3: data.audio_description_mp3,
        accessible_video_mp4: data.accessible_video_mp4,
        accessible_video_method: data.accessible_video_mp4 ? accessibleVideoMethod : undefined,
        languages: data.languages,
        sdh_vtt: data.sdh_vtt,
        transcreation: [],
        tts_preferences: data.audio_description_mp3 ? ttsPreferences : undefined,
        translation_mode: data.translation_mode,
      },
      brand_context: brandContext.trim() || undefined,
      project_id: selectedProjectId || undefined,
      brief_id: briefId || undefined,
      deadline: deadline || undefined,
      initial_linguist_id: teamLinguistId || undefined,
      initial_reviewer_id: teamReviewerId || 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
      setTimeout(() => {
        navigate(`/jobs/${job.id}`);
      }, 3000);
    } catch (error) {
      console.error('Job creation failed:', error);
      const err = error as {
        code?: string;
        message?: string;
        response?: { status?: number; data?: { detail?: string } };
      };
      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);
    }
  };

  // Multi-file submit handler
  const onSubmitMulti = async (data: JobFormData) => {
    if (multiUpload.files.length === 0) {
      toast.toastOnly.error('Please select video files');
      return;
    }

    if (!selectedClientId) {
      toast.toastOnly.error('Please select a client');
      return;
    }
    if (!selectedProjectId) {
      toast.toastOnly.error('Please select a project');
      return;
    }

    await multiUpload.startUpload({
      requestedOutputs: {
        captions_vtt: data.captions_vtt,
        audio_description_vtt: data.audio_description_vtt,
        audio_description_mp3: data.audio_description_mp3,
        accessible_video_mp4: data.accessible_video_mp4,
        accessible_video_method: data.accessible_video_mp4 ? accessibleVideoMethod : undefined,
        languages: data.languages,
        sdh_vtt: data.sdh_vtt,
        transcreation: [],
        tts_preferences: data.audio_description_mp3 ? ttsPreferences : undefined,
        translation_mode: data.translation_mode,
      },
      brandContext: brandContext.trim() || undefined,
      projectId: selectedProjectId || undefined,
      deadline: deadline || undefined,
      initialLinguistId: teamLinguistId || undefined,
      initialReviewerId: teamReviewerId || undefined,
    });
  };

  // Form submit router
  const onSubmit = async (data: JobFormData) => {
    if (isMultiMode) {
      await onSubmitMulti(data);
    } else {
      await onSubmitSingle(data);
    }
  };

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

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

  const handleReset = () => {
    setCreatedJob(null);
    setSelectedFile(null);
    setUploadProgress(0);
    multiUpload.reset();
    setValue('title', '');
  };

  const resetCreateProjectForm = () => {
    setNewProjectName('');
    setNewProjectLanguages([]);
    setNewProjectLinguistId('');
    setNewProjectReviewerId('');
    setShowCreateProject(false);
  };

  const handleCreateProject = async () => {
    if (!newProjectName.trim()) {
      toast.toastOnly.error('Project name is required');
      return;
    }
    try {
      const created = await createProjectMutation.mutateAsync({
        name: newProjectName.trim(),
        default_languages: newProjectLanguages,
        default_linguist_id: newProjectLinguistId || undefined,
        default_reviewer_id: newProjectReviewerId || undefined,
      });
      setSelectedProjectId(created.id);
      // Pre-fill job languages if project has defaults
      if (created.default_languages?.length) {
        setValue('languages', created.default_languages);
      }
      await refetchProjects();
      resetCreateProjectForm();
      toast.toastOnly.success(`Project "${created.name}" created`);
    } catch {
      toast.toastOnly.error('Failed to create project');
    }
  };

  const handleRetryFailed = async () => {
    const data = watch();
    await multiUpload.retryFailed({
      requestedOutputs: {
        captions_vtt: data.captions_vtt,
        audio_description_vtt: data.audio_description_vtt,
        audio_description_mp3: data.audio_description_mp3,
        accessible_video_mp4: data.accessible_video_mp4,
        accessible_video_method: data.accessible_video_mp4 ? accessibleVideoMethod : undefined,
        languages: data.languages,
        sdh_vtt: data.sdh_vtt,
        transcreation: [],
        tts_preferences: data.audio_description_mp3 ? ttsPreferences : undefined,
        translation_mode: data.translation_mode,
      },
      brandContext: brandContext.trim() || undefined,
      projectId: selectedProjectId || undefined,
      initialLinguistId: teamLinguistId || undefined,
      initialReviewerId: teamReviewerId || undefined,
    });
  };

  // Single file 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={handleReset}
                className="text-gray-600 hover:text-gray-800"
              >
                Create Another Job
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Multi-upload complete state
  if (multiUpload.isComplete) {
    return (
      <div className="container mx-auto px-4 py-8 max-w-2xl">
        <div className="text-center py-8">
          <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">Upload Complete!</h1>
          <p className="text-gray-600 mb-6">
            {multiUpload.successCount} of {multiUpload.totalFiles} videos uploaded successfully
          </p>
        </div>

        {/* Success list */}
        {multiUpload.successCount > 0 && (
          <div className="mb-6">
            <h2 className="text-sm font-medium text-gray-700 mb-2">Successful ({multiUpload.successCount})</h2>
            <div className="border border-gray-200 rounded-lg divide-y divide-gray-200">
              {multiUpload.uploads
                .filter(u => u.status === 'success')
                .map(upload => (
                  <div key={upload.id} className="flex items-center justify-between px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-5 h-5 rounded-full bg-green-100 flex items-center justify-center">
                        <svg className="w-3 h-3 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                        </svg>
                      </div>
                      <span className="text-sm text-gray-900">{upload.autoTitle}</span>
                    </div>
                    <Link
                      to={`/jobs/${upload.jobId}`}
                      className="text-sm text-blue-600 hover:text-blue-800"
                    >
                      View Job
                    </Link>
                  </div>
                ))}
            </div>
          </div>
        )}

        {/* Failed list */}
        {multiUpload.failedCount > 0 && (
          <div className="mb-6">
            <h2 className="text-sm font-medium text-gray-700 mb-2">Failed ({multiUpload.failedCount})</h2>
            <div className="border border-red-200 rounded-lg divide-y divide-red-200 bg-red-50">
              {multiUpload.uploads
                .filter(u => u.status === 'error')
                .map(upload => (
                  <div key={upload.id} className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-5 h-5 rounded-full bg-red-100 flex items-center justify-center">
                        <svg className="w-3 h-3 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                      </div>
                      <span className="text-sm text-gray-900">{upload.filename}</span>
                    </div>
                    <p className="text-xs text-red-600 ml-7 mt-1">{upload.error}</p>
                  </div>
                ))}
            </div>
            <button
              type="button"
              onClick={handleRetryFailed}
              className="mt-3 text-sm text-blue-600 hover:text-blue-800"
            >
              Retry Failed Uploads
            </button>
          </div>
        )}

        <div className="flex gap-4 justify-center pt-4">
          <button
            onClick={() => navigate('/jobs')}
            className="px-6 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50"
          >
            View All Jobs
          </button>
          <button
            onClick={handleReset}
            className="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            Upload More Videos
          </button>
        </div>
      </div>
    );
  }

  // Multi-upload in progress state
  if (multiUpload.isUploading) {
    return (
      <div className="container mx-auto px-4 py-8 max-w-2xl">
        <h1 className="text-3xl font-bold text-gray-900 mb-8">Uploading Videos</h1>
        <UploadProgressList uploads={multiUpload.uploads} />
      </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>

      {/* Single file progress bar */}
      {createJobMutation.isPending && !isMultiMode && (
        <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 {isMultiMode ? 'Files' : 'File'}
          </label>
          <UploadDropzone
            onFilesSelect={handleFilesSelect}
            multiple={true}
            disabled={isUploading}
          />

          {/* Single file display */}
          {selectedFile && !isMultiMode && (
            <div className="mt-2 flex items-center justify-between text-sm text-gray-600">
              <span>Selected: {selectedFile.name} ({Math.round(selectedFile.size / (1024 * 1024))}MB)</span>
              <button
                type="button"
                onClick={handleRemoveSingleFile}
                className="text-gray-400 hover:text-red-500"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          )}

          {/* Multi-file list */}
          {isMultiMode && (
            <MultiUploadFileList
              files={multiUpload.files}
              onRemove={(id) => {
                multiUpload.removeFile(id);
                // If only one file left after removal, switch back to single mode
                if (multiUpload.files.length === 2) {
                  const remainingFile = multiUpload.files.find(f => f.id !== id);
                  if (remainingFile) {
                    setSelectedFile(remainingFile.file);
                    setValue('title', remainingFile.autoTitle);
                    multiUpload.clearFiles();
                  }
                }
              }}
              onClearAll={() => {
                multiUpload.clearFiles();
                setSelectedFile(null);
                setValue('title', '');
              }}
              disabled={isUploading}
            />
          )}
        </div>

        {/* Job Title - only shown in single file mode */}
        {!isMultiMode && selectedFile && (
          <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>
        )}

        {/* Multi-mode info */}
        {isMultiMode && (
          <div className="bg-blue-50 border border-blue-200 rounded-md p-3">
            <p className="text-sm text-blue-800">
              <strong>Multi-upload mode:</strong> Job titles will be automatically generated from file names.
              Settings below will apply to all {multiUpload.files.length} videos.
            </p>
          </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>
            <label className="flex items-center">
              <input
                type="checkbox"
                {...register('accessible_video_mp4')}
                className="mr-2"
              />
              <span>Accessible Video (MP4 with embedded audio descriptions)</span>
            </label>
            <label className="flex items-center">
              <input
                type="checkbox"
                {...register('sdh_vtt')}
                className="mr-2"
              />
              <span>SDH Captions (VTT with speaker labels, sound effects &amp; music notation)</span>
            </label>

            {/* Accessible Video Method Selector - shown when accessible_video_mp4 is checked */}
            {accessibleVideoMp4 && (
              <div className="ml-6 mt-3 space-y-2">
                <p className="text-sm text-gray-600 mb-2">Select audio description integration method:</p>
                <label className="flex items-start p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-purple-50 has-[:checked]:border-purple-500 has-[:checked]:bg-purple-50">
                  <input
                    type="radio"
                    value="pause_insert"
                    checked={accessibleVideoMethod === 'pause_insert'}
                    onChange={() => setAccessibleVideoMethod('pause_insert')}
                    className="mt-1 mr-3"
                    disabled={isUploading}
                  />
                  <div>
                    <span className="font-medium text-gray-900">Pause & Insert</span>
                    <p className="text-xs text-gray-500 mt-1">
                      Video pauses at natural breaks for audio description narration. Best for dialogue-heavy content.
                    </p>
                  </div>
                </label>
                <label className="flex items-start p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-purple-50 has-[:checked]:border-purple-500 has-[:checked]:bg-purple-50">
                  <input
                    type="radio"
                    value="overlay"
                    checked={accessibleVideoMethod === 'overlay'}
                    onChange={() => setAccessibleVideoMethod('overlay')}
                    className="mt-1 mr-3"
                    disabled={isUploading}
                  />
                  <div>
                    <span className="font-medium text-gray-900">Audio Overlay</span>
                    <p className="text-xs text-gray-500 mt-1">
                      Audio descriptions play over original audio (ducked). Best for videos with natural pauses or light dialogue.
                    </p>
                  </div>
                </label>
              </div>
            )}
          </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={isUploading}
                />
              </div>
            )}
          </div>
        )}

        {/* Target Languages */}
        <LanguageSelector
          selectedLanguages={languages}
          onAdd={addLanguage}
          onRemove={removeLanguage}
          disabled={isUploading}
        />

        {/* Team Assignment — auto-filled from project defaults, editable per-job */}
        {selectedProjectId && (
          <div className="border border-gray-200 rounded-lg p-4 space-y-3">
            <h3 className="text-sm font-semibold text-gray-700">Team Assignment
              <span className="ml-2 text-xs font-normal text-gray-400">(applied to all languages when job enters QC)</span>
            </h3>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">Linguist</label>
                <select
                  value={teamLinguistId}
                  onChange={e => setTeamLinguistId(e.target.value)}
                  className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  disabled={isUploading}
                >
                  <option value="">— None —</option>
                  {linguistUsers.map(u => (
                    <option key={u.id} value={u.id}>{u.full_name}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-600 mb-1">Reviewer</label>
                <select
                  value={teamReviewerId}
                  onChange={e => setTeamReviewerId(e.target.value)}
                  className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  disabled={isUploading}
                >
                  <option value="">— None —</option>
                  {reviewerUsers.map(u => (
                    <option key={u.id} value={u.id}>{u.full_name}</option>
                  ))}
                </select>
              </div>
            </div>
          </div>
        )}

        {/* Translation Mode - Only shown when target languages are selected */}
        {languages.length > 0 && (
          <div className="rounded-lg bg-blue-50 border border-blue-200 px-4 py-3 text-sm text-blue-800">
            Translations are generated from the approved English master VTT, preserving all cue timings 1:1.
            Target languages become available for linguist review after English QC is approved.
          </div>
        )}

        {/* Client + Project */}
        <div className="space-y-3">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Client <span className="text-red-500">*</span>
            </label>
            <select
              value={selectedClientId}
              onChange={e => {
                setSelectedClientId(e.target.value);
                setSelectedProjectId('');
                resetCreateProjectForm();
              }}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              disabled={isUploading}
            >
              <option value="">— Select client —</option>
              {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>

          {selectedClientId && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Project <span className="text-red-500">*</span>
              </label>
              <select
                value={selectedProjectId}
                onChange={e => {
                  const value = e.target.value;
                  if (value === '__create__') {
                    setSelectedProjectId('');
                    setShowCreateProject(true);
                  } else {
                    setSelectedProjectId(value);
                    setShowCreateProject(false);
                    // W-5: autofill job languages + team from project defaults
                    if (value) {
                      const proj = projects.find(p => p.id === value);
                      if (proj?.default_languages?.length) {
                        setValue('languages', proj.default_languages);
                      }
                      setTeamLinguistId(proj?.default_linguist_id ?? '');
                      setTeamReviewerId(proj?.default_reviewer_id ?? '');
                    }
                  }
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                disabled={isUploading}
              >
                <option value="">— Select project —</option>
                {projects.filter(p => p.is_active).map(p => (
                  <option key={p.id} value={p.id}>{p.name}</option>
                ))}
                <option value="__create__">＋ Create new project…</option>
              </select>

              {/* Inline create-project form */}
              {showCreateProject && (
                <div className="mt-3 border border-blue-200 bg-blue-50 rounded-lg p-4 space-y-4">
                  <h3 className="text-sm font-semibold text-blue-900">New project</h3>

                  <div>
                    <label className="block text-xs font-medium text-gray-700 mb-1">
                      Name <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      value={newProjectName}
                      onChange={e => setNewProjectName(e.target.value)}
                      className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="Project name"
                    />
                  </div>

                  <div>
                    <p className="text-xs font-medium text-gray-700 mb-1">
                      Default languages <span className="text-gray-400 font-normal">(optional — pre-fills languages on new jobs)</span>
                    </p>
                    <LanguageSelector
                      selectedLanguages={newProjectLanguages}
                      onAdd={l => setNewProjectLanguages(prev => prev.includes(l) ? prev : [...prev, l])}
                      onRemove={l => setNewProjectLanguages(prev => prev.filter(x => x !== l))}
                      disabled={false}
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">
                        Default linguist <span className="text-gray-400 font-normal">(optional)</span>
                      </label>
                      <select
                        value={newProjectLinguistId}
                        onChange={e => setNewProjectLinguistId(e.target.value)}
                        className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      >
                        <option value="">— None —</option>
                        {linguistUsers.map(u => (
                          <option key={u.id} value={u.id}>{u.full_name}</option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-700 mb-1">
                        Default reviewer <span className="text-gray-400 font-normal">(optional)</span>
                      </label>
                      <select
                        value={newProjectReviewerId}
                        onChange={e => setNewProjectReviewerId(e.target.value)}
                        className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      >
                        <option value="">— None —</option>
                        {reviewerUsers.map(u => (
                          <option key={u.id} value={u.id}>{u.full_name}</option>
                        ))}
                      </select>
                    </div>
                  </div>

                  <div className="flex items-center gap-3 pt-1">
                    <button
                      type="button"
                      onClick={handleCreateProject}
                      disabled={createProjectMutation.isPending || !newProjectName.trim()}
                      className="px-4 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {createProjectMutation.isPending ? 'Creating…' : 'Create project'}
                    </button>
                    <button
                      type="button"
                      onClick={resetCreateProjectForm}
                      className="text-sm text-gray-500 hover:text-gray-700"
                    >
                      Cancel
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Deadline */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Deadline <span className="text-gray-400 font-normal">(optional)</span>
          </label>
          <input
            type="date"
            value={deadline}
            onChange={(e) => setDeadline(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            disabled={isUploading}
          />
        </div>

        {/* Brand Context */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Brand Names <span className="text-gray-400 font-normal">(optional)</span>
          </label>
          <input
            type="text"
            value={brandContext}
            onChange={(e) => setBrandContext(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="e.g. Sellotape, Coca-Cola, Apple iPhone"
            disabled={isUploading}
          />
          <p className="mt-1 text-xs text-gray-500">
            List brand names visible in the video so the AI uses them instead of generic terms (e.g. "Sellotape" instead of "sticky tape").
          </p>
        </div>

        {/* Submit Button */}
        <div className="pt-4">
          <button
            type="submit"
            disabled={totalSelectedFiles === 0 || isUploading}
            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"
          >
            {isUploading
              ? (isMultiMode ? 'Uploading Videos...' : 'Creating Job...')
              : (isMultiMode ? `Upload ${multiUpload.files.length} Videos` : 'Create Job')
            }
          </button>
        </div>
      </form>
    </div>
  );
}
