import { FileText, Trash2, Calendar, Pencil, Check, X, Mail } from 'lucide-react';
import { useState } from 'react';
import EmailPreviewModal from './EmailPreviewModal';
import { SmtpConfig } from './Settings';
import { EmailTemplate } from '../App';
import { ToastType } from './ui/Toast';

interface HistoryItem {
    id: string;
    date: string;
    transcription: string; // This might be raw text or path?
    summary: string;
    subject?: string;
    filename?: string;
}

interface HistoryViewProps {
    history: HistoryItem[];
    onLoad: (item: HistoryItem) => void;
    onDelete: (id: string) => void;
    onRename: (id: string, newSubject: string) => void;
    smtpConfig: SmtpConfig;
    emailTemplates: EmailTemplate[];
    addToast: (message: string, type: ToastType, duration?: number) => void;
}

export default function HistoryView({ history, onLoad, onDelete, onRename, smtpConfig, emailTemplates, addToast }: HistoryViewProps) {
    const [editingId, setEditingId] = useState<string | null>(null);
    const [editValue, setEditValue] = useState("");
    const [emailModalItem, setEmailModalItem] = useState<HistoryItem | null>(null);

    const startEditing = (item: HistoryItem) => {
        setEditingId(item.id);
        setEditValue(item.subject || "Untitled Recording");
    };

    const saveEdit = () => {
        if (editingId && editValue.trim()) {
            onRename(editingId, editValue.trim());
            setEditingId(null);
        }
    };

    const cancelEdit = () => {
        setEditingId(null);
        setEditValue("");
    };

    return (
        <div className="flex flex-col w-full h-full bg-background p-6">
            <h1 className="text-2xl font-bold mb-6 flex items-center gap-2">
                <FileText className="w-8 h-8" />
                Recording History
            </h1>

            {history.length === 0 ? (
                <div className="flex-1 flex flex-col items-center justify-center text-muted-foreground">
                    <FileText size={48} className="mb-4 opacity-20" />
                    <p>No history found.</p>
                </div>
            ) : (
                <div className="flex-1 overflow-y-auto space-y-3 pr-2">
                    {history.map(item => (
                        <div key={item.id} className="bg-card border border-border rounded-xl p-4 hover:shadow-md transition-all group">
                            <div className="flex justify-between items-start">
                                <div className="flex-1">
                                    {editingId === item.id ? (
                                        <div className="flex items-center gap-2 mb-2" onClick={(e) => e.stopPropagation()}>
                                            <input
                                                autoFocus
                                                type="text"
                                                className="flex-1 bg-background border border-input rounded px-2 py-1 text-sm font-semibold focus:outline-none focus:ring-1 focus:ring-ring"
                                                value={editValue}
                                                onChange={(e) => setEditValue(e.target.value)}
                                                onKeyDown={(e) => {
                                                    if (e.key === 'Enter') saveEdit();
                                                    if (e.key === 'Escape') cancelEdit();
                                                }}
                                            />
                                            <button onClick={saveEdit} className="p-1 text-green-500 hover:bg-green-500/10 rounded">
                                                <Check size={16} />
                                            </button>
                                            <button onClick={cancelEdit} className="p-1 text-muted-foreground hover:bg-muted rounded">
                                                <X size={16} />
                                            </button>
                                        </div>
                                    ) : (
                                        <div
                                            className="cursor-pointer"
                                            onClick={() => onLoad(item)}
                                        >
                                            <h3 className="text-lg font-semibold group-hover:text-primary transition-colors mb-1 flex items-center gap-2">
                                                {item.subject || "Untitled Recording"}
                                                <button
                                                    onClick={(e) => { e.stopPropagation(); startEditing(item); }}
                                                    className="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-foreground p-1 rounded hover:bg-muted transition-all"
                                                    title="Rename"
                                                >
                                                    <Pencil size={14} />
                                                </button>
                                            </h3>
                                        </div>
                                    )}

                                    <div className="flex items-center gap-2 text-xs text-muted-foreground mb-2" onClick={() => !editingId && onLoad(item)}>
                                        <Calendar size={12} />
                                        {item.date}
                                        {item.filename && <span className="bg-secondary px-1.5 py-0.5 rounded text-[10px] font-mono">{item.filename}</span>}
                                    </div>
                                    <p className="text-sm text-foreground/70 line-clamp-2 cursor-pointer" onClick={() => !editingId && onLoad(item)}>
                                        {item.summary ? item.summary.substring(0, 150) + "..." : "No summary available."}
                                    </p>
                                </div>

                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={(e) => { e.stopPropagation(); setEmailModalItem(item); }}
                                        className="text-muted-foreground hover:text-primary p-2 rounded-lg hover:bg-primary/10 transition-colors opacity-0 group-hover:opacity-100"
                                        title="Send Email"
                                    >
                                        <Mail size={18} />
                                    </button>
                                    <button
                                        onClick={(e) => { e.stopPropagation(); onDelete(item.id); }}
                                        className="text-muted-foreground hover:text-destructive p-2 rounded-lg hover:bg-destructive/10 transition-colors opacity-0 group-hover:opacity-100"
                                        title="Delete"
                                    >
                                        <Trash2 size={18} />
                                    </button>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            <EmailPreviewModal
                isOpen={emailModalItem !== null}
                onClose={() => setEmailModalItem(null)}
                initialRecipients={[]}
                initialSubject={emailModalItem?.subject || "Meeting Summary"}
                initialBody={emailModalItem?.summary || ""}
                emailTemplates={emailTemplates}
                smtpConfig={smtpConfig ? { ...smtpConfig, port: Number(smtpConfig.port) } : null}
                addToast={addToast}
            />
        </div>
    );
}
