'use client';

import { useState } from 'react';
import { toast } from 'react-hot-toast';
import { Type, Download, Sparkles, Copy, Check } 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 outputFormats = [
  { value: 'txt', label: 'Plain Text (.txt)' },
  { value: 'srt', label: 'SRT Subtitles (.srt)' },
  { value: 'vtt', label: 'WebVTT (.vtt)' },
];

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' },
];

export default function VoiceToTextPage() {
  const { addJob, updateJob } = useStore();
  const [file, setFile] = useState<File | null>(null);
  const [assetId, setAssetId] = useState<string | null>(null);
  const [outputFormat, setOutputFormat] = useState('txt');
  const [translate, setTranslate] = useState(false);
  const [targetLanguage, setTargetLanguage] = useState('EN-US');
  const [jobId, setJobId] = useState<string | null>(null);
  const [results, setResults] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [copied, setCopied] = useState(false);

  const handleFileUpload = async (uploadedFile: File) => {
    setFile(uploadedFile);
    setUploading(true);

    try {
      const response = await assetsApi.upload(uploadedFile);
      setAssetId(response.data.id);
      toast.success('Audio uploaded!');
    } catch (err: any) {
      if (err.response?.status === 409) {
        const existingAssetId = err.response.data.detail.asset_id;
        const shouldOverwrite = window.confirm(
          `File "${uploadedFile.name}" already exists. \nClick OK to Overwrite, Cancel to Use Existing.`
        );

        if (shouldOverwrite) {
          try {
            const response = await assetsApi.upload(uploadedFile, undefined, false, true); // overwrite=true
            setAssetId(response.data.id);
            toast.success('Audio overwritten!');
          } catch (retryErr: any) {
            toast.error('Failed to overwrite audio');
            setFile(null);
          }
        } else {
          setAssetId(existingAssetId);
          toast('Using existing file', { icon: 'ℹ️' });
        }
      } else {
        toast.error('Failed to upload audio');
        setFile(null);
      }
    } finally {
      setUploading(false);
    }
  };

  const handleTranscribe = async () => {
    if (!assetId) {
      toast.error('Please upload an audio file first');
      return;
    }

    setLoading(true);
    setResults(null);

    try {
      const response = await modulesApi.voiceToText({
        asset_id: assetId,
        output_format: outputFormat,
        translate,
        target_language: translate ? targetLanguage : undefined,
      });

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

      toast.success('Transcription started!');
    } catch (err: any) {
      toast.error(err.response?.data?.detail || 'Failed to start transcription');
      setLoading(false);
    }
  };

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

    if (job.output_data) {
      const assets = job.output_asset_ids
        ? await Promise.all(
          job.output_asset_ids.map(async (id: string) => {
            const asset = await assetsApi.get(id);
            return asset.data;
          })
        )
        : [];

      setResults({
        text: job.output_data.text,
        translatedText: job.output_data.translated_text,
        language: job.output_data.language,
        assets,
      });
      toast.success('Transcription completed!');
    }
  };

  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) {
      toast.error('Failed to download file');
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    toast.success('Copied to clipboard!');
    setTimeout(() => setCopied(false), 2000);
  };

  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">
          <Type className="w-6 h-6 text-forge-yellow" />
        </div>
        <div>
          <h1 className="text-2xl font-bold text-white">Voice to Text</h1>
          <p className="text-gray-500">Transcribe audio with Whisper AI</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 Audio
            </label>
            <FileUpload
              onUpload={handleFileUpload}
              accept={{ 'audio/*': ['.mp3', '.wav', '.m4a', '.flac', '.ogg'] }}
              currentFile={file}
              onClear={() => {
                setFile(null);
                setAssetId(null);
              }}
              label="Upload an audio file to transcribe"
            />
            {uploading && (
              <p className="mt-2 text-sm text-forge-yellow">Uploading...</p>
            )}
          </div>

          {/* Output Format */}
          <div>
            <label className="block text-sm font-medium text-gray-300 mb-2">
              Output Format
            </label>
            <select
              value={outputFormat}
              onChange={(e: React.ChangeEvent<HTMLSelectElement>) => setOutputFormat(e.target.value)}
              className="select-field"
            >
              {outputFormats.map((format) => (
                <option key={format.value} value={format.value}>
                  {format.label}
                </option>
              ))}
            </select>
          </div>

          {/* Translation */}
          <div className="space-y-3">
            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="translate"
                checked={translate}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTranslate(e.target.checked)}
                className="w-4 h-4 rounded border-gray-600 bg-forge-dark text-forge-yellow focus:ring-forge-yellow"
              />
              <label htmlFor="translate" className="text-gray-300">
                Translate to another language
              </label>
            </div>

            {translate && (
              <select
                value={targetLanguage}
                onChange={(e: React.ChangeEvent<HTMLSelectElement>) => setTargetLanguage(e.target.value)}
                className="select-field"
              >
                {targetLanguages.filter((l) => l.value).map((lang) => (
                  <option key={lang.value} value={lang.value}>
                    {lang.label}
                  </option>
                ))}
              </select>
            )}
          </div>

          {/* Transcribe Button */}
          <button
            onClick={handleTranscribe}
            disabled={loading || !assetId || uploading}
            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 ? 'Transcribing...' : 'Transcribe Audio'}
          </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">Transcription</h2>
          {results ? (
            <div className="space-y-4">
              {/* Download Files */}
              {results.assets.length > 0 && (
                <div className="bg-forge-dark rounded-xl border border-gray-800 p-4">
                  <h3 className="text-white font-medium mb-3">Download 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'}
                          </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>
              )}

              {/* Original Transcript */}
              <div className="bg-forge-dark rounded-xl border border-gray-800 p-4">
                <div className="flex items-center justify-between mb-3">
                  <h3 className="text-white font-medium">
                    Original Text
                    {results.language && (
                      <span className="text-gray-500 text-sm ml-2">
                        (Detected: {results.language})
                      </span>
                    )}
                  </h3>
                  <button
                    onClick={() => copyToClipboard(results.text)}
                    className="p-2 text-gray-400 hover:text-forge-yellow transition-colors"
                  >
                    {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                  </button>
                </div>
                <div className="max-h-64 overflow-y-auto">
                  <p className="text-gray-300 text-sm whitespace-pre-wrap">
                    {results.text}
                  </p>
                </div>
              </div>

              {/* Translated Text */}
              {results.translatedText && (
                <div className="bg-forge-dark rounded-xl border border-gray-800 p-4">
                  <div className="flex items-center justify-between mb-3">
                    <h3 className="text-white font-medium">Translated Text</h3>
                    <button
                      onClick={() => copyToClipboard(results.translatedText)}
                      className="p-2 text-gray-400 hover:text-forge-yellow transition-colors"
                    >
                      <Copy className="w-4 h-4" />
                    </button>
                  </div>
                  <div className="max-h-64 overflow-y-auto">
                    <p className="text-gray-300 text-sm whitespace-pre-wrap">
                      {results.translatedText}
                    </p>
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="bg-forge-dark rounded-xl border border-gray-800 p-8 text-center">
              <Type className="w-12 h-12 text-gray-600 mx-auto mb-3" />
              <p className="text-gray-500">Transcription will appear here</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
