import React, { useState, useEffect } from 'react';
import { Mic, Square } from 'lucide-react';
import { invoke } from "@tauri-apps/api/core";
import logo from '../assets/logo.png'; // Import logo

interface PromptTemplate {
    id: string;
    name: string;
    content: string;
}

interface HistoryItem {
    id: string;
    date: string;
    transcription: string;
    summary: string;
}

interface RecorderProps {
    apiKey: string;
    productId: string;
    prompts: PromptTemplate[];
    onOpenSettings: () => void;
    // Lifted State Props (still passed for state management, though unused in view)
    transcription: string;
    setTranscription: (val: string) => void;
    summary: string;
    setSummary: (val: string) => void;
    // History Props
    history: HistoryItem[];
    onSaveToHistory: (t?: string, s?: string) => void;
    onDeleteHistory: (id: string) => void;
    onLoadHistory: (item: HistoryItem) => void;
    savePath: string | null;
    onRecordingComplete: () => void;
}

interface AudioDevice {
    id: string;
    name: string;
}

const Recorder: React.FC<RecorderProps> = ({
    apiKey, productId, prompts,
    setTranscription, setSummary,
    onSaveToHistory, savePath, onRecordingComplete
}) => {
    const [isRecording, setIsRecording] = useState(false);
    const [isPaused, setIsPaused] = useState(false);
    const [status, setStatus] = useState<string>('Ready to record');
    const [selectedDevice, setSelectedDevice] = useState<string>('');
    const [selectedPromptId, setSelectedPromptId] = useState<string>('');
    const [selectedModel, setSelectedModel] = useState<string>('mixtral');
    const [devices, setDevices] = useState<AudioDevice[]>([]);
    const [availableModels, setAvailableModels] = useState<Array<{ id: string, name: string }>>([]);

    useEffect(() => {
        loadDevices();
        if (apiKey && productId) {
            loadModels();
        }
    }, [apiKey, productId]);

    const loadModels = async () => {
        try {
            const models = await invoke<Array<{ id: string, name: string }>>('get_available_models', { apiKey, productId });
            if (models && models.length > 0) {
                models.sort((a, b) => a.name.localeCompare(b.name));
                setAvailableModels(models);
            }
        } catch (e) {
            console.error("Failed to load models dynamically, using defaults:", e);
        }
    };

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

    const loadDevices = async () => {
        try {
            const devList = await invoke<AudioDevice[]>('get_input_devices');
            // Alias BlackHole
            const aliasedDevs = devList.map(d => ({
                ...d,
                name: d.name.includes('BlackHole') ? 'Hearbit Virtual Mic (BlackHole)' : d.name
            }));
            setDevices(aliasedDevs);

            // Select Hearbit mic by default if available and no selection made
            if (!selectedDevice) {
                const vb = aliasedDevs.find(d => d.name.includes('Hearbit Virtual Mic'));
                if (vb) {
                    setSelectedDevice(vb.id);
                } else if (aliasedDevs.length > 0) {
                    setSelectedDevice(aliasedDevs[0].id);
                }
            }
        } catch (e) {
            console.error('Failed to load devices', e);
        }
    };

    const openAudioSetup = async () => {
        try {
            await invoke('open_audio_midi_setup');
        } catch (e) {
            console.error(e);
            setStatus('Failed to open Audio Setup');
        }
    };

    const startRecording = async () => {
        try {
            setStatus('Starting...');
            await invoke('start_recording', { deviceId: selectedDevice, savePath: savePath || null });
            setIsRecording(true);
            setIsPaused(false);
            setTranscription('');
            setSummary('');
            setStatus('Recording...');
        } catch (e) {
            console.error(e);
            setStatus(`Error: ${e}`);
            setIsRecording(false);
        }
    };

    const togglePause = async () => {
        try {
            if (isPaused) {
                await invoke('resume_recording');
                setIsPaused(false);
                setStatus('Recording...');
            } else {
                await invoke('pause_recording');
                setIsPaused(true);
                setStatus('Paused');
            }
        } catch (e) {
            console.error("Pause/Resume error:", e);
        }
    };

    const stopRecording = async () => {
        try {
            setIsRecording(false);
            setIsPaused(false);
            setStatus('Processing...');
            const filePath = await invoke<string>('stop_recording');

            setStatus('Transcribing (Infomaniak Whisper)...');
            const transText = await invoke<string>('transcribe_audio', {
                filePath,
                apiKey,
                productId
            });
            setTranscription(transText);

            // Check if transcription is empty or just whitespace
            if (!transText || transText.trim().length === 0) {
                setStatus('Done (No speech detected)');
                setTranscription('(No speech detected. Check your microphone settings.)');
                setTimeout(() => setStatus('Ready to record'), 3000);
                return;
            }

            // Find selected prompt content
            const activePrompt = prompts.find(p => p.id === selectedPromptId);
            const promptContent = activePrompt ? activePrompt.content : "Summarize this.";

            setStatus(`Summarizing (${selectedModel})...`);
            const sumText = await invoke<string>('summarize_text', {
                text: transText,
                apiKey,
                productId,
                prompt: promptContent,
                model: selectedModel
            });
            setSummary(sumText);

            // Auto-save to history
            onSaveToHistory(transText, sumText);

            setStatus('Done!');
            onRecordingComplete(); // Auto-switch tab
            setTimeout(() => setStatus('Ready to record'), 3000);
        } catch (e) {
            console.error(e);
            setStatus(`Error: ${e}`);
        }
    };

    return (
        <div className="flex flex-col w-full h-full bg-background relative">
            {/* Fixed Header */}
            <div className="w-full flex justify-center items-center p-6 shrink-0">
                <img src={logo} alt="Logo" className="h-12 object-contain" />
            </div>

            {/* Scrollable Content */}
            <div className="flex-1 overflow-y-auto p-6 flex flex-col items-center pb-20">
                <div className="mb-6 relative shrink-0">
                    <div className={`w-32 h-32 rounded-full flex items-center justify-center transition-all duration-300 ${isRecording ? (isPaused ? 'bg-yellow-500/10' : 'bg-red-500/10 animate-pulse') : 'bg-secondary'}`}>
                        {isRecording ? (
                            <div className={`w-24 h-24 rounded-full flex items-center justify-center shadow-[0_0_20px_rgba(239,68,68,0.5)] ${isPaused ? 'bg-yellow-500' : 'bg-red-500'}`}>
                                <Mic size={40} className="text-white animate-bounce" />
                            </div>
                        ) : (
                            <div className="w-24 h-24 rounded-full bg-primary flex items-center justify-center">
                                <Mic size={40} className="text-primary-foreground" />
                            </div>
                        )}
                    </div>
                </div>

                <h1 className="text-2xl font-bold mb-2 text-foreground">
                    {isRecording ? (isPaused ? 'Paused' : 'Listening...') : 'Ready to Record'}
                </h1>

                <p className="text-muted-foreground mb-6 text-center text-sm h-6">
                    {status}
                </p>

                <div className="w-full max-w-sm space-y-4 mb-6 shrink-0">
                    {!isRecording ? (
                        <button
                            onClick={startRecording}
                            disabled={!apiKey || !productId}
                            className="w-full py-4 text-lg 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"
                        >
                            {!apiKey ? 'Configure API Key First' : 'Start Recording'}
                        </button>
                    ) : (
                        <div className="flex gap-2 w-full">
                            <button
                                onClick={togglePause}
                                className={`flex-1 py-4 text-lg font-semibold rounded-lg transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2 ${isPaused
                                    ? 'bg-blue-600 text-white hover:bg-blue-700'
                                    : 'bg-yellow-500 text-white hover:bg-yellow-600'
                                    }`}
                            >
                                {isPaused ? 'Resume' : 'Pause'}
                            </button>
                            <button
                                onClick={stopRecording}
                                className="flex-1 py-4 text-lg font-semibold bg-destructive text-destructive-foreground rounded-lg hover:bg-destructive/90 transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2"
                            >
                                <Square size={20} fill="currentColor" />
                                Stop
                            </button>
                        </div>
                    )}

                    <div className="grid grid-cols-2 gap-4 pt-2">
                        <div>
                            <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block mb-1">
                                Input Device
                            </label>
                            <select
                                value={selectedDevice}
                                onChange={(e) => setSelectedDevice(e.target.value)}
                                className="w-full p-2 text-sm bg-secondary rounded border border-border outline-none focus:ring-2 focus:ring-primary"
                                disabled={isRecording}
                            >
                                {devices.map(d => (
                                    <option key={d.id} value={d.id}>{d.name}</option>
                                ))}
                                {devices.length === 0 && <option value="">Loading devices...</option>}
                            </select>
                        </div>
                        <div>
                            <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block mb-1">
                                LLM Model
                            </label>
                            <select
                                value={selectedModel}
                                onChange={(e) => setSelectedModel(e.target.value)}
                                className="w-full p-2 text-sm bg-secondary rounded border border-border outline-none focus:ring-2 focus:ring-primary"
                                disabled={isRecording}
                            >
                                {availableModels.map(m => (
                                    <option key={m.id} value={m.id}>{m.name}</option>
                                ))}
                            </select>
                        </div>
                    </div>

                    <div className="w-full">
                        <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)}
                            className="w-full p-2 text-sm bg-secondary rounded border border-border outline-none focus:ring-2 focus:ring-primary"
                            disabled={isRecording || prompts.length === 0}
                        >
                            {prompts.map(p => (
                                <option key={p.id} value={p.id}>{p.name}</option>
                            ))}
                            {prompts.length === 0 && <option value="">No templates</option>}
                        </select>
                    </div>

                    <div className="flex flex-col gap-2 mt-2 w-full">
                        <button
                            onClick={openAudioSetup}
                            className="text-xs text-muted-foreground hover:text-foreground w-full text-center border border-dashed border-border/50 rounded p-1"
                        >
                            Open Audio MIDI Setup (Configure Multi-Output)
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Recorder;
