'use client';

import { useState } from 'react';
import { toast } from 'react-hot-toast';
import { Captions, Download, Sparkles, ChevronDown, ChevronUp } from 'lucide-react';
import FileUpload from '@/components/FileUpload';
import JobProgress from '@/components/JobProgress';
import { modulesApi, assetsApi } from '@/lib/api';
import { useStore } from '@/lib/store';

const languages = [
  { value: '', label: 'Auto-detect' },
  { value: 'en', label: 'English' },
  { value: 'es', label: 'Spanish' },
  { value: 'fr', label: 'French' },
  { value: 'de', label: 'German' },
  { value: 'it', label: 'Italian' },
  { value: 'pt', label: 'Portuguese' },
  { value: 'ja', label: 'Japanese' },
  { value: 'ko', label: 'Korean' },
  { value: 'zh', label: 'Chinese' },
];

const targetLanguages = [
  { value: '', label: 'No translation' },
  { value: 'EN-US', label: 'English (US)' },
  { value: 'EN-GB', label: 'English (UK)' },
  { value: 'ES', label: 'Spanish' },
  { value: 'FR', label: 'French' },
  { value: 'DE', label: 'German' },
  { value: 'IT', label: 'Italian' },
  { value: 'PT-BR', label: 'Portuguese (Brazil)' },
  { value: 'JA', label: 'Japanese' },
  { value: 'KO', label: 'Korean' },
  { value: 'ZH', label: 'Chinese' },
];

const fonts = [
  'Arial', 'Helvetica', 'Times New Roman', 'Courier New', 'Verdana',
  'Georgia', 'Comic Sans MS', 'Impact', 'Tahoma', 'Trebuchet MS',
  'Lucida Sans', 'Lucida Console', 'Palatino Linotype', 'Book Antiqua',
  'Century Gothic', 'Franklin Gothic Medium', 'Garamond', 'Segoe UI',
  'Calibri', 'Cambria', 'Candara', 'Constantia', 'Consolas', 'Corbel'
];

const colors = [
  { value: 'white', label: 'White' },
  { value: 'yellow', label: 'Yellow' },
  { value: 'black', label: 'Black' },
  { value: 'red', label: 'Red' },
  { value: 'blue', label: 'Blue' },
  { value: 'green', label: 'Green' },
  { value: 'orange', label: 'Orange' },
  { value: 'purple', label: 'Purple' },
];

