import React, { useState } from 'react';
import ReactMarkdown from 'react-markdown';
import { Copy, Check, Mail, RefreshCw, Wand2 } from 'lucide-react';
import EmailPreviewModal from './EmailPreviewModal';
import { SmtpConfig } from './Settings';
import { ToastType } from './ui/Toast';
import { PromptTemplate, EmailTemplate } from '../App';
import { invoke } from '@tauri-apps/api/core';

interface TranscriptionViewProps {
    transcription: string;
    summary: string;
    smtpConfig: SmtpConfig;
    apiKey: string;
    productId: string;
    prompts: PromptTemplate[];
    emailTemplates: EmailTemplate[];
    onUpdateSummary: (newSummary: string) => void;
    addToast: (message: string, type: ToastType, duration?: number) => void;
}

const TranscriptionView: React.FC<TranscriptionViewProps> = ({
    transcription, summary, smtpConfig, apiKey, productId, prompts, emailTemplates, onUpdateSummary, addToast
}) => {
    const [copiedTrans, setCopiedTrans] = useState(false);
    const [copiedSum, setCopiedSum] = useState(false);
    const [isEmailModalOpen, setIsEmailModalOpen] = useState(false);

    // Regenerate State
    const [isRegenerating, setIsRegenerating] = useState(false);
    const [showRegenOptions, setShowRegenOptions] = useState(false);
    const [regenModel, setRegenModel] = useState<string>('mixtral');
    const [regenPromptId, setRegenPromptId] = useState<string>('');
    const [availableModels, setAvailableModels] = useState<Array<{ id: string, name: string }>>([]);

    React.useEffect(() => {
        if (showRegenOptions && availableModels.length === 0) {
            loadModels();
        }
        if (prompts.length > 0 && !regenPromptId) {
            setRegenPromptId(prompts[0].id);
        }
    }, [showRegenOptions]);

    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:", e);
        }
    };

    const handleRegenerate = async () => {
        if (!transcription || !apiKey || !productId) return;

        setIsRegenerating(true);
        try {
            const prompt = prompts.find(p => p.id === regenPromptId)?.content || "Summarize this.";

            const newSummary = await invoke<string>('summarize_text', {
                text: transcription,
                apiKey,
                productId,
                prompt,
                model: regenModel
            });

            onUpdateSummary(newSummary);
            addToast('Summary regenerated!', 'success');
            setShowRegenOptions(false);
        } catch (e) {
            console.error(e);
            addToast(`Regeneration failed: ${e}`, 'error');
        } finally {
            setIsRegenerating(false);
        }
    };

    const handleCopy = async (text: string, isSummary: boolean) => {
        if (!text) return;
        try {
            await navigator.clipboard.writeText(text);
            if (isSummary) {
                setCopiedSum(true);
                setTimeout(() => setCopiedSum(false), 2000);
            } else {
                setCopiedTrans(true);
                setTimeout(() => setCopiedTrans(false), 2000);
            }
        } catch (err) {
            console.error('Failed to copy!', err);
        }
    };

    return (
        <div className="flex flex-col h-full bg-background font-mono text-sm overflow-hidden">
            <div className="flex-1 flex flex-col md:flex-row divide-y md:divide-y-0 md:divide-x divide-border/40 overflow-hidden">
                {/* Original Transcription */}
                <div className="flex-1 flex flex-col min-h-0">
                    <div className="p-3 border-b border-border/40 bg-secondary/20 flex justify-between items-center shrink-0">
                        <span className="text-xs uppercase tracking-wider text-muted-foreground font-semibold">Original Transcription</span>
                        <button
                            onClick={() => handleCopy(transcription, false)}
                            className="text-xs flex items-center gap-1 hover:text-primary transition-colors disabled:opacity-50"
                            disabled={!transcription}
                        >
                            {copiedTrans ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
                            {copiedTrans ? 'Copied' : 'Copy'}
                        </button>
                    </div>
                    <div className="flex-1 overflow-y-auto p-4 bg-background">
                        {transcription ? (
                            <p className="whitespace-pre-wrap text-foreground leading-relaxed">{transcription}</p>
                        ) : (
                            <p className="text-muted-foreground italic text-xs">No transcription available yet...</p>
                        )}
                    </div>
                </div>

                {/* AI Summary */}
                <div className="flex-1 flex flex-col min-h-0">
                    <div className="p-3 border-b border-border/40 bg-secondary/20 flex justify-between items-center shrink-0">
                        <span className="text-xs uppercase tracking-wider text-muted-foreground font-semibold">AI Summary</span>

                        <div className="flex items-center gap-2">
                            {/* Regenerate Trigger */}
                            <button
                                onClick={() => setShowRegenOptions(!showRegenOptions)}
                                disabled={!transcription || !apiKey}
                                className={`text-xs flex items-center gap-1 transition-colors px-2 py-1 rounded ${showRegenOptions ? 'bg-primary text-primary-foreground' : 'hover:bg-secondary text-muted-foreground hover:text-foreground'}`}
                                title="Regenerate Summary"
                            >
                                <RefreshCw size={12} className={isRegenerating ? "animate-spin" : ""} />
                                {showRegenOptions ? 'Close' : 'Redo'}
                            </button>

                            <div className="h-4 w-px bg-border/50 mx-1"></div>

                            <div className="flex items-center gap-3">
                                <button
                                    onClick={() => setIsEmailModalOpen(true)}
                                    disabled={!summary}
                                    className="text-xs flex items-center gap-1 hover:text-primary transition-colors disabled:opacity-50"
                                    title="Send via Email"
                                >
                                    <Mail size={14} /> Email
                                </button>
                                <button
                                    onClick={() => handleCopy(summary, true)}
                                    className="text-xs flex items-center gap-1 hover:text-primary transition-colors disabled:opacity-50"
                                    disabled={!summary}
                                >
                                    {copiedSum ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
                                    {copiedSum ? 'Copied' : 'Copy'}
                                </button>
                            </div>
                        </div>
                    </div>
                    {/* Regenerate Panel */}
                    {showRegenOptions && (
                        <div className="p-3 bg-secondary/30 border-b border-border/40 grid grid-cols-1 md:grid-cols-[1fr_1fr_auto] gap-2 items-end animate-in slide-in-from-top-2 duration-200">
                            <div>
                                <label className="text-[10px] uppercase font-bold text-muted-foreground block mb-1">Model</label>
                                <select
                                    value={regenModel}
                                    onChange={(e) => setRegenModel(e.target.value)}
                                    className="w-full text-xs p-1.5 rounded border border-border bg-background"
                                >
                                    {availableModels.length === 0 && <option value="mixtral">Loading...</option>}
                                    {availableModels.map(m => <option key={m.id} value={m.id}>{m.name}</option>)}
                                </select>
                            </div>
                            <div>
                                <label className="text-[10px] uppercase font-bold text-muted-foreground block mb-1">Template</label>
                                <select
                                    value={regenPromptId}
                                    onChange={(e) => setRegenPromptId(e.target.value)}
                                    className="w-full text-xs p-1.5 rounded border border-border bg-background"
                                >
                                    {prompts.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                                </select>
                            </div>
                            <button
                                onClick={handleRegenerate}
                                disabled={isRegenerating}
                                className="text-xs bg-primary text-primary-foreground px-3 py-1.5 rounded font-semibold hover:bg-primary/90 disabled:opacity-50 flex items-center gap-2 h-[30px]"
                            >
                                <Wand2 size={12} /> {isRegenerating ? 'Running...' : 'Generate New'}
                            </button>
                        </div>
                    )}
                    <div className="flex-1 overflow-y-auto p-4 bg-secondary/10 prose prose-sm max-w-none prose-p:text-foreground/90 prose-headings:text-foreground prose-strong:text-foreground prose-ul:text-foreground/90">
                        {summary ? (
                            <ReactMarkdown>{summary}</ReactMarkdown>
                        ) : (
                            <p className="text-muted-foreground italic text-xs">No summary available yet...</p>
                        )}
                    </div>
                </div>
            </div>

            <EmailPreviewModal
                isOpen={isEmailModalOpen}
                onClose={() => setIsEmailModalOpen(false)}
                initialRecipients={[]} // TODO: Pass attendees from meeting
                initialSubject="Meeting Summary" // Default subject
                initialBody={summary}
                emailTemplates={emailTemplates} // Pass templates
                smtpConfig={smtpConfig ? { ...smtpConfig, port: Number(smtpConfig.port) } : null}
                addToast={addToast}
            />
        </div >
    );
};

export default TranscriptionView;
