'use client';

import { useState, useEffect } from 'react';
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 {
    FileText,
    Plus,
    Edit,
    Trash2,
    Eye,
    Copy,
    Search
} from 'lucide-react';
import Link from 'next/link';

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

export default function EmailTemplatesPage() {
    const [templates, setTemplates] = useState<EmailTemplate[]>([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        fetchTemplates();
    }, []);

    const fetchTemplates = async () => {
        setIsLoading(true);
        try {
            // TODO: Replace with actual API call
            const mockTemplates: EmailTemplate[] = [
                {
                    id: '1',
                    name: 'תזכורת תשלום סטנדרטית',
                    subject: 'תזכורת תשלום עבור הדומיין {domain}',
                    body: 'שלום {customerName}...',
                    variables: ['customerName', 'domain', 'amount', 'daysOverdue'],
                    isActive: true,
                    createdAt: new Date('2025-01-15'),
                    updatedAt: new Date('2025-01-15')
                },
                {
                    id: '2',
                    name: 'הודעת איחור תשלום',
                    subject: 'איחור בתשלום - {domain}',
                    body: 'שלום {customerName}...',
                    variables: ['customerName', 'domain', 'amount', 'daysOverdue'],
                    isActive: true,
                    createdAt: new Date('2025-01-14'),
                    updatedAt: new Date('2025-01-14')
                },
                {
                    id: '3',
                    name: 'תודה על התשלום',
                    subject: 'תודה על התשלום - {domain}',
                    body: 'שלום {customerName}...',
                    variables: ['customerName', 'domain', 'amount'],
                    isActive: false,
                    createdAt: new Date('2025-01-13'),
                    updatedAt: new Date('2025-01-13')
                }
            ];
            setTemplates(mockTemplates);
        } catch (error) {
            console.error('Error fetching templates:', error);
        } finally {
            setIsLoading(false);
        }
    };

    const filteredTemplates = templates.filter(template =>
        template.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        template.subject.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const handleDelete = async (id: string) => {
        if (!confirm('האם אתה בטוח שברצונך למחוק תבנית זו?')) return;

        try {
            // TODO: API call to delete template
            setTemplates(templates.filter(t => t.id !== id));
        } catch (error) {
            console.error('Error deleting template:', error);
        }
    };

    const handleDuplicate = async (template: EmailTemplate) => {
        try {
            const newTemplate = {
                ...template,
                id: Date.now().toString(),
                name: `${template.name} (עותק)`,
                createdAt: new Date(),
                updatedAt: new Date()
            };
            setTemplates([newTemplate, ...templates]);
        } catch (error) {
            console.error('Error duplicating template:', error);
        }
    };

    const toggleActive = async (id: string) => {
        try {
            setTemplates(templates.map(t =>
                t.id === id ? { ...t, isActive: !t.isActive } : t
            ));
        } catch (error) {
            console.error('Error toggling template status:', error);
        }
    };

    return (
        <AppLayout>
            <div className="max-w-7xl mx-auto">
                {/* Header */}
                <div className="mb-8">
                    <div className="flex justify-between items-center mb-4">
                        <div>
                            <h1 className="text-3xl font-bold text-gray-900 mb-2">ניהול תבניות אימייל</h1>
                            <p className="text-gray-600">צור, ערוך ונהל תבניות אימייל לשליחה ללקוחות</p>
                        </div>
                        <Link href="/emails/templates/new">
                            <Button className="bg-blue-600 hover:bg-blue-700 text-white">
                                <Plus className="w-4 h-4 ml-2" />
                                תבנית חדשה
                            </Button>
                        </Link>
                    </div>

                    {/* Search */}
                    <div className="relative">
                        <Search className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <Input
                            type="text"
                            placeholder="חפש תבניות..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="pr-10 text-right"
                        />
                    </div>
                </div>

                {/* Templates Grid */}
                {isLoading ? (
                    <div className="flex justify-center items-center h-64">
                        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
                    </div>
                ) : filteredTemplates.length === 0 ? (
                    <Card className="p-12 text-center">
                        <FileText className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                        <h3 className="text-xl font-semibold text-gray-900 mb-2">אין תבניות</h3>
                        <p className="text-gray-600 mb-4">
                            {searchTerm ? 'לא נמצאו תבניות התואמות את החיפוש' : 'התחל ביצירת תבנית אימייל ראשונה'}
                        </p>
                        {!searchTerm && (
                            <Link href="/emails/templates/new">
                                <Button className="bg-blue-600 hover:bg-blue-700 text-white">
                                    <Plus className="w-4 h-4 ml-2" />
                                    צור תבנית חדשה
                                </Button>
                            </Link>
                        )}
                    </Card>
                ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        {filteredTemplates.map((template) => (
                            <Card key={template.id} className="p-6 hover:shadow-lg transition-shadow">
                                {/* Template Header */}
                                <div className="flex justify-between items-start mb-4">
                                    <div className="flex items-center gap-2">
                                        <FileText className="w-5 h-5 text-blue-600" />
                                        <h3 className="text-lg font-semibold text-gray-900">{template.name}</h3>
                                    </div>
                                    <button
                                        onClick={() => toggleActive(template.id)}
                                        className={`px-2 py-1 text-xs rounded-full ${template.isActive
                                            ? 'bg-green-100 text-green-800'
                                            : 'bg-gray-100 text-gray-800'
                                            }`}
                                    >
                                        {template.isActive ? 'פעיל' : 'לא פעיל'}
                                    </button>
                                </div>

                                {/* Template Subject */}
                                <div className="mb-4">
                                    <p className="text-sm text-gray-600 mb-1">נושא:</p>
                                    <p className="text-sm text-gray-900 line-clamp-2">{template.subject}</p>
                                </div>

                                {/* Variables */}
                                <div className="mb-4">
                                    <p className="text-sm text-gray-600 mb-2">משתנים:</p>
                                    <div className="flex flex-wrap gap-1">
                                        {template.variables.slice(0, 3).map((variable) => (
                                            <span
                                                key={variable}
                                                className="px-2 py-1 bg-blue-50 text-blue-700 text-xs rounded"
                                            >
                                                {'{' + variable + '}'}
                                            </span>
                                        ))}
                                        {template.variables.length > 3 && (
                                            <span className="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded">
                                                +{template.variables.length - 3}
                                            </span>
                                        )}
                                    </div>
                                </div>

                                {/* Last Updated */}
                                <div className="mb-4 text-xs text-gray-500">
                                    עודכן: {new Date(template.updatedAt).toLocaleDateString('he-IL')}
                                </div>

                                {/* Actions */}
                                <div className="flex gap-2">
                                    <Link href={`/emails/templates/${template.id}`} className="flex-1">
                                        <Button variant="outline" className="w-full" size="sm">
                                            <Edit className="w-4 h-4 ml-1" />
                                            ערוך
                                        </Button>
                                    </Link>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => handleDuplicate(template)}
                                        title="שכפל תבנית"
                                    >
                                        <Copy className="w-4 h-4" />
                                    </Button>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() => handleDelete(template.id)}
                                        className="text-red-600 hover:text-red-700 hover:bg-red-50"
                                        title="מחק תבנית"
                                    >
                                        <Trash2 className="w-4 h-4" />
                                    </Button>
                                </div>
                            </Card>
                        ))}
                    </div>
                )}
            </div>
        </AppLayout>
    );
}

