'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) {
            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 {
            const defaultTime = new Date();
            defaultTime.setHours(defaultTime.getHours() + 1);
            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');
            setFormData({
                title: '',
                description: '',
                time: `${year}-${month}-${day}T${hours}:${minutes}`,
                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();
        let formattedTime = '';
        if (formData.time) {
            formattedTime = formData.time.replace('T', ' ') + ':00.000';
        }
        await onSubmit({ ...formData, time: formattedTime });
    };

    const inputClass = 'block w-full px-4 py-2.5 text-sm text-gray-900 dark:text-gray-100 border border-gray-200 dark:border-gray-700 rounded-xl bg-gray-50 dark:bg-gray-800/60 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 dark:focus:border-indigo-400 transition-colors';
    const labelClass = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';

    return (
        <form onSubmit={handleSubmit} className="space-y-6 bg-white dark:bg-gray-900 p-6 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-800 shadow-sm">
            <div className="pb-4 border-b border-gray-100 dark:border-gray-800">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                    {reminder ? 'ویرایش یادآوری' : 'ایجاد یادآوری جدید'} برای پکیج {packageName}
                </h3>
            </div>

            <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
                <div className="md:col-span-2">
                    <label htmlFor="title" className={labelClass}>عنوان <span className="text-red-500">*</span></label>
                    <input type="text" id="title" name="title" required value={formData.title || ''} onChange={handleInputChange} className={inputClass} placeholder="مثال: یادآوری روزانه" />
                </div>
                <div>
                    <label htmlFor="type" className={labelClass}>نوع <span className="text-red-500">*</span></label>
                    <select id="type" name="type" required value={formData.type || 'reminder'} onChange={handleInputChange} className={inputClass}>
                        {Object.entries(REMINDER_TYPES).map(([value, label]) => (
                            <option key={value} value={value}>{label}</option>
                        ))}
                    </select>
                </div>
                <div>
                    <label htmlFor="time" className={labelClass}>زمان <span className="text-red-500">*</span></label>
                    <input type="datetime-local" id="time" name="time" required value={formData.time || ''} onChange={handleInputChange} className={inputClass} />
                </div>
                <div>
                    <label className={`${labelClass} invisible`}>تکرار</label>
                    <label className="flex items-center gap-3 p-3 rounded-xl bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors cursor-pointer">
                        <input type="checkbox" id="repeatable" name="repeatable" checked={formData.repeatable || false} onChange={handleInputChange} className="h-4 w-4 text-indigo-600 border-gray-300 dark:border-gray-600 dark:bg-gray-800 rounded-lg focus:ring-indigo-500" />
                        <span className="text-sm font-medium text-gray-700 dark:text-gray-300">قابل تکرار</span>
                    </label>
                </div>
                {formData.repeatable && (
                    <div>
                        <label htmlFor="repeat_days" className={labelClass}>فاصله تکرار (روز)</label>
                        <input type="number" id="repeat_days" name="repeat_days" min="1" value={formData.repeat_days || ''} onChange={handleNumberChange} className={inputClass} placeholder="مثال: 7" />
                    </div>
                )}
            </div>

            <div className="pt-2 border-t border-gray-100 dark:border-gray-800">
                <label htmlFor="description" className={labelClass}>توضیحات</label>
                <textarea id="description" name="description" rows={3} value={formData.description || ''} onChange={handleInputChange} className={inputClass} placeholder="توضیحات یادآوری را وارد کنید..." />
            </div>

            <div className="flex justify-end gap-3 pt-4 border-t border-gray-100 dark:border-gray-800">
                <button type="button" onClick={onCancel} className="px-5 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 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 transition-colors">
                    انصراف
                </button>
                <button type="submit" disabled={isLoading} className="px-5 py-2.5 rounded-xl bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500/30 disabled:opacity-50 transition-colors shadow-sm shadow-indigo-500/20">
                    {isLoading ? 'در حال ذخیره...' : reminder ? 'به‌روزرسانی' : 'ایجاد'}
                </button>
            </div>
        </form>
    );
}
