'use client';

import React, { useState } from 'react';
import { Calendar, Plus } from 'lucide-react';

interface Task {
    id: number;
    title: string;
    description?: string;
    customer_id: string;
    domain_id?: string;
    project_id?: string;
    due_date?: string;
}

interface Props {
    task: Task;
    onSuccess?: () => void;
}

export default function CreateEventFromTask({ task, onSuccess }: Props) {
    const [showForm, setShowForm] = useState(false);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const handleCreateEvent = async (eventData: any) => {
        setLoading(true);
        setError(null);
        try {
            // Create event
            const eventResponse = await fetch('/api/events', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(eventData)
            });

            if (!eventResponse.ok) {
                const errorData = await eventResponse.json();
                throw new Error(errorData.error || 'שגיאה ביצירת אירוע');
            }

            const event = await eventResponse.json();

            // Link task to event
            const linkResponse = await fetch(`/api/tasks/${task.id}/link-event`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ event_id: event.id })
            });

            if (!linkResponse.ok) {
                const errorData = await linkResponse.json();
                throw new Error(errorData.error || 'שגיאה בקישור לאירוע');
            }

            setShowForm(false);
            if (onSuccess) onSuccess();
        } catch (err: any) {
            setError(err.message || 'שגיאה ביצירת אירוע');
        } finally {
            setLoading(false);
        }
    };

    const getDefaultEventData = () => {
        const dueDate = task.due_date ? new Date(task.due_date) : new Date();
        const startTime = new Date(dueDate);
        startTime.setHours(10, 0, 0, 0); // 10:00 AM
        const endTime = new Date(startTime);
        endTime.setHours(11, 0, 0, 0); // 11:00 AM

        return {
            title: task.title,
            description: task.description || `אירוע עבור משימה: ${task.title}`,
            start_datetime: startTime.toISOString().slice(0, 16),
            end_datetime: endTime.toISOString().slice(0, 16),
            customer_id: task.customer_id,
            domain_id: task.domain_id || null,
            project_id: task.project_id || null,
            event_type: 'meeting',
            status: 'scheduled'
        };
    };

    if (showForm) {
        return (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                <div className="bg-white rounded-lg p-6 w-full max-w-md mx-4">
                    <h3 className="text-lg font-medium text-gray-900 mb-4">
                        צור אירוע עבור משימה
                    </h3>

                    {error && (
                        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded mb-4">
                            {error}
                        </div>
                    )}

                    <form onSubmit={(e) => {
                        e.preventDefault();
                        const formData = new FormData(e.currentTarget);
                        const eventData = {
                            title: formData.get('title') as string,
                            description: formData.get('description') as string,
                            start_datetime: formData.get('start_datetime') as string,
                            end_datetime: formData.get('end_datetime') as string,
                            customer_id: task.customer_id,
                            domain_id: task.domain_id || null,
                            project_id: task.project_id || null,
                            event_type: 'meeting',
                            status: 'scheduled'
                        };
                        handleCreateEvent(eventData);
                    }}>
                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    כותרת האירוע *
                                </label>
                                <input
                                    type="text"
                                    name="title"
                                    defaultValue={task.title}
                                    className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                    required
                                    dir="rtl"
                                    aria-label="כותרת האירוע"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    תיאור
                                </label>
                                <textarea
                                    name="description"
                                    defaultValue={task.description || `אירוע עבור משימה: ${task.title}`}
                                    className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                    rows={3}
                                    dir="rtl"
                                    aria-label="תיאור האירוע"
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">
                                        תאריך ושעת התחלה *
                                    </label>
                                    <input
                                        type="datetime-local"
                                        name="start_datetime"
                                        defaultValue={getDefaultEventData().start_datetime}
                                        className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                        required
                                        aria-label="תאריך ושעת התחלה"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">
                                        תאריך ושעת סיום
                                    </label>
                                    <input
                                        type="datetime-local"
                                        name="end_datetime"
                                        defaultValue={getDefaultEventData().end_datetime}
                                        className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                        aria-label="תאריך ושעת סיום"
                                    />
                                </div>
                            </div>
                        </div>

                        <div className="flex justify-end gap-3 mt-6">
                            <button
                                type="button"
                                onClick={() => setShowForm(false)}
                                className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
                            >
                                ביטול
                            </button>
                            <button
                                type="submit"
                                disabled={loading}
                                className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                            >
                                {loading ? 'יוצר...' : 'צור אירוע'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        );
    }

    return (
        <button
            onClick={() => setShowForm(true)}
            className="flex items-center gap-2 px-3 py-1 text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded-md transition-colors"
            title="צור אירוע עבור משימה זו"
        >
            <Calendar className="w-4 h-4" />
            <span>קבע פגישה</span>
        </button>
    );
}
