'use client';

import { useState, useEffect } from 'react';
import { Reminder, CreateReminderData, UpdateReminderData, REMINDER_TYPES } from '@/types/reminder';

interface ReminderFormProps {
    reminder?: Reminder | null;
    packageName: string;
    onSubmit: (data: CreateReminderData | UpdateReminderData) => Promise<void>;
    onCancel: () => void;
    isLoading: boolean;
}

export default function ReminderForm({ reminder, packageName, onSubmit, onCancel, isLoading }: ReminderFormProps) {
    const [formData, setFormData] = useState<CreateReminderData | UpdateReminderData>({
        title: '',
        description: '',
        time: '',
        repeatable: false,
        repeat_days: null,
        type: 'reminder',
    });

    useEffect(() => {
        if (reminder) {
            // Format datetime for input field (remove milliseconds and timezone)
            // Convert from "2025-12-13T15:30:00.000" to "2025-12-13T15:30" for input
            const formattedTime = reminder.time ? reminder.time.replace(/\.\d+/, '').slice(0, 16) : '';
            
            setFormData({
                title: reminder.title || '',
                description: reminder.description || '',
                time: formattedTime,
                repeatable: reminder.repeatable || false,
                repeat_days: reminder.repeat_days,
                type: reminder.type || 'reminder',
            });
        } else {
            // Set default time to current date + 1 hour
            const defaultTime = new Date();
            defaultTime.setHours(defaultTime.getHours() + 1);
            
            // Format as YYYY-MM-DDTHH:MM for datetime-local input
            const year = defaultTime.getFullYear();
            const month = String(defaultTime.getMonth() + 1).padStart(2, '0');
            const day = String(defaultTime.getDate()).padStart(2, '0');
            const hours = String(defaultTime.getHours()).padStart(2, '0');
            const minutes = String(defaultTime.getMinutes()).padStart(2, '0');
            
            const formattedDefaultTime = `${year}-${month}-${day}T${hours}:${minutes}`;
            
            setFormData({
                title: '',
                description: '',
                time: formattedDefaultTime,
                repeatable: false,
                repeat_days: null,
                type: 'reminder',
            });
        }
    }, [reminder]);

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
        const { name, value, type } = e.target;
        
        if (type === 'checkbox') {
            const checked = (e.target as HTMLInputElement).checked;
            setFormData(prev => ({
                ...prev,
                [name]: checked,
            }));
        } else {
            setFormData(prev => ({
                ...prev,
                [name]: value,
            }));
        }
    };

    const handleNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value ? parseInt(value, 10) : null,
        }));
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        
        // Format the time properly for API: "2025-12-13 20:00:00.000"
        let formattedTime = '';
        
        if (formData.time) {
            // Input comes as "2025-12-13T20:00" from datetime-local
            // Replace 'T' with space and add milliseconds
            formattedTime = formData.time.replace('T', ' ') + ':00.000';
        }
        
        const submitData = {
            ...formData,
            time: formattedTime,
        };
        
        await onSubmit(submitData);
    };

    return (
        <form onSubmit={handleSubmit} className="space-y-6 bg-white dark:bg-gray-900 p-6 rounded-lg shadow transition-colors">
            <div>
                <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">
                    {reminder ? 'ویرایش یادآوری' : 'ایجاد یادآوری جدید'} برای پکیج {packageName}
                </h3>
            </div>

            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                {/* Title */}
                <div className="md:col-span-2">
                    <label htmlFor="title" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        عنوان <span className="text-red-500">*</span>
                    </label>
                    <input
                        type="text"
                        id="title"
                        name="title"
                        required
                        value={formData.title || ''}
                        onChange={handleInputChange}
                        className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                        placeholder="مثال: یادآوری روزانه"
                    />
                </div>

                {/* Type */}
                <div>
                    <label htmlFor="type" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        نوع <span className="text-red-500">*</span>
                    </label>
                    <select
                        id="type"
                        name="type"
                        required
                        value={formData.type || 'reminder'}
                        onChange={handleInputChange}
                        className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                    >
                        {Object.entries(REMINDER_TYPES).map(([value, label]) => (
                            <option key={value} value={value}>
                                {label}
                            </option>
                        ))}
                    </select>
                </div>

                {/* Time */}
                <div>
                    <label htmlFor="time" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        زمان <span className="text-red-500">*</span>
                    </label>
                    <input
                        type="datetime-local"
                        id="time"
                        name="time"
                        required
                        value={formData.time || ''}
                        onChange={handleInputChange}
                        className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                    />
                </div>

                {/* Repeatable */}
                <div>
                    <div className="flex items-center h-full pt-6">
                        <input
                            type="checkbox"
                            id="repeatable"
                            name="repeatable"
                            checked={formData.repeatable || false}
                            onChange={handleInputChange}
                            className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 dark:border-gray-600 dark:bg-gray-800 rounded"
                        />
                        <label htmlFor="repeatable" className="mr-2 block text-sm text-gray-900 dark:text-gray-100">
                            قابل تکرار
                        </label>
                    </div>
                </div>

                {/* Repeat Days */}
                {formData.repeatable && (
                    <div>
                        <label htmlFor="repeat_days" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            فاصله تکرار (روز)
                        </label>
                        <input
                            type="number"
                            id="repeat_days"
                            name="repeat_days"
                            min="1"
                            value={formData.repeat_days || ''}
                            onChange={handleNumberChange}
                            className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                            placeholder="مثال: 7"
                        />
                    </div>
                )}
            </div>

            {/* Description */}
            <div>
                <label htmlFor="description" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    توضیحات
                </label>
                <textarea
                    id="description"
                    name="description"
                    rows={3}
                    value={formData.description || ''}
                    onChange={handleInputChange}
                    className="block w-full px-3 py-2 text-slate-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:placeholder-gray-500 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm transition-colors"
                    placeholder="توضیحات یادآوری را وارد کنید..."
                />
            </div>

            {/* Form Actions */}
            <div className="flex justify-end space-x-3 space-x-reverse pt-4 border-t dark:border-gray-800">
                <button
                    type="button"
                    onClick={onCancel}
                    className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 transition-colors"
                >
                    انصراف
                </button>
                <button
                    type="submit"
                    disabled={isLoading}
                    className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-gray-900 focus:ring-indigo-500 disabled:opacity-50 transition-colors"
                >
                    {isLoading ? 'در حال ذخیره...' : reminder ? 'به‌روزرسانی' : 'ایجاد'}
                </button>
            </div>
        </form>
    );
}