import React, { useState } from 'react';
import { X, Eye, Send, Code } from 'lucide-react';
import { EmailTemplate } from '../App';
import { SmtpConfig } from './Settings';
import { invoke } from '@tauri-apps/api/core';

interface EmailTemplateEditorProps {
    isOpen: boolean;
    onClose: () => void;
    template: EmailTemplate | null;
    onSave: (template: EmailTemplate) => void;
    smtpConfig: SmtpConfig;
    addToast: (msg: string, type: 'success' | 'error' | 'info') => void;
}

const EmailTemplateEditor: React.FC<EmailTemplateEditorProps> = ({
    isOpen, onClose, template, onSave, smtpConfig, addToast
}) => {
    const [name, setName] = useState('');
    const [subject, setSubject] = useState('');
    const [body, setBody] = useState('');
    const [activeTab, setActiveTab] = useState<'edit' | 'preview'>('edit');
    const [testEmail, setTestEmail] = useState('');
    const [sendingTest, setSendingTest] = useState(false);

    // Load template data when it changes or opens
    React.useEffect(() => {
        if (template) {
            setName(template.name);
            setSubject(template.subject);
            setBody(template.body);
        } else {
            // New template defaults
            setName('New Template');
            setSubject('Subject: {{subject}}');
            setBody('{{summary}}');
        }
    }, [template, isOpen]);

    if (!isOpen) return null;

    const handleSave = () => {
        if (!template) {
            // Create new
            onSave({
                id: Date.now().toString(),
                name,
                subject,
                body
            });
        } else {
            // Update existing
            onSave({
                ...template,
                name,
                subject,
                body
            });
        }
        onClose();
    };

    const handleSendTest = async () => {
        if (!testEmail) {
            addToast('Please enter a test email address', 'error');
            return;
        }
        if (!smtpConfig.host) {
            addToast('SMTP settings missing in main settings', 'error');
            return;
        }

        setSendingTest(true);
        try {
            // Basic substitution for preview
            // Basic substitution for preview
            // If markdown (simple check), convert? For now, we assume user is writing HTML or we leave it raw if they want.
            // But the request is to "use HTML format".
            // If it looks like HTML, use it. If not, maybe wrap in <p>?
            // For the test email, we pass it as body_html.

            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: [testEmail],
                    subject: `[TEST] ${subject}`,
                    body_html: body // Send raw body (HTML)
                }
            });
            addToast('Test email sent!', 'success');
        } catch (e) {
            console.error(e);
            addToast(`Failed to send test: ${e}`, 'error');
        } finally {
            setSendingTest(false);
        }
    };

    return (
        <div className="fixed inset-0 z-[60] bg-black/50 flex items-center justify-center p-4">
            <div className="bg-background border border-border rounded-lg shadow-xl w-full max-w-4xl flex flex-col h-[85vh]">
                {/* Header */}
                <div className="p-4 border-b border-border flex justify-between items-center bg-secondary/20">
                    <h3 className="font-semibold text-lg flex items-center gap-2">
                        {template ? 'Edit Email Template' : 'Create Email Template'}
                    </h3>
                    <button onClick={onClose} className="text-muted-foreground hover:text-foreground">
                        <X size={20} />
                    </button>
                </div>

                {/* Content */}
                <div className="flex-1 flex flex-col min-h-0 container mx-auto p-4 gap-4">
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-xs font-semibold text-muted-foreground mb-1">Template Name</label>
                            <input
                                type="text"
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                className="w-full p-2 rounded border border-border bg-background focus:ring-2 focus:ring-primary outline-none"
                            />
                        </div>
                        <div>
                            <label className="block text-xs font-semibold text-muted-foreground mb-1">Subject Pattern</label>
                            <input
                                type="text"
                                value={subject}
                                onChange={(e) => setSubject(e.target.value)}
                                className="w-full p-2 rounded border border-border bg-background focus:ring-2 focus:ring-primary outline-none"
                            />
                        </div>
                    </div>

                    <div className="flex bg-secondary/30 border border-border rounded-t-lg mt-2">
                        <button
                            onClick={() => setActiveTab('edit')}
                            className={`px-4 py-2 text-sm font-medium flex items-center gap-2 ${activeTab === 'edit' ? 'bg-background border-b-0 text-primary' : 'text-muted-foreground hover:text-foreground'}`}
                        >
                            <Code size={16} /> Edit HTML
                        </button>
                        <button
                            onClick={() => setActiveTab('preview')}
                            className={`px-4 py-2 text-sm font-medium flex items-center gap-2 ${activeTab === 'preview' ? 'bg-background border-b-0 text-primary' : 'text-muted-foreground hover:text-foreground'}`}
                        >
                            <Eye size={16} /> Preview
                        </button>
                    </div>

                    <div className="flex-1 border border-t-0 border-border rounded-b-lg bg-background overflow-hidden relative">
                        {activeTab === 'edit' ? (
                            <textarea
                                value={body}
                                onChange={(e) => setBody(e.target.value)}
                                className="w-full h-full p-4 font-mono text-sm resize-none focus:outline-none bg-background text-foreground"
                                placeholder="<html><body>...</body></html> or Markdown"
                            />
                        ) : (
                            <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"
                                />
                            </div>
                        )}
                    </div>

                    {/* Test Email Section */}
                    <div className="flex items-center gap-2 pt-2 border-t border-border/50">
                        <input
                            type="email"
                            value={testEmail}
                            onChange={(e) => setTestEmail(e.target.value)}
                            placeholder="test@example.com"
                            className="flex-1 p-2 rounded border border-border bg-secondary/50 text-sm focus:ring-2 focus:ring-primary outline-none"
                        />
                        <button
                            onClick={handleSendTest}
                            disabled={sendingTest || !testEmail}
                            className="px-4 py-2 text-sm font-medium bg-secondary hover:bg-secondary/80 text-foreground rounded border border-border transition-colors disabled:opacity-50 flex items-center gap-2"
                        >
                            {sendingTest ? 'Sending...' : <><Send size={14} /> Send Test</>}
                        </button>
                    </div>
                </div>

                {/* Footer */}
                <div className="p-4 border-t border-border flex justify-end gap-2 bg-secondary/10">
                    <button
                        onClick={onClose}
                        className="px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
                    >
                        Cancel
                    </button>
                    <button
                        onClick={handleSave}
                        className="px-6 py-2 text-sm font-medium bg-primary text-primary-foreground rounded hover:bg-primary/90 transition-colors"
                    >
                        Save Template
                    </button>
                </div>
            </div>
        </div>
    );
};

export default EmailTemplateEditor;
