'use client';

import { useState, useEffect, useMemo } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/src/components/layout/AppLayout';
import {
    Save,
    ArrowRight,
    Eye,
    EyeOff,
    FileText,
    Code,
    Palette,
    Sparkles
} from 'lucide-react';
import { toast } from 'react-hot-toast';
import RichTextEditor from '@/components/emails/RichTextEditor';

interface EmailTemplate {
    id: string;
    name: string;
    subject: string;
    body: string;
    variables: string[];
    isActive: boolean;
    createdAt: Date;
    updatedAt: Date;
}

export default function EditTemplatePage() {
    const params = useParams();
    const router = useRouter();
    const templateId = params.id as string;

    const [template, setTemplate] = useState<EmailTemplate | null>(null);
    const [name, setName] = useState('');
    const [subject, setSubject] = useState('');
    const [body, setBody] = useState('');
    const [isActive, setIsActive] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [showPreview, setShowPreview] = useState(false);

    // Available variables for templates
    const availableVariables = [
        { key: 'customerName', label: 'שם הלקוח', example: 'ישראל ישראלי' },
        { key: 'domain', label: 'דומיין', example: 'example.com' },
        { key: 'amount', label: 'סכום לתשלום', example: '₪150' },
        { key: 'daysOverdue', label: 'ימי איחור', example: '5' },
        { key: 'packageName', label: 'שם החבילה', example: 'חבילת בסיס' },
        { key: 'paymentLink', label: 'קישור לתשלום', example: 'https://payment.com' },
        { key: 'supportEmail', label: 'אימייל תמיכה', example: 'support@company.com' },
        { key: 'companyName', label: 'שם החברה', example: 'TSM Company' },
    ];

    useEffect(() => {
        fetchTemplate();
    }, [templateId]);

    const fetchTemplate = async () => {
        try {
            // TODO: Replace with actual API call
            const mockTemplate: EmailTemplate = {
                id: templateId,
                name: 'תזכורת תשלום סטנדרטית',
                subject: 'תזכורת תשלום עבור הדומיין {domain}',
                body: `
<div dir="rtl" style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
    <h2 style="color: #1f2937;">שלום {customerName},</h2>
    <p>זוהי תזכורת ידידותית שהתשלום עבור הדומיין <strong>{domain}</strong> באיחור של <strong>{daysOverdue} ימים</strong>.</p>
    <div style="background-color: #fef3c7; border-right: 4px solid #f59e0b; padding: 15px; margin: 20px 0;">
        <h3 style="color: #92400e;">פרטי התשלום:</h3>
        <ul style="color: #92400e;">
            <li>סכום לתשלום: <strong>₪{amount}</strong></li>
            <li>דומיין: <strong>{domain}</strong></li>
            <li>חבילה: <strong>{packageName}</strong></li>
        </ul>
    </div>
    <p>בברכה,<br/>{companyName}</p>
</div>
                `.trim(),
                variables: ['customerName', 'domain', 'amount', 'daysOverdue', 'packageName', 'companyName'],
                isActive: true,
                createdAt: new Date('2025-01-15'),
                updatedAt: new Date('2025-01-15')
            };

            setTemplate(mockTemplate);
            setName(mockTemplate.name);
            setSubject(mockTemplate.subject);
            setBody(mockTemplate.body);
            setIsActive(mockTemplate.isActive);
        } catch (error) {
            console.error('Error fetching template:', error);
            toast.error('שגיאה בטעינת התבנית');
        }
    };

    const handleSave = async () => {
        setIsSaving(true);
        try {
            // TODO: API call to save template
            await new Promise(resolve => setTimeout(resolve, 1000));

            toast.success('התבנית נשמרה בהצלחה!');
            router.push('/emails/templates');
        } catch (error) {
            console.error('Error saving template:', error);
            toast.error('שגיאה בשמירת התבנית');
        } finally {
            setIsSaving(false);
        }
    };

    const insertVariable = (variableKey: string) => {
        const variable = `{${variableKey}}`;
        // Insert at cursor position in subject or body
        // For now, just append to subject
        setSubject(prev => prev + variable);
    };

    const previewBody = useMemo(() => {
        let preview = body;
        availableVariables.forEach(({ key, example }) => {
            const regex = new RegExp(`\\{${key}\\}`, 'g');
            preview = preview.replace(regex, example);
        });
        return preview;
    }, [body]);


    if (!template) {
        return (
            <AppLayout>
                <div className="flex items-center justify-center h-64">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
                </div>
            </AppLayout>
        );
    }

    return (
        <AppLayout>
            <div className="max-w-7xl mx-auto">
                {/* Header */}
                <div className="mb-8">
                    <div className="flex items-center gap-4 mb-4">
                        <Button
                            variant="outline"
                            onClick={() => router.push('/emails/templates')}
                        >
                            <ArrowRight className="w-4 h-4 ml-2" />
                            חזרה לתבניות
                        </Button>
                        <div className="flex-1">
                            <h1 className="text-3xl font-bold text-gray-900">עריכת תבנית</h1>
                            <p className="text-gray-600">ערוך את תבנית האימייל שלך</p>
                        </div>
                        <Button
                            onClick={handleSave}
                            disabled={isSaving}
                            className="bg-green-600 hover:bg-green-700 text-white"
                        >
                            {isSaving ? (
                                <>
                                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white ml-2" />
                                    שומר...
                                </>
                            ) : (
                                <>
                                    <Save className="w-4 h-4 ml-2" />
                                    שמור שינויים
                                </>
                            )}
                        </Button>
                    </div>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    {/* Main Editor */}
                    <div className="lg:col-span-2 space-y-6">
                        {/* Template Info */}
                        <Card className="p-6">
                            <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                                <FileText className="w-5 h-5 text-blue-600" />
                                פרטי התבנית
                            </h3>

                            <div className="space-y-4">
                                <div>
                                    <Label htmlFor="name">שם התבנית</Label>
                                    <Input
                                        id="name"
                                        value={name}
                                        onChange={(e) => setName(e.target.value)}
                                        placeholder="לדוגמה: תזכורת תשלום סטנדרטית"
                                    />
                                </div>

                                <div>
                                    <Label htmlFor="subject">נושא האימייל</Label>
                                    <Input
                                        id="subject"
                                        value={subject}
                                        onChange={(e) => setSubject(e.target.value)}
                                        placeholder="לדוגמה: תזכורת תשלום עבור {domain}"
                                    />
                                    <p className="text-xs text-gray-500 mt-1">
                                        השתמש במשתנים כמו {'{domain}'} או {'{customerName}'}
                                    </p>
                                </div>

                                <div className="flex items-center justify-between">
                                    <Label htmlFor="active">סטטוס התבנית</Label>
                                    <button
                                        onClick={() => setIsActive(!isActive)}
                                        className={`px-3 py-1 text-sm rounded-full ${isActive
                                            ? 'bg-green-100 text-green-800'
                                            : 'bg-gray-100 text-gray-800'
                                            }`}
                                    >
                                        {isActive ? 'פעיל' : 'לא פעיל'}
                                    </button>
                                </div>
                            </div>
                        </Card>

                        {/* Body Editor */}
                        <Card className="p-6">
                            <div className="flex items-center justify-between mb-4">
                                <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                                    <Palette className="w-5 h-5 text-blue-600" />
                                    תוכן האימייל
                                </h3>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => setShowPreview(!showPreview)}
                                >
                                    {showPreview ? (
                                        <>
                                            <Code className="w-4 h-4 ml-2" />
                                            עריכה
                                        </>
                                    ) : (
                                        <>
                                            <Eye className="w-4 h-4 ml-2" />
                                            תצוגה מקדימה
                                        </>
                                    )}
                                </Button>
                            </div>

                            {showPreview ? (
                                <div
                                    className="min-h-[400px] border border-gray-200 rounded-lg p-6 bg-white"
                                    dangerouslySetInnerHTML={{ __html: previewBody }}
                                />
                            ) : (
                                <RichTextEditor
                                    value={body}
                                    onChange={setBody}
                                    placeholder="כתוב את תוכן האימייל כאן..."
                                />
                            )}
                        </Card>
                    </div>

                    {/* Variables Sidebar */}
                    <div className="lg:col-span-1">
                        <Card className="p-6 sticky top-6">
                            <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                                <Sparkles className="w-5 h-5 text-purple-600" />
                                משתנים זמינים
                            </h3>

                            <p className="text-sm text-gray-600 mb-4">
                                לחץ על משתנה כדי להוסיף אותו לנושא
                            </p>

                            <div className="space-y-2">
                                {availableVariables.map((variable) => (
                                    <button
                                        key={variable.key}
                                        onClick={() => insertVariable(variable.key)}
                                        className="w-full text-right p-3 bg-purple-50 hover:bg-purple-100 rounded-lg transition-colors group"
                                    >
                                        <div className="flex items-center justify-between mb-1">
                                            <span className="text-sm font-medium text-purple-900">
                                                {variable.label}
                                            </span>
                                            <Code className="w-4 h-4 text-purple-600 opacity-0 group-hover:opacity-100 transition-opacity" />
                                        </div>
                                        <div className="flex items-center gap-2 text-xs">
                                            <code className="bg-purple-200 text-purple-800 px-2 py-0.5 rounded">
                                                {'{' + variable.key + '}'}
                                            </code>
                                            <span className="text-gray-500">→</span>
                                            <span className="text-gray-700">{variable.example}</span>
                                        </div>
                                    </button>
                                ))}
                            </div>

                            <div className="mt-6 p-4 bg-blue-50 rounded-lg">
                                <h4 className="text-sm font-semibold text-blue-900 mb-2">
                                    💡 טיפ
                                </h4>
                                <p className="text-xs text-blue-700">
                                    המשתנים יוחלפו אוטומטית בנתונים האמיתיים בעת שליחת האימייל. וודא שאתה כותב אותם בדיוק כמו שמופיע.
                                </p>
                            </div>
                        </Card>
                    </div>
                </div>
            </div>
        </AppLayout>
    );
}

