import React, { useState, useEffect } from 'react';
import { Mail, X, Send } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';

import { EmailTemplate } from '../App';

interface EmailPreviewModalProps {
    isOpen: boolean;
    onClose: () => void;
    initialRecipients: string[];
    initialSubject: string;
    initialBody: string;
    emailTemplates: EmailTemplate[]; // New prop
    smtpConfig: {
        host: string;
        port: number;
        user: string;
        pass: string;
        sender: string;
        senderName?: string;
    } | null;
    addToast: (msg: string, type: 'success' | 'error' | 'info') => void;
}

// Basic Markdown to HTML converter for email body
const formatMarkdownToHtml = (markdown: string): string => {
    let html = markdown
        // Headers
        .replace(/^# (.*$)/gim, '<h1 style="color: #1a1a1a; font-size: 24px; margin-top: 20px; margin-bottom: 10px; border-bottom: 2px solid #eaeaea; padding-bottom: 10px;">$1</h1>')
        .replace(/^## (.*$)/gim, '<h2 style="color: #2d2d2d; font-size: 20px; margin-top: 25px; margin-bottom: 10px;">$1</h2>')
        .replace(/^### (.*$)/gim, '<h3 style="color: #404040; font-size: 18px; margin-top: 20px; margin-bottom: 8px;">$1</h3>')

        // Bold
        .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')

        // Lists
        .replace(/^\s*-\s+(.*$)/gim, '<li style="margin-bottom: 5px;">$1</li>')
        // Wrap lists (simple heuristic)
        .replace(/(<li.*<\/li>)/gim, '<ul>$1</ul>')
        .replace(/<\/ul>\s*<ul>/gim, '') // Merge adjacent lists

        // Tables (Basic support for the format used in prompts)
        .replace(/\| (.*?) \| (.*?) \| (.*?) \|/gim, '<tr><td style="border: 1px solid #ddd; padding: 8px;">$1</td><td style="border: 1px solid #ddd; padding: 8px;">$2</td><td style="border: 1px solid #ddd; padding: 8px;">$3</td></tr>')
        .replace(/\| :--- \| :--- \| :--- \|/gim, '') // Remove separator row
        // Tables wrapping (heuristic)
        .replace(/(<tr>.*<\/tr>)/gim, '<table style="width: 100%; border-collapse: collapse; margin-top: 10px; margin-bottom: 20px;">$1</table>')
        .replace(/<\/table>\s*<table.*?>/gim, '') // Merge adjacent tables

        // Paragraphs (double newlines)
        .replace(/\n\n/gim, '<br><br>');

    return html;
};

const EmailPreviewModal: React.FC<EmailPreviewModalProps> = ({
    isOpen, onClose, initialRecipients, initialSubject, initialBody, smtpConfig, addToast, emailTemplates
}) => {
    const [recipients, setRecipients] = useState<string>(initialRecipients.join(', '));
    const [subject, setSubject] = useState(initialSubject);
    const [body, setBody] = useState(initialBody);
    const [sending, setSending] = useState(false);
    const [selectedTemplateId, setSelectedTemplateId] = useState<string>('');

    const [activeTab, setActiveTab] = useState<'preview' | 'source'>('preview');

    const generateHtmlBody = (content: string, title: string) => {
        // Check if it's a full HTML document
        if (/^\s*<!DOCTYPE html/i.test(content) || /^\s*<html/i.test(content)) {
            return content;
        }

        // Simple heuristic: if it looks like HTML fragment (div, p, table), treat as HTML. Otherwise, markdown.
        const isHtmlFragment = /^\s*<(div|p|table|section|header|footer)/i.test(content);
        const formattedBody = isHtmlFragment ? content : formatMarkdownToHtml(content);

        return `
<!DOCTYPE html>
<html>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background-color: #f4f4f5; color: #333;">
    <div style="max-width: 640px; margin: 40px auto; background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
        <!-- Header -->
        <div style="background-color: #000000; padding: 30px 40px;">
            <h1 style="color: #ffffff; margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.5px;">${title}</h1>
        </div>
        <!-- Content -->
        <div style="padding: 40px; line-height: 1.6;">
            ${formattedBody}
        </div>
        <!-- Footer -->
        <div style="background-color: #f9fafb; padding: 20px 40px; text-align: center; border-top: 1px solid #e5e7eb;">
            <p style="margin: 0; font-size: 12px; color: #6b7280;">
                Generated by <strong>Hearbit AI</strong> • Secure & Local Meeting Intelligence
            </p>
        </div>
    </div>
</body>
</html>`;
    };

    useEffect(() => {
        if (isOpen) {
            setRecipients(initialRecipients.join(', '));
            setSubject(initialSubject);
            // Default: Wrap initialBody in our HTML template
            setBody(generateHtmlBody(initialBody, initialSubject));
            setSelectedTemplateId('');
        }
    }, [isOpen, initialRecipients, initialSubject, initialBody]);

    const handleTemplateChange = (tmplId: string) => {
        setSelectedTemplateId(tmplId);
        if (!tmplId) return;

        const tmpl = emailTemplates.find(t => t.id === tmplId);
        if (tmpl) {
            // Replace placeholders
            const dateStr = new Date().toLocaleDateString();
            let newSub = tmpl.subject.replace(/{{date}}/g, dateStr).replace(/{{subject}}/g, "Meeting");

            // Clean up JSON if necessary (e.g. remove markdown code blocks ```json ... ```)
            let cleanSummary = initialBody;
            if (initialBody.trim().startsWith('```')) {
                cleanSummary = initialBody.replace(/^```(json)?/i, '').replace(/```$/, '').trim();
            }

            let newBody = tmpl.body
                .replace(/{{date}}/g, dateStr)
                .replace(/{{subject}}/g, "the meeting")
                .replace(/{{summary}}/g, cleanSummary);

            setSubject(newSub);
            setBody(generateHtmlBody(newBody, newSub));
        }
    };

    if (!isOpen) return null;

    const handleSend = async () => {
        if (!smtpConfig || !smtpConfig.host) {
            addToast("SMTP Settings not configured. Please go to Settings.", "error");
            return;
        }

        setSending(true);
        try {
            // Split recipients by comma/semicolon and clean
            const toList = recipients.split(/[,;]/).map(s => s.trim()).filter(s => s.length > 0);

            await invoke('send_smtp_email', {
                config: {
                    host: smtpConfig.host,
                    port: Number(smtpConfig.port),
                    username: smtpConfig.user,
                    password: smtpConfig.pass,
                    sender_email: smtpConfig.sender,
                    sender_name: smtpConfig.senderName
                },
                message: {
                    to: toList,
                    subject: subject,
                    body_html: body
                }
            });
            addToast("Email sent successfully!", "success");
            onClose();
        } catch (e) {
            console.error(e);
            addToast(`Failed to send email: ${e}`, "error");
        } finally {
            setSending(false);
        }
    };

    return (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4">
            <div className="bg-background border border-border rounded-xl shadow-2xl w-full max-w-3xl flex flex-col h-[90vh]">
                <div className="p-4 border-b border-border flex justify-between items-center shrink-0">
                    <h3 className="font-semibold flex items-center gap-2">
                        <Mail size={18} /> Send Summary via Email
                    </h3>
                    <button onClick={onClose} className="text-muted-foreground hover:text-foreground">
                        <X size={20} />
                    </button>
                </div>

                <div className="p-4 space-y-4 overflow-y-auto flex-1 flex flex-col">
                    {/* Template Selector */}
                    {emailTemplates.length > 0 && (
                        <div className="bg-secondary/20 p-3 rounded-lg border border-border/50">
                            <label className="block text-xs font-semibold text-muted-foreground mb-1 uppercase tracking-wide">
                                Load Template
                            </label>
                            <select
                                value={selectedTemplateId}
                                onChange={(e) => handleTemplateChange(e.target.value)}
                                className="w-full text-sm p-2 rounded border border-border bg-background outline-none focus:ring-2 focus:ring-primary"
                            >
                                <option value="">-- Select a Template --</option>
                                {emailTemplates.map(t => (
                                    <option key={t.id} value={t.id}>{t.name}</option>
                                ))}
                            </select>
                        </div>
                    )}

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label className="block text-xs font-semibold text-muted-foreground mb-1">To</label>
                            <input
                                type="text"
                                value={recipients}
                                onChange={(e) => setRecipients(e.target.value)}
                                className="w-full p-2 rounded border border-border bg-secondary text-sm focus:ring-2 focus:ring-primary outline-none"
                                placeholder="email@example.com, other@example.com"
                            />
                        </div>
                        <div>
                            <label className="block text-xs font-semibold text-muted-foreground mb-1">Subject</label>
                            <input
                                type="text"
                                value={subject}
                                onChange={(e) => setSubject(e.target.value)}
                                className="w-full p-2 rounded border border-border bg-secondary text-sm focus:ring-2 focus:ring-primary outline-none"
                            />
                        </div>
                    </div>

                    <div className="flex-1 flex flex-col min-h-0 border border-border rounded-lg overflow-hidden">
                        {/* Tabs */}
                        <div className="flex border-b border-border bg-secondary/30">
                            <button
                                onClick={() => setActiveTab('preview')}
                                className={`px-4 py-2 text-sm font-medium transition-colors ${activeTab === 'preview' ? 'bg-background text-primary border-r border-border' : 'text-muted-foreground hover:text-foreground'}`}
                            >
                                Preview
                            </button>
                            <button
                                onClick={() => setActiveTab('source')}
                                className={`px-4 py-2 text-sm font-medium transition-colors ${activeTab === 'source' ? 'bg-background text-primary border-l border-r border-border' : 'text-muted-foreground hover:text-foreground'}`}
                            >
                                HTML Source
                            </button>
                        </div>

                        {/* Content */}
                        <div className="flex-1 bg-background overflow-hidden relative">
                            {activeTab === 'preview' ? (
                                <div className="w-full h-full bg-white text-black">
                                    <iframe
                                        srcDoc={body}
                                        className="w-full h-full border-none"
                                        title="Email Preview"
                                        sandbox="allow-same-origin allow-scripts"
                                    />
                                </div>
                            ) : (
                                <textarea
                                    value={body}
                                    onChange={(e) => setBody(e.target.value)}
                                    className="w-full h-full p-4 text-sm font-mono resize-none focus:outline-none bg-background text-foreground"
                                    placeholder="<html>...</html>"
                                />
                            )}
                        </div>
                    </div>
                </div>

                <div className="p-4 border-t border-border flex justify-end gap-2 bg-secondary/10 rounded-b-xl">
                    <button
                        onClick={onClose}
                        className="px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
                    >
                        Cancel
                    </button>
                    <button
                        onClick={handleSend}
                        disabled={sending}
                        className="px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-all flex items-center gap-2 disabled:opacity-50"
                    >
                        {sending ? 'Sending...' : <><Send size={16} /> Send Email</>}
                    </button>
                </div>
            </div>
        </div>
    );
};

export default EmailPreviewModal;
