'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { phoneSchema, PhoneFormData } from '@/utils/validation';
import { usePhoneStore } from '@/store/sqliteStore';
import { useUIStore } from '@/store/uiStore';
import { Plus, X } from 'lucide-react';

interface AddPhoneFormProps {
    onSuccess?: () => void;
}

export default function AddPhoneForm({ onSuccess }: AddPhoneFormProps) {
    const { addPhone } = usePhoneStore();
    const { closeAddPhoneModal, addNotification } = useUIStore();

    const {
        register,
        handleSubmit,
        formState: { errors, isSubmitting },
        reset,
    } = useForm<PhoneFormData>({
        resolver: zodResolver(phoneSchema),
        defaultValues: {
            phone: '',
            domain: '',
            website: 'https://',
            owner: '',
            email: '',
            package: 'Linux Mini Professionals',
            amount: 0,
            status: 'pending',
            priority: 'medium',
            startDate: new Date().toISOString().split('T')[0],
            nextPayment: new Date().toISOString().split('T')[0],
        },
    });

    const onSubmit = async (data: PhoneFormData) => {
        try {
            addPhone({
                ...data,
                lastUpdate: new Date().toISOString().split('T')[0],
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString(),
            });

            addNotification({
                type: 'success',
                title: 'דומיין נוסף בהצלחה',
                message: `הדומיין ${data.domain} נוסף למערכת`,
                duration: 5000,
                timestamp: new Date(),
            });

            reset();
            closeAddPhoneModal();
            onSuccess?.();
        } catch {
            addNotification({
                type: 'error',
                title: 'שגיאה בהוספת דומיין',
                message: 'אירעה שגיאה בהוספת הדומיין. אנא נסה שוב.',
                duration: 5000,
                timestamp: new Date(),
            });
        }
    };

    const handleCancel = () => {
        reset();
        closeAddPhoneModal();
    };

    return (
        <div className="bg-white rounded-lg shadow-xl max-w-2xl mx-auto">
            {/* Header */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200">
                <div className="flex items-center">
                    <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center ml-3">
                        <Plus className="w-5 h-5 text-blue-600" />
                    </div>
                    <div>
                        <h2 className="text-xl font-semibold text-gray-900">הוסף דומיין חדש</h2>
                        <p className="text-sm text-gray-500">מלא את הפרטים להוספת דומיין חדש</p>
                    </div>
                </div>
                <button
                    onClick={handleCancel}
                    className="text-gray-400 hover:text-gray-600 transition-colors"
                    title="ביטול"
                    aria-label="ביטול"
                >
                    <X className="w-6 h-6" />
                </button>
            </div>

            {/* Form */}
            <form onSubmit={handleSubmit(onSubmit)} className="p-6 space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Phone Number */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            מספר פלאפון *
                        </label>
                        <input
                            {...register('phone')}
                            type="text"
                            placeholder="050-1234567"
                            className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.phone ? 'border-red-300' : 'border-gray-300'
                                }`}
                        />
                        {errors.phone && (
                            <p className="mt-1 text-sm text-red-600">{errors.phone.message}</p>
                        )}
                    </div>

                    {/* Domain */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            שם הדומיין *
                        </label>
                        <input
                            {...register('domain')}
                            type="text"
                            placeholder="example.co.il"
                            className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.domain ? 'border-red-300' : 'border-gray-300'
                                }`}
                        />
                        {errors.domain && (
                            <p className="mt-1 text-sm text-red-600">{errors.domain.message}</p>
                        )}
                    </div>

                    {/* Website */}
                    <div className="md:col-span-2">
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            כתובת האתר *
                        </label>
                        <input
                            {...register('website', {
                                setValueAs: (v) => {
                                    const s = (v || '').trim();
                                    if (!s) return '';
                                    if (/^https?:\/\//i.test(s)) return s;
                                    return `https://${s}`;
                                },
                            })}
                            onBlur={(e) => {
                                const s = (e.target.value || '').trim();
                                if (s && !/^https?:\/\//i.test(s)) {
                                    e.target.value = `https://${s}`;
                                }
                            }}
                            type="text"
                            placeholder="https://example.co.il"
                            className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.website ? 'border-red-300' : 'border-gray-300'
                                }`}
                        />
                        {errors.website && (
                            <p className="mt-1 text-sm text-red-600">{errors.website.message}</p>
                        )}
                    </div>

                    {/* Owner */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            שם הבעלים *
                        </label>
                        <input
                            {...register('owner')}
                            type="text"
                            placeholder="משה כהן"
                            className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.owner ? 'border-red-300' : 'border-gray-300'
                                }`}
                        />
                        {errors.owner && (
                            <p className="mt-1 text-sm text-red-600">{errors.owner.message}</p>
                        )}
                    </div>

                    {/* Email */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            כתובת אימייל *
                        </label>
                        <input
                            {...register('email')}
                            type="email"
                            placeholder="moshe@example.co.il"
                            className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.email ? 'border-red-300' : 'border-gray-300'
                                }`}
                        />
                        {errors.email && (
                            <p className="mt-1 text-sm text-red-600">{errors.email.message}</p>
                        )}
                    </div>

                    {/* Package */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            סוג החבילה *
                        </label>
                        <select
                            {...register('package')}
                            className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.package ? 'border-red-300' : 'border-gray-300'
                                }`}
                        >
                            <option value="Linux Mini Professionals">Linux Mini Professionals</option>
                            <option value="Linux Standard">Linux Standard</option>
                            <option value="Linux Premium">Linux Premium</option>
                            <option value="Windows Basic">Windows Basic</option>
                            <option value="Windows Professional">Windows Professional</option>
                        </select>
                        {errors.package && (
                            <p className="mt-1 text-sm text-red-600">{errors.package.message}</p>
                        )}
                    </div>

                    {/* Amount */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            סכום (₪) *
                        </label>
                        <input
                            {...register('amount', { valueAsNumber: true })}
                            type="number"
                            step="0.01"
                            min="0"
                            placeholder="299.99"
                            className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.amount ? 'border-red-300' : 'border-gray-300'
                                }`}
                        />
                        {errors.amount && (
                            <p className="mt-1 text-sm text-red-600">{errors.amount.message}</p>
                        )}
                    </div>

                    {/* Status */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            סטטוס *
                        </label>
                        <select
                            {...register('status')}
                            className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.status ? 'border-red-300' : 'border-gray-300'
                                }`}
                        >
                            <option value="pending">ממתין</option>
                            <option value="paid">שולם</option>
                            <option value="overdue">פיגור</option>
                            <option value="free">חינם</option>
                            <option value="renewal">לחידוש</option>
                            <option value="paused">מושהה</option>
                            <option value="delete_backup">למחוק יש גיבוי</option>
                            <option value="delete_no_backup">למחוק אין גיבוי</option>
                        </select>
                        {errors.status && (
                            <p className="mt-1 text-sm text-red-600">{errors.status.message}</p>
                        )}
                    </div>

                    {/* Priority */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            עדיפות *
                        </label>
                        <select
                            {...register('priority')}
                            className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.priority ? 'border-red-300' : 'border-gray-300'
                                }`}
                        >
                            <option value="low">נמוכה</option>
                            <option value="medium">בינונית</option>
                            <option value="high">גבוהה</option>
                            <option value="to-delete">למחוק</option>
                            <option value="to-check">לבדוק</option>
                        </select>
                        {errors.priority && (
                            <p className="mt-1 text-sm text-red-600">{errors.priority.message}</p>
                        )}
                    </div>

                    {/* Next Payment */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            תשלום הבא *
                        </label>
                        <input
                            {...register('nextPayment')}
                            type="date"
                            className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.nextPayment ? 'border-red-300' : 'border-gray-300'
                                }`}
                        />
                        {errors.nextPayment && (
                            <p className="mt-1 text-sm text-red-600">{errors.nextPayment.message}</p>
                        )}
                    </div>
                </div>

                {/* Start Date */}
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        תאריך התחלה *
                    </label>
                    <input
                        {...register('startDate')}
                        type="date"
                        className={`block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.startDate ? 'border-red-300' : 'border-gray-300'
                            }`}
                    />
                    {errors.startDate && (
                        <p className="mt-1 text-sm text-red-600">{errors.startDate.message}</p>
                    )}
                </div>

                {/* Actions */}
                <div className="flex items-center justify-end space-x-3 space-x-reverse pt-6 border-t border-gray-200">
                    <button
                        type="button"
                        onClick={handleCancel}
                        className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                    >
                        ביטול
                    </button>
                    <button
                        type="submit"
                        disabled={isSubmitting}
                        className="px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        {isSubmitting ? 'מוסיף...' : 'הוסף דומיין'}
                    </button>
                </div>
            </form>
        </div>
    );
}
