import React, { useState } from 'react';
import { Upload, FileAudio, X, Check, Loader2 } from 'lucide-react';
import { invoke } from "@tauri-apps/api/core";
import { open } from '@tauri-apps/plugin-dialog';
import logo from '../assets/logo.png';

interface PromptTemplate {
    id: string;
    name: string;
    content: string;
    keywords?: string[];
}

interface ImportProps {
    apiKey: string;
    productId: string;
    prompts: PromptTemplate[];
    selectedModel: string;
    onSaveToHistory: (transcription: string, summary: string) => void;
    onComplete: () => void; // Navigate to Transcription view
    addToast: (msg: string, type: 'success' | 'error' | 'info', duration?: number) => void;
    setTranscription: (text: string) => void;
    setSummary: (text: string) => void;
}

interface AudioMetadata {
    duration: number;
    size: number;
    format: string;
}

type ProcessingStage = 'idle' | 'validating' | 'transcribing' | 'summarizing' | 'complete';

const SUPPORTED_FORMATS = ['mp3', 'mp4', 'm4a', 'wav', 'flac', 'ogg', 'aac', 'wma'];

const Import: React.FC<ImportProps> = ({
    apiKey,
    productId,
    prompts,
    selectedModel,
    onSaveToHistory,
    onComplete,
    addToast,
    setTranscription,
    setSummary
}) => {
    const [selectedFile, setSelectedFile] = useState<string | null>(null);
    const [metadata, setMetadata] = useState<AudioMetadata | null>(null);
    const [meetingTitle, setMeetingTitle] = useState('');
    const [stage, setStage] = useState<ProcessingStage>('idle');
    const [selectedPromptId, setSelectedPromptId] = useState<string>('');

    // Set default prompt
    React.useEffect(() => {
        if (prompts.length > 0 && !selectedPromptId) {
            setSelectedPromptId(prompts[0].id);
        }
    }, [prompts, selectedPromptId]);

    const validateFile = (filePath: string): boolean => {
        const extension = filePath.split('.').pop()?.toLowerCase();
        if (!extension || !SUPPORTED_FORMATS.includes(extension)) {
            addToast(`Unsupported format. Supported: ${SUPPORTED_FORMATS.join(', ').toUpperCase()}`, 'error', 5000);
            return false;
        }
        return true;
    };

    const extractFilename = (path: string): string => {
        const parts = path.split(/[/\\]/);
        const filename = parts[parts.length - 1];
        return filename.replace(/\.[^/.]+$/, ''); // Remove extension
    };

    const formatDuration = (seconds: number): string => {
        const mins = Math.floor(seconds / 60);
        const secs = Math.floor(seconds % 60);
        return `${mins}:${secs.toString().padStart(2, '0')}`;
    };

    const formatSize = (bytes: number): string => {
        if (bytes < 1024 * 1024) {
            return `${(bytes / 1024).toFixed(1)} KB`;
        }
        return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
    };

    const handleFileSelect = async (filePath: string) => {
        if (!validateFile(filePath)) return;

        setStage('validating');
        setSelectedFile(filePath);
        setMeetingTitle(extractFilename(filePath));

        try {
            const meta = await invoke<AudioMetadata>('get_audio_metadata', { filePath });
            setMetadata(meta);
            setStage('idle');
            addToast('File loaded successfully', 'success', 2000);
        } catch (e) {
            console.error('Metadata error:', e);
            setMetadata(null);
            setStage('idle');
        }
    };

    const handleManualSelect = async () => {
        try {
            const selected = await open({
                multiple: false,
                filters: [{
                    name: 'Audio/Video',
                    extensions: SUPPORTED_FORMATS
                }]
            });

            if (selected && typeof selected === 'string') {
                handleFileSelect(selected);
            }
        } catch (e) {
            console.error('File picker error:', e);
            addToast('Failed to open file picker', 'error');
        }
    };

    const handleProcess = async () => {
        if (!selectedFile) return;
        if (!apiKey || !productId) {
            addToast('Please configure API key in Settings', 'error');
            return;
        }

        try {
            // Check file extension
            const isWav = selectedFile.toLowerCase().endsWith('.wav');
            let processFile = selectedFile;

            // Convert WAV to MP3 if needed
            if (isWav) {
                setStage('validating');
                addToast('Converting WAV to MP3...', 'info', 2000);
                processFile = await invoke<string>('convert_to_mp3', { wavPath: selectedFile });
            }

            // Get file size to check if chunking needed
            const metadata = await invoke<AudioMetadata>('get_audio_metadata', { filePath: processFile });
            const sizeMB = metadata.size / (1024 * 1024);

            let transText = '';

            // Check if chunking needed for large files
            if (sizeMB >= 18) {
                // CHUNKING PATH for large files
                setStage('validating');
                addToast(`Large file (${sizeMB.toFixed(1)}MB). Splitting into chunks...`, 'info', 4000);

                const chunks = await invoke<string[]>('chunk_audio', {
                    filePath: processFile,
                    chunkMinutes: 10
                });

                addToast(`Processing ${chunks.length} chunks...`, 'info', 4000);

                let allTranscriptions: string[] = [];

                for (let i = 0; i < chunks.length; i++) {
                    setStage('transcribing');
                    addToast(`Transcribing chunk ${i + 1}/${chunks.length}...`, 'info', 2000);
                    const chunkText = await invoke<string>('transcribe_audio', {
                        filePath: chunks[i],
                        apiKey,
                        productId
                    });
                    allTranscriptions.push(chunkText);
                }

                // Merge transcriptions
                transText = allTranscriptions.join('\n\n--- Next Segment ---\n\n');
                addToast('All chunks transcribed successfully!', 'success', 3000);
            } else {
                // NORMAL PATH for small files
                setStage('transcribing');
                transText = await invoke<string>('transcribe_audio', {
                    filePath: processFile,
                    apiKey,
                    productId
                });
            }

            setTranscription(transText);

            if (!transText || transText.trim().length === 0) {
                addToast('No speech detected in file', 'error');
                setStage('idle');
                return;
            }

            // Smart prompt selection (copied from Recorder.tsx)
            let activePrompt = prompts.find(p => p.id === selectedPromptId);
            const lowerText = transText.toLowerCase();
            let bestMatchId = selectedPromptId;
            let maxMatches = 0;

            for (const p of prompts) {
                if (!p.keywords) continue;
                let matches = 0;
                for (const kw of p.keywords) {
                    if (lowerText.includes(kw.toLowerCase())) {
                        matches++;
                    }
                }
                if (matches > maxMatches) {
                    maxMatches = matches;
                    bestMatchId = p.id;
                }
            }

            if (bestMatchId !== selectedPromptId) {
                const newPrompt = prompts.find(p => p.id === bestMatchId);
                if (newPrompt) {
                    addToast(`Smart Select: Switched to "${newPrompt.name}"`, 'info', 3000);
                    activePrompt = newPrompt;
                }
            }

            const promptContent = activePrompt ? activePrompt.content : "Summarize this.";

            setStage('summarizing');
            const sumText = await invoke<string>('summarize_text', {
                text: transText,
                apiKey,
                productId,
                prompt: promptContent,
                model: selectedModel
            });
            setSummary(sumText);

            // Save to history
            onSaveToHistory(transText, sumText);

            setStage('complete');
            addToast('Import complete!', 'success', 3000);

            // Navigate to Transcription view
            setTimeout(() => {
                onComplete();
            }, 1000);

        } catch (e) {
            console.error('Processing error:', e);
            addToast(`Error: ${e}`, 'error');
            setStage('idle');
        }
    };

    const handleReset = () => {
        setSelectedFile(null);
        setMetadata(null);
        setMeetingTitle('');
        setStage('idle');
    };

    const getStageInfo = () => {
        switch (stage) {
            case 'validating': return { icon: Loader2, text: 'Validating file...', color: 'text-blue-500' };
            case 'transcribing': return { icon: Loader2, text: 'Transcribing audio...', color: 'text-purple-500' };
            case 'summarizing': return { icon: Loader2, text: 'Generating summary...', color: 'text-green-500' };
            case 'complete': return { icon: Check, text: 'Complete!', color: 'text-green-500' };
            default: return null;
        }
    };

    const stageInfo = getStageInfo();
    const isProcessing = stage !== 'idle' && stage !== 'complete';

    return (
        <div className="flex flex-col w-full h-full bg-background relative">
            {/* Header */}
            <div className="w-full flex justify-center items-center p-4 shrink-0">
                <img src={localStorage.getItem('customLogo') || logo} alt="Logo" className="h-10 object-contain" />
            </div>

            {/* Main Content */}
            <div className="flex-1 overflow-y-auto px-6 pb-6 flex flex-col items-center">
                <h1 className="text-xl font-bold mb-2 text-foreground">Import Audio File</h1>
                <p className="text-muted-foreground mb-6 text-center text-sm">
                    Select an audio file for transcription and summarization
                </p>

                {/* File Selection Zone */}
                <div
                    className={`w-full max-w-md border-2 border-dashed rounded-lg p-8 mb-6 transition-all ${selectedFile
                        ? 'border-green-500 bg-green-500/5'
                        : 'border-border bg-secondary/30'
                        }`}
                >
                    <div className="flex flex-col items-center justify-center gap-4">
                        {selectedFile ? (
                            <>
                                <FileAudio size={48} className="text-green-500" />
                                <div className="text-center">
                                    <p className="font-semibold text-foreground">{meetingTitle}</p>
                                    {metadata && (
                                        <p className="text-xs text-muted-foreground mt-1">
                                            {formatDuration(metadata.duration)} • {formatSize(metadata.size)} • {metadata.format.toUpperCase()}
                                        </p>
                                    )}
                                </div>
                                <button
                                    onClick={handleReset}
                                    className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1"
                                >
                                    <X size={14} /> Change file
                                </button>
                            </>
                        ) : (
                            <>
                                <Upload size={48} className="text-muted-foreground" />
                                <div className="text-center">
                                    <p className="font-semibold text-foreground">Select Audio File</p>
                                    <p className="text-xs text-muted-foreground mt-1">
                                        Click below to browse your files
                                    </p>
                                </div>
                                <button
                                    onClick={handleManualSelect}
                                    disabled={isProcessing}
                                    className="px-6 py-3 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 disabled:opacity-50 text-base font-semibold transition-all shadow-md hover:shadow-lg"
                                >
                                    Browse Files
                                </button>
                                <p className="text-xs text-muted-foreground">
                                    Supported: MP3, MP4, WAV, M4A, FLAC, OGG, AAC, WMA
                                </p>
                            </>
                        )}
                    </div>
                </div>

                {/* Configuration Section */}
                {selectedFile && (
                    <div className="w-full max-w-md space-y-4">
                        {/* Meeting Title */}
                        <div>
                            <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block mb-1">
                                Meeting Title
                            </label>
                            <input
                                type="text"
                                value={meetingTitle}
                                onChange={(e) => setMeetingTitle(e.target.value)}
                                disabled={isProcessing}
                                className="w-full p-2 text-sm bg-secondary rounded border border-border outline-none focus:ring-2 focus:ring-primary disabled:opacity-50"
                                placeholder="Enter meeting title..."
                            />
                        </div>

                        {/* AI Template */}
                        <div>
                            <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block mb-1">
                                AI Template
                            </label>
                            <select
                                value={selectedPromptId}
                                onChange={(e) => setSelectedPromptId(e.target.value)}
                                disabled={isProcessing || prompts.length === 0}
                                className="w-full p-2 text-sm bg-secondary rounded border border-border outline-none focus:ring-2 focus:ring-primary disabled:opacity-50"
                            >
                                {prompts.map(p => (
                                    <option key={p.id} value={p.id}>{p.name}</option>
                                ))}
                                {prompts.length === 0 && <option value="">No templates</option>}
                            </select>
                        </div>

                        {/* Process Button */}
                        <button
                            onClick={handleProcess}
                            disabled={!selectedFile || isProcessing || !apiKey}
                            className="w-full py-3 text-base font-semibold bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2"
                        >
                            {isProcessing ? (
                                <>
                                    <Loader2 size={20} className="animate-spin" />
                                    Processing...
                                </>
                            ) : (
                                <>
                                    <Upload size={20} />
                                    Transcribe & Summarize
                                </>
                            )}
                        </button>

                        {/* Progress Indicator */}
                        {stageInfo && (
                            <div className="flex items-center justify-center gap-2 p-3 bg-secondary/50 rounded-lg border border-border">
                                <stageInfo.icon size={16} className={`${stageInfo.color} ${stage !== 'complete' ? 'animate-spin' : ''}`} />
                                <span className={`text-sm font-medium ${stageInfo.color}`}>
                                    {stageInfo.text}
                                </span>
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
};

export default Import;
