import { useState, useEffect } from 'react';
import { Save, TestTube, Loader2, CheckCircle2, XCircle, ArrowLeft, Server, Mail, FileText } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { RichTextEditor } from './RichTextEditor';
import { sanitizeHtml } from '@/utils/sanitizeHtml';

interface MailSettings {
    host: string;
    port: string;
    user: string;
    pass: string;
    tls: boolean;
}

const emptySettings: MailSettings = {
    host: '',
    port: '',
    user: '',
    pass: '',
    tls: true,
};

interface SettingsPageProps {
    onBack?: () => void;
    onSaved?: () => void;
}

export function SettingsPage({ onBack, onSaved }: SettingsPageProps) {
    const { getToken } = useAuth();
    const [imap, setImap] = useState<MailSettings>({ ...emptySettings, port: '993' });
    const [smtp, setSmtp] = useState<MailSettings>({ ...emptySettings, port: '465' });
    const [signature, setSignature] = useState('');
    const [saving, setSaving] = useState(false);
    const [testing, setTesting] = useState(false);
    const [testResult, setTestResult] = useState<{ imap: boolean; smtp: boolean } | null>(null);
    const [saved, setSaved] = useState(false);
    const [error, setError] = useState('');
    const [loadingSettings, setLoadingSettings] = useState(true);

    // Load existing settings
    useEffect(() => {
        (async () => {
            try {
                const token = await getToken();
                const res = await fetch('/api/settings', {
                    headers: { Authorization: `Bearer ${token}` },
                });
                const data = await res.json();
                if (data.imap) {
                    setImap({
                        host: data.imap.host || '',
                        port: String(data.imap.port || '993'),
                        user: data.imap.user || '',
                        pass: data.imap.pass || '',
                        tls: data.imap.tls !== false,
                    });
                }
                if (data.smtp) {
                    setSmtp({
                        host: data.smtp.host || '',
                        port: String(data.smtp.port || '465'),
                        user: data.smtp.user || '',
                        pass: data.smtp.pass || '',
                        tls: data.smtp.tls !== false,
                    });
                }
                if (data.signature !== undefined) {
                    setSignature(data.signature);
                }
            } catch (e) {
                console.error('Failed to load settings:', e);
            } finally {
                setLoadingSettings(false);
            }
        })();
    }, [getToken]);

    const handleSave = async () => {
        setError('');
        setSaving(true);
        setSaved(false);

        try {
            const token = await getToken();

            // Sanitize signature HTML before sending to API
            let sanitizedSignature: string;
            try {
                sanitizedSignature = sanitizeHtml(signature);
            } catch (sanitizeError: any) {
                throw new Error(`Failed to sanitize signature: ${sanitizeError.message}`);
            }

            const res = await fetch('/api/settings', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${token}`,
                },
                body: JSON.stringify({ imap, smtp, signature: sanitizedSignature }),
            });

            if (!res.ok) {
                const data = await res.json();
                throw new Error(data.error || 'Failed to save settings');
            }

            setSaved(true);
            onSaved?.();
            setTimeout(() => setSaved(false), 3000);
        } catch (e: any) {
            setError(e.message);
        } finally {
            setSaving(false);
        }
    };

    const handleTest = async () => {
        setTestResult(null);
        setTesting(true);
        setError('');

        try {
            const token = await getToken();
            const res = await fetch('/api/settings/test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${token}`,
                },
                body: JSON.stringify({ imap, smtp }),
            });

            const data = await res.json();
            setTestResult(data);
        } catch (e: any) {
            setError(e.message);
        } finally {
            setTesting(false);
        }
    };

    const inputStyles =
        'w-full rounded-lg border border-gray-200 bg-gray-50 px-3.5 py-2.5 text-[14px] text-gray-900 outline-none placeholder:text-gray-400 focus:border-blue-300 focus:bg-white focus:ring-2 focus:ring-blue-100';

    const InputField = ({
        label,
        value,
        onChange,
        placeholder,
        type = 'text',
    }: {
        label: string;
        value: string;
        onChange: (v: string) => void;
        placeholder: string;
        type?: string;
    }) => (
        <div>
            <label className="mb-1.5 block text-[13px] font-medium text-gray-700">{label}</label>
            <input
                type={type}
                value={value}
                onChange={(e) => onChange(e.target.value)}
                className={inputStyles}
                placeholder={placeholder}
            />
        </div>
    );

    if (loadingSettings) {
        return (
            <div className="flex flex-1 items-center justify-center bg-white">
                <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
            </div>
        );
    }

    return (
        <div className="flex flex-1 flex-col overflow-y-auto bg-gray-50">
            {/* Header */}
            <div className="flex flex-shrink-0 items-center gap-3 border-b border-gray-200 bg-white px-6 py-4">
                {onBack && (
                    <button
                        onClick={onBack}
                        className="rounded-md p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
                    >
                        <ArrowLeft className="h-5 w-5" strokeWidth={1.75} />
                    </button>
                )}
                <h1 className="text-[18px] font-semibold text-gray-900">Mail Settings</h1>
            </div>

            <div className="mx-auto w-full max-w-2xl space-y-6 px-6 py-6">
                {error && (
                    <div className="rounded-lg bg-red-50 px-4 py-3 text-[13px] text-red-600">{error}</div>
                )}

                {saved && (
                    <div className="flex items-center gap-2 rounded-lg bg-green-50 px-4 py-3 text-[13px] text-green-700">
                        <CheckCircle2 className="h-4 w-4" />
                        Settings saved successfully
                    </div>
                )}

                {testResult && (
                    <div className="space-y-2">
                        <div
                            className={`flex items-center gap-2 rounded-lg px-4 py-3 text-[13px] ${testResult.imap ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-600'
                                }`}
                        >
                            {testResult.imap ? (
                                <CheckCircle2 className="h-4 w-4" />
                            ) : (
                                <XCircle className="h-4 w-4" />
                            )}
                            IMAP: {testResult.imap ? 'Connected successfully' : 'Connection failed'}
                        </div>
                        <div
                            className={`flex items-center gap-2 rounded-lg px-4 py-3 text-[13px] ${testResult.smtp ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-600'
                                }`}
                        >
                            {testResult.smtp ? (
                                <CheckCircle2 className="h-4 w-4" />
                            ) : (
                                <XCircle className="h-4 w-4" />
                            )}
                            SMTP: {testResult.smtp ? 'Connected successfully' : 'Connection failed'}
                        </div>
                    </div>
                )}

                {/* IMAP Settings */}
                <div className="rounded-xl border border-gray-200 bg-white p-6">
                    <div className="mb-5 flex items-center gap-3">
                        <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-50">
                            <Server className="h-4.5 w-4.5 text-blue-600" strokeWidth={1.75} />
                        </div>
                        <div>
                            <h2 className="text-[15px] font-semibold text-gray-900">IMAP Settings</h2>
                            <p className="text-[12px] text-gray-400">For receiving emails</p>
                        </div>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <InputField
                            label="Host"
                            value={imap.host}
                            onChange={(v) => setImap({ ...imap, host: v })}
                            placeholder="imap.gmail.com"
                        />
                        <InputField
                            label="Port"
                            value={imap.port}
                            onChange={(v) => setImap({ ...imap, port: v })}
                            placeholder="993"
                        />
                        <InputField
                            label="Username"
                            value={imap.user}
                            onChange={(v) => setImap({ ...imap, user: v })}
                            placeholder="you@gmail.com"
                        />
                        <InputField
                            label="Password"
                            value={imap.pass}
                            onChange={(v) => setImap({ ...imap, pass: v })}
                            placeholder="App password"
                            type="password"
                        />
                    </div>
                    <div className="mt-4">
                        <label className="flex items-center gap-2 text-[13px] text-gray-700">
                            <input
                                type="checkbox"
                                checked={imap.tls}
                                onChange={(e) => setImap({ ...imap, tls: e.target.checked })}
                                className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                            />
                            Use TLS/SSL
                        </label>
                    </div>
                </div>

                {/* SMTP Settings */}
                <div className="rounded-xl border border-gray-200 bg-white p-6">
                    <div className="mb-5 flex items-center gap-3">
                        <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-50">
                            <Mail className="h-4.5 w-4.5 text-emerald-600" strokeWidth={1.75} />
                        </div>
                        <div>
                            <h2 className="text-[15px] font-semibold text-gray-900">SMTP Settings</h2>
                            <p className="text-[12px] text-gray-400">For sending emails</p>
                        </div>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <InputField
                            label="Host"
                            value={smtp.host}
                            onChange={(v) => setSmtp({ ...smtp, host: v })}
                            placeholder="smtp.gmail.com"
                        />
                        <InputField
                            label="Port"
                            value={smtp.port}
                            onChange={(v) => setSmtp({ ...smtp, port: v })}
                            placeholder="465"
                        />
                        <InputField
                            label="Username"
                            value={smtp.user}
                            onChange={(v) => setSmtp({ ...smtp, user: v })}
                            placeholder="you@gmail.com"
                        />
                        <InputField
                            label="Password"
                            value={smtp.pass}
                            onChange={(v) => setSmtp({ ...smtp, pass: v })}
                            placeholder="App password"
                            type="password"
                        />
                    </div>
                    <div className="mt-4">
                        <label className="flex items-center gap-2 text-[13px] text-gray-700">
                            <input
                                type="checkbox"
                                checked={smtp.tls}
                                onChange={(e) => setSmtp({ ...smtp, tls: e.target.checked })}
                                className="h-4 w-4 rounded border-gray-300 text-emerald-600 focus:ring-emerald-500"
                            />
                            Use TLS/SSL
                        </label>
                    </div>
                </div>

                {/* Email Signature */}
                <div className="rounded-xl border border-gray-200 bg-white p-6">
                    <div className="mb-5 flex items-center gap-3">
                        <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-purple-50">
                            <FileText className="h-4.5 w-4.5 text-purple-600" strokeWidth={1.75} />
                        </div>
                        <div>
                            <h2 className="text-[15px] font-semibold text-gray-900">Email Signature</h2>
                            <p className="text-[12px] text-gray-400">Automatically added to your emails</p>
                        </div>
                    </div>

                    <div>
                        <label className="mb-1.5 block text-[13px] font-medium text-gray-700">
                            Signature
                        </label>
                        <RichTextEditor
                            value={signature}
                            onChange={setSignature}
                            placeholder="Best regards,&#10;Your Name&#10;Your Title&#10;Company Name"
                            minHeight="120px"
                            showAdvancedFormatting={true}
                        />
                        <p className="mt-1.5 text-[12px] text-gray-400">
                            This signature will be automatically added to all new emails and replies. Use the toolbar to format your signature with bold, italic, underline, links, lists, and colors.
                        </p>
                    </div>
                </div>

                {/* Action buttons */}
                <div className="flex items-center gap-3 pb-6">
                    <button
                        onClick={handleTest}
                        disabled={testing || !imap.host || !smtp.host}
                        className="flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-5 py-2.5 text-[13px] font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50"
                    >
                        {testing ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                        ) : (
                            <TestTube className="h-4 w-4" strokeWidth={1.75} />
                        )}
                        Test Connection
                    </button>
                    <button
                        onClick={handleSave}
                        disabled={saving || !imap.host || !smtp.host}
                        className="flex items-center gap-2 rounded-lg bg-gray-900 px-5 py-2.5 text-[13px] font-medium text-white hover:bg-gray-800 disabled:opacity-50"
                    >
                        {saving ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                        ) : (
                            <Save className="h-4 w-4" strokeWidth={1.75} />
                        )}
                        Save Settings
                    </button>
                </div>
            </div>
        </div>
    );
}
