'use client';

import React, { useEffect, useState } from 'react';
import { RichTextEditor } from '@/components/ui/rich-text-editor';
import { Calendar, Clock, MapPin, Users, User, Globe, Briefcase, FileText, Tag } from 'lucide-react';
import { EventTag } from '@/types/tags';
import { TagManager } from './TagManager';

type Mode = 'create' | 'edit';

interface Customer {
    id: string;
    name: string;
    company: string;
}

interface Domain {
    id: string;
    domain: string;
}

interface Project {
    id: string;
    title: string;
}

interface Quote {
    id: string;
    title: string;
}

interface Props {
    mode: Mode;
    eventId?: string;
    defaultCustomerId?: string;
    defaultDomainId?: string;
    defaultProjectId?: string;
    defaultStartDatetime?: string; // New prop for default date
    lockCustomer?: boolean;
    lockDomain?: boolean;
    lockProject?: boolean;
    onSuccess?: () => void;
}

export default function EventForm({
    mode,
    eventId,
    defaultCustomerId,
    defaultDomainId,
    defaultProjectId,
    defaultStartDatetime,
    lockCustomer = false,
    lockDomain = false,
    lockProject = false,
    onSuccess
}: Props) {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // Form fields
    const [title, setTitle] = useState('');
    const [description, setDescription] = useState('');
    const [startDatetime, setStartDatetime] = useState(defaultStartDatetime || '');
    const [endDatetime, setEndDatetime] = useState('');
    const [location, setLocation] = useState('');
    const [customerId, setCustomerId] = useState<string>(defaultCustomerId || '');
    const [domainId, setDomainId] = useState<string>(defaultDomainId || '');
    const [projectId, setProjectId] = useState<string>(defaultProjectId || '');
    const [quoteId, setQuoteId] = useState<string>('');
    const [eventType, setEventType] = useState<'meeting' | 'call' | 'presentation' | 'webinar' | 'deadline' | 'reminder' | 'other'>('meeting');
    const [status, setStatus] = useState<'scheduled' | 'in_progress' | 'completed' | 'cancelled' | 'postponed'>('scheduled');
    const [attendees, setAttendees] = useState<string[]>([]);
    const [reminderMinutes, setReminderMinutes] = useState(15);
    const [selectedTags, setSelectedTags] = useState<EventTag[]>([]);

    // Related data
    const [customers, setCustomers] = useState<Customer[]>([]);
    const [domains, setDomains] = useState<Domain[]>([]);
    const [projects, setProjects] = useState<Project[]>([]);
    const [quotes, setQuotes] = useState<Quote[]>([]);

    // Event type options
    const eventTypeOptions = [
        { value: 'meeting', label: 'פגישה', icon: '🤝' },
        { value: 'call', label: 'שיחה', icon: '📞' },
        { value: 'presentation', label: 'מצגת', icon: '📊' },
        { value: 'webinar', label: 'וובינר', icon: '💻' },
        { value: 'deadline', label: 'דדליין', icon: '⏰' },
        { value: 'reminder', label: 'תזכורת', icon: '🔔' },
        { value: 'other', label: 'אחר', icon: '📌' }
    ];

    // Status options
    const statusOptions = [
        { value: 'scheduled', label: 'מתוכנן', color: 'blue' },
        { value: 'in_progress', label: 'בתהליך', color: 'yellow' },
        { value: 'completed', label: 'הושלם', color: 'green' },
        { value: 'cancelled', label: 'בוטל', color: 'red' },
        { value: 'postponed', label: 'נדחה', color: 'gray' }
    ];

    // Reminder options
    const reminderOptions = [
        { value: 0, label: 'ללא תזכורת' },
        { value: 5, label: '5 דקות לפני' },
        { value: 15, label: '15 דקות לפני' },
        { value: 30, label: '30 דקות לפני' },
        { value: 60, label: 'שעה לפני' },
        { value: 1440, label: 'יום לפני' }
    ];

    // טעינת לקוחות בטעינה ראשונית
    useEffect(() => {
        (async () => {
            try {
                console.log('🔄 Loading customers from /api/comprehensive/customers...');
                const res = await fetch('/api/comprehensive/customers');
                console.log('Response status:', res.status);

                if (res.ok) {
                    const data = await res.json();
                    console.log('✅ Customers loaded:', data.length, 'customers');
                    console.log('First customer:', data[0]);
                    setCustomers(data);
                } else {
                    const errorText = await res.text();
                    console.error('❌ Failed to load customers:', res.status, errorText);
                }
            } catch (e) {
                console.error('❌ Error loading customers:', e);
            }
        })();
    }, []);

    // טעינת דומיינים ופרויקטים כשבוחרים לקוח
    useEffect(() => {
        if (customerId) {
            (async () => {
                try {
                    const [domainsRes, projectsRes, quotesRes] = await Promise.all([
                        fetch(`/api/customers/${customerId}/domains`),
                        fetch(`/api/customers/${customerId}/projects`),
                        fetch(`/api/customers/${customerId}/quotes`)
                    ]);
                    if (domainsRes.ok) {
                        const domainsData = await domainsRes.json();
                        setDomains(domainsData);
                    }
                    if (projectsRes.ok) {
                        const projectsData = await projectsRes.json();
                        setProjects(projectsData);
                    }
                    if (quotesRes.ok) {
                        const quotesData = await quotesRes.json();
                        setQuotes(quotesData);
                    }
                } catch (e) {
                    console.error('Error loading customer data:', e);
                }
            })();
        } else {
            setDomains([]);
            setProjects([]);
            setQuotes([]);
            setDomainId('');
            setProjectId('');
            setQuoteId('');
        }
    }, [customerId]);

    // טעינת אירוע קיים במצב עריכה
    useEffect(() => {
        if (mode === 'edit' && eventId) {
            (async () => {
                setLoading(true);
                try {
                    console.log('🔄 Loading event for edit, ID:', eventId);
                    const url = `/api/events/${eventId}`;
                    console.log('📡 Fetching from:', url);

                    const res = await fetch(url, { cache: 'no-store' });
                    console.log('📡 Response status:', res.status);

                    if (!res.ok) {
                        const errorText = await res.text();
                        console.error('❌ API Error:', res.status, errorText);
                        throw new Error(`API Error: ${res.status} - ${errorText}`);
                    }

                    const event = await res.json();
                    console.log('✅ Event loaded for edit:', event);
                    setTitle(event.title ?? '');
                    setDescription(event.description ?? '');
                    setStartDatetime(event.start_datetime ? new Date(event.start_datetime).toISOString().slice(0, 16) : '');
                    setEndDatetime(event.end_datetime ? new Date(event.end_datetime).toISOString().slice(0, 16) : '');
                    setLocation(event.location ?? '');
                    setCustomerId(event.customer_id ?? '');
                    setDomainId(event.domain_id ?? '');
                    setProjectId(event.project_id ?? '');
                    setQuoteId(event.quote_id ?? '');
                    setEventType(event.event_type ?? 'meeting');
                    setStatus(event.status ?? 'scheduled');
                    setAttendees(event.attendees ? JSON.parse(event.attendees) : []);
                    setReminderMinutes(event.reminder_minutes ?? 15);

                    // טעינת תגיות האירוע מה-JSON
                    try {
                        const tags = event.tags ? JSON.parse(event.tags) : [];
                        setSelectedTags(tags);
                    } catch (e) {
                        console.error('Error loading event tags:', e);
                    }
                } catch (e) {
                    setError('שגיאה בטעינת האירוע');
                } finally {
                    setLoading(false);
                }
            })();
        }
    }, [mode, eventId]);

    const onSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        setLoading(true);
        setError(null);
        try {
            const payload = {
                title,
                description: description || null,
                start_datetime: startDatetime,
                end_datetime: endDatetime || null,
                location: location || null,
                customer_id: customerId || null,
                domain_id: domainId || null,
                project_id: projectId || null,
                quote_id: quoteId || null,
                event_type: eventType,
                status,
                attendees: attendees.length > 0 ? attendees : null,
                reminder_minutes: reminderMinutes,
                tags: selectedTags.length > 0 ? selectedTags : null,
            };

            console.log('📤 Sending payload:', payload);
            console.log('🏷️ Selected tags:', selectedTags);

            const res = await fetch(mode === 'create' ? '/api/events' : `/api/events/${eventId}`, {
                method: mode === 'create' ? 'POST' : 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload),
            });

            if (!res.ok) {
                const errData = await res.json();
                throw new Error(errData.error || 'שמירה נכשלה');
            }

            const event = await res.json();

            if (onSuccess) {
                onSuccess();
            } else {
                window.location.href = '/events';
            }
        } catch (e: any) {
            setError(e.message || 'שמירה נכשלה');
        } finally {
            setLoading(false);
        }
    };

    const addAttendee = () => {
        setAttendees([...attendees, '']);
    };

    const updateAttendee = (index: number, value: string) => {
        const newAttendees = [...attendees];
        newAttendees[index] = value;
        setAttendees(newAttendees);
    };

    const removeAttendee = (index: number) => {
        const newAttendees = attendees.filter((_, i) => i !== index);
        setAttendees(newAttendees);
    };

    return (
        <form onSubmit={onSubmit} className="bg-white shadow rounded-lg p-6 space-y-6" dir="rtl">
            {error && (
                <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
                    {error}
                </div>
            )}

            {/* כותרת ותיאור */}
            <div className="space-y-4">
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">כותרת האירוע *</label>
                    <input
                        className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        value={title}
                        onChange={e => setTitle(e.target.value)}
                        required
                        placeholder="הזן כותרת לאירוע"
                        aria-label="כותרת האירוע"
                    />
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">תיאור</label>
                    <RichTextEditor
                        value={description}
                        onChange={setDescription}
                        placeholder="תאר את האירוע..."
                        className="w-full"
                    />
                </div>
            </div>

            {/* תאריכים וזמנים */}
            <div className="border-t pt-4">
                <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
                    <Calendar className="w-5 h-5" />
                    תאריכים וזמנים
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">תאריך ושעת התחלה *</label>
                        <input
                            type="datetime-local"
                            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            value={startDatetime}
                            onChange={e => setStartDatetime(e.target.value)}
                            required
                            aria-label="תאריך ושעת התחלה"
                        />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">תאריך ושעת סיום</label>
                        <input
                            type="datetime-local"
                            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            value={endDatetime}
                            onChange={e => setEndDatetime(e.target.value)}
                            aria-label="תאריך ושעת סיום"
                        />
                    </div>
                </div>
            </div>

            {/* מיקום */}
            <div className="border-t pt-4">
                <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
                    <MapPin className="w-5 h-5" />
                    מיקום
                </h3>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">מיקום</label>
                    <input
                        className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        value={location}
                        onChange={e => setLocation(e.target.value)}
                        placeholder="הזן מיקום האירוע"
                        aria-label="מיקום האירוע"
                    />
                </div>
            </div>

            {/* קשרים */}
            <div className="border-t pt-4">
                <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
                    <User className="w-5 h-5" />
                    קשרים
                </h3>
                <div className="space-y-4">
                    {/* בחירת לקוח */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            לקוח {lockCustomer && <span className="text-xs text-gray-500">(נעול)</span>}
                        </label>
                        <select
                            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                            value={customerId}
                            onChange={e => setCustomerId(e.target.value)}
                            disabled={lockCustomer}
                            aria-label="בחירת לקוח"
                        >
                            <option value="">-- בחר לקוח --</option>
                            {customers.map(c => (
                                <option key={c.id} value={c.id}>{c.name} ({c.company})</option>
                            ))}
                        </select>
                    </div>

                    {/* בחירת דומיין */}
                    {customerId && (
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                דומיין {lockDomain && <span className="text-xs text-gray-500">(נעול)</span>}
                            </label>
                            <select
                                className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                                value={domainId}
                                onChange={e => setDomainId(e.target.value)}
                                disabled={lockDomain}
                                aria-label="בחירת דומיין"
                            >
                                <option value="">-- ללא דומיין --</option>
                                {domains.map(d => (
                                    <option key={d.id} value={d.id}>{d.domain}</option>
                                ))}
                            </select>
                        </div>
                    )}

                    {/* בחירת פרויקט */}
                    {customerId && (
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                פרויקט {lockProject && <span className="text-xs text-gray-500">(נעול)</span>}
                            </label>
                            <select
                                className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
                                value={projectId}
                                onChange={e => setProjectId(e.target.value)}
                                disabled={lockProject}
                                aria-label="בחירת פרויקט"
                            >
                                <option value="">-- ללא פרויקט --</option>
                                {projects.map(p => (
                                    <option key={p.id} value={p.id}>{p.title}</option>
                                ))}
                            </select>
                        </div>
                    )}

                    {/* בחירת הצעת מחיר */}
                    {customerId && (
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">הצעת מחיר</label>
                            <select
                                className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                value={quoteId}
                                onChange={e => setQuoteId(e.target.value)}
                                aria-label="בחירת הצעת מחיר"
                            >
                                <option value="">-- ללא הצעת מחיר --</option>
                                {quotes.map(q => (
                                    <option key={q.id} value={q.id}>{q.title}</option>
                                ))}
                            </select>
                        </div>
                    )}
                </div>
            </div>

            {/* פרטי אירוע */}
            <div className="border-t pt-4">
                <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
                    <Clock className="w-5 h-5" />
                    פרטי אירוע
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">סוג אירוע</label>
                        <select
                            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            value={eventType}
                            onChange={e => setEventType(e.target.value as any)}
                            aria-label="בחירת סוג אירוע"
                        >
                            {eventTypeOptions.map(option => (
                                <option key={option.value} value={option.value}>
                                    {option.icon} {option.label}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">סטטוס</label>
                        <select
                            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            value={status}
                            onChange={e => setStatus(e.target.value as any)}
                            aria-label="בחירת סטטוס"
                        >
                            {statusOptions.map(option => (
                                <option key={option.value} value={option.value}>
                                    {option.label}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">תזכורת</label>
                        <select
                            className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            value={reminderMinutes}
                            onChange={e => setReminderMinutes(Number(e.target.value))}
                            aria-label="בחירת תזכורת"
                        >
                            {reminderOptions.map(option => (
                                <option key={option.value} value={option.value}>
                                    {option.label}
                                </option>
                            ))}
                        </select>
                    </div>
                </div>
            </div>

            {/* תגיות */}
            <div className="border-t pt-4 bg-yellow-50 p-4">
                <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
                    <Tag className="w-5 h-5" />
                    תגיות
                </h3>
                <p className="text-sm text-gray-600 mb-2">selectedTags: {selectedTags.length}</p>
                <TagManager
                    selectedTags={selectedTags}
                    onTagsChange={setSelectedTags}
                />
            </div>

            {/* משתתפים */}
            <div className="border-t pt-4">
                <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center gap-2">
                    <Users className="w-5 h-5" />
                    משתתפים
                </h3>
                <div className="space-y-2">
                    {attendees.map((attendee, index) => (
                        <div key={index} className="flex gap-2">
                            <input
                                type="text"
                                className="flex-1 border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                value={attendee}
                                onChange={e => updateAttendee(index, e.target.value)}
                                placeholder="שם משתתף"
                                aria-label={`משתתף ${index + 1}`}
                            />
                            <button
                                type="button"
                                onClick={() => removeAttendee(index)}
                                className="px-3 py-2 text-red-600 hover:text-red-800"
                            >
                                מחק
                            </button>
                        </div>
                    ))}
                    <button
                        type="button"
                        onClick={addAttendee}
                        className="px-4 py-2 text-blue-600 hover:text-blue-800 border border-blue-300 rounded-md"
                    >
                        + הוסף משתתף
                    </button>
                </div>
            </div>

            {/* כפתורים */}
            <div className="flex justify-start gap-3 border-t pt-4">
                <button
                    type="submit"
                    disabled={loading}
                    className="bg-blue-600 text-white px-6 py-2 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                    {loading ? 'שומר...' : (mode === 'create' ? 'צור אירוע' : 'שמור שינויים')}
                </button>
                <a
                    href="/events"
                    className="px-6 py-2 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
                >
                    ביטול
                </a>
            </div>
        </form>
    );
}