export default function SubtitlesPage() {
  const { addJob, updateJob } = useStore();
  const [file, setFile] = useState<File | null>(null);
  const [assetId, setAssetId] = useState<string | null>(null);
  const [sourceLanguage, setSourceLanguage] = useState('');
  const [targetLanguage, setTargetLanguage] = useState('');
  const [burnSubtitles, setBurnSubtitles] = useState(false);

  // Styling options
  const [font, setFont] = useState('Arial');
  const [fontSize, setFontSize] = useState(24);
  const [textColor, setTextColor] = useState('white');
  const [outlineColor, setOutlineColor] = useState('black');
  const [outlineWidth, setOutlineWidth] = useState(2);
  const [position, setPosition] = useState('bottom');

  const [showAdvanced, setShowAdvanced] = useState(false);

  const [jobId, setJobId] = useState<string | null>(null);
  const [results, setResults] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);

  const handleFileUpload = async (uploadedFile: File) => {
    setFile(uploadedFile);
    toast.success('Video ready for processing!');
  };

  const handleProcess = async () => {
    if (!file) {
      toast.error('Please upload a video first');
      return;
    }

    // Debug: Check file state
    console.log('🎬 Starting subtitle processing...');
    console.log('  File object:', file);
    console.log('  File name:', file.name);
    console.log('  File size:', file.size, 'bytes');
    console.log('  File type:', file.type);

    setLoading(true);
    setResults(null);

    try {
      // Create minimal FormData with only required fields for testing
      const formData = new FormData();
      formData.append('file', file);

      // Only add non-default values
      if (sourceLanguage && sourceLanguage !== 'auto') {
        formData.append('source_language', sourceLanguage);
      }
      if (targetLanguage) {
        formData.append('target_language', targetLanguage);
      }
      if (burnSubtitles) {
        formData.append('burn_subtitles', 'true');
      }

      // Debug: Log FormData contents
      console.log('📤 Sending MINIMAL FormData to subtitle API:');
      for (const [key, value] of formData.entries()) {
        if (value instanceof File) {
          console.log(`  ${key}:`, value.name, `(${value.size} bytes, ${value.type})`);
        } else {
          console.log(`  ${key}:`, value);
        }
      }

      const response = await modulesApi.processSubtitles(formData);

      const job = response.data;
      setJobId(job.id);
      addJob({
        id: job.id,
        module: 'subtitle_processor',
        status: job.status,
        progress: job.progress,
        created_at: job.created_at,
      });

      toast.success('Subtitle processing started!');
    } catch (err: any) {
      console.error('Subtitle processing error:', err);
      console.error('Error response:', err.response);
      console.error('Error data:', err.response?.data);

      // Handle validation errors (array of error objects)
      if (err.response?.data?.detail && Array.isArray(err.response.data.detail)) {
        const errorMessages = err.response.data.detail.map((e: any) => {
          return `${e.loc?.join('.')} - ${e.msg}`;
        }).join('; ');
        toast.error(`Validation error: ${errorMessages}`);
      } else if (typeof err.response?.data?.detail === 'string') {
        toast.error(err.response.data.detail);
      } else {
        toast.error('Failed to start processing');
      }

      setLoading(false);
    }
  };

  const handleJobComplete = async (job: any) => {
    setLoading(false);
    updateJob(job.id, { status: 'completed', progress: 100 });

    if (job.output_asset_ids?.length > 0) {
      const assets = await Promise.all(
        job.output_asset_ids.map(async (id: string) => {
          const asset = await assetsApi.get(id);
          return asset.data;
        })
      );
      setResults({
        assets,
        transcript: job.output_data?.transcript,
        language: job.output_data?.language,
      });
      toast.success('Subtitles generated successfully!');
    }
  };

  const handleJobError = (error: string) => {
    setLoading(false);
    toast.error(error);
  };

  const handleDownload = async (asset: any) => {
    try {
      const response = await assetsApi.download(asset.id);
      const url = window.URL.createObjectURL(response.data);
      const a = document.createElement('a');
      a.href = url;
      a.download = asset.original_filename;
      a.click();
      window.URL.revokeObjectURL(url);
    } catch (err: any) {
      toast.error('Failed to download file');
    }
  };

  return (
    <div className="max-w-6xl mx-auto space-y-8">
      <div className="flex items-center gap-4">
        <div className="w-12 h-12 bg-forge-yellow/10 rounded-lg flex items-center justify-center">
          <Captions className="w-6 h-6 text-forge-yellow" />
        </div>
        <div>
          <h1 className="text-2xl font-bold text-white">Subtitle Generator</h1>
          <p className="text-gray-500">Auto-generate and translate subtitles with custom styling</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* Controls */}
        <div className="space-y-6">
          {/* File Upload */}
          <div>
            <label className="block text-sm font-medium text-gray-300 mb-2">
              Upload Video
            </label>
            <FileUpload
              onUpload={handleFileUpload}
              accept={{ 'video/*': ['.mp4', '.mov', '.avi', '.webm'] }}
              currentFile={file}
              onClear={() => {
                setFile(null);
                setAssetId(null);
              }}
              label="Upload a video for transcription"
            />
          </div>

          {/* Languages */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Source Language
              </label>
              <select
                value={sourceLanguage}
                onChange={(e) => setSourceLanguage(e.target.value)}
                className="select-field"
              >
                {languages.map((lang) => (
                  <option key={lang.value} value={lang.value}>
                    {lang.label}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Translate To
              </label>
              <select
                value={targetLanguage}
                onChange={(e) => setTargetLanguage(e.target.value)}
                className="select-field"
              >
                {targetLanguages.map((lang) => (
                  <option key={lang.value} value={lang.value}>
                    {lang.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Subtitle Styling */}
          <div className="bg-forge-dark rounded-xl border border-gray-800 p-4 space-y-4">
            <h3 className="text-white font-medium">Subtitle Styling</h3>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Font
                </label>
                <select
                  value={font}
                  onChange={(e) => setFont(e.target.value)}
                  className="select-field"
                >
                  {fonts.map((f) => (
                    <option key={f} value={f}>{f}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Font Size
                </label>
                <input
                  type="number"
                  value={fontSize}
                  onChange={(e) => setFontSize(parseInt(e.target.value))}
                  min="8"
                  max="72"
                  className="input-field"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Text Color
                </label>
                <select
                  value={textColor}
                  onChange={(e) => setTextColor(e.target.value)}
                  className="select-field"
                >
                  {colors.map((c) => (
                    <option key={c.value} value={c.value}>{c.label}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Outline Color
                </label>
                <select
                  value={outlineColor}
                  onChange={(e) => setOutlineColor(e.target.value)}
                  className="select-field"
                >
                  {colors.map((c) => (
                    <option key={c.value} value={c.value}>{c.label}</option>
                  ))}
                </select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Outline Width
                </label>
                <input
                  type="number"
                  value={outlineWidth}
                  onChange={(e) => setOutlineWidth(parseFloat(e.target.value))}
                  min="0"
                  max="4"
                  step="0.1"
                  className="input-field"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Position
                </label>
                <select
                  value={position}
                  onChange={(e) => setPosition(e.target.value)}
                  className="select-field"
                >
                  <option value="bottom">Bottom</option>
                  <option value="top">Top</option>
                </select>
              </div>
            </div>
          </div>

          {/* Burn Subtitles */}
          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              id="burnSubtitles"
              checked={burnSubtitles}
              onChange={(e) => setBurnSubtitles(e.target.checked)}
              className="w-4 h-4 rounded border-gray-600 bg-forge-dark text-forge-yellow focus:ring-forge-yellow"
            />
            <label htmlFor="burnSubtitles" className="text-gray-300">
              Burn subtitles into video (hardcoded)
            </label>
          </div>

          {/* Process Button */}
          <button
            onClick={handleProcess}
            disabled={loading || !file}
            className="btn-primary w-full flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Sparkles className="w-5 h-5" />
            {loading ? 'Processing...' : 'Generate Subtitles'}
          </button>

          {/* Job Progress */}
          {jobId && loading && (
            <JobProgress
              jobId={jobId}
              onComplete={handleJobComplete}
              onError={handleJobError}
            />
          )}
        </div>

        {/* Results */}
        <div>
          <h2 className="text-lg font-semibold text-white mb-4">Results</h2>
          {results ? (
            <div className="space-y-4">
              {/* Generated Files */}
              <div className="bg-forge-dark rounded-xl border border-gray-800 p-4">
                <h3 className="text-white font-medium mb-3">Generated Files</h3>
                <div className="space-y-2">
                  {results.assets.map((asset: any) => (
                    <div
                      key={asset.id}
                      className="flex items-center justify-between p-3 bg-forge-gray rounded-lg"
                    >
                      <div>
                        <p className="text-white text-sm">{asset.original_filename}</p>
                        <p className="text-xs text-gray-500">
                          {asset.metadata?.type === 'translated' ? 'Translated' : 'Original'} •{' '}
                          {asset.file_type}
                        </p>
                      </div>
                      <button
                        onClick={() => handleDownload(asset)}
                        className="p-2 text-forge-yellow hover:bg-forge-yellow/10 rounded transition-colors"
                      >
                        <Download className="w-4 h-4" />
                      </button>
                    </div>
                  ))}
                </div>
              </div>

              {/* Transcript Preview */}
              {results.transcript && (
                <div className="bg-forge-dark rounded-xl border border-gray-800 p-4">
                  <h3 className="text-white font-medium mb-3">
                    Transcript Preview
                    {results.language && (
                      <span className="text-gray-500 text-sm ml-2">
                        (Detected: {results.language})
                      </span>
                    )}
                  </h3>
                  <div className="max-h-64 overflow-y-auto">
                    <p className="text-gray-300 text-sm whitespace-pre-wrap">
                      {results.transcript.substring(0, 1000)}
                      {results.transcript.length > 1000 && '...'}
                    </p>
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="bg-forge-dark rounded-xl border border-gray-800 p-8 text-center">
              <Captions className="w-12 h-12 text-gray-600 mx-auto mb-3" />
              <p className="text-gray-500">Subtitles will appear here</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
