'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 { Edit, X } from 'lucide-react';
import { useEffect } from 'react';

interface EditPhoneFormProps {
  phoneId: string;
  onSuccess?: () => void;
}

export default function EditPhoneForm({ phoneId, onSuccess }: EditPhoneFormProps) {
  const { phones, updatePhone } = usePhoneStore();
  const { closeEditPhoneModal, addNotification } = useUIStore();

  const phone = phones.find(p => p.id === phoneId);

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
    setValue,
  } = useForm<PhoneFormData>({
    resolver: zodResolver(phoneSchema),
    defaultValues: {
      phone: '',
      domain: '',
      website: '',
      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],
    },
  });

  useEffect(() => {
    if (phone) {
      setValue('phone', phone.phone);
      setValue('domain', phone.domain);
      setValue('website', phone.website);
      setValue('owner', phone.owner);
      setValue('email', phone.email);
      setValue('package', phone.package);
      setValue('amount', phone.amount);
      setValue('status', phone.status);
      setValue('priority', phone.priority);
      setValue('startDate', phone.startDate);
      setValue('nextPayment', phone.nextPayment);
      setValue('notes', phone.notes || '');
    }
  }, [phone, setValue]);

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

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

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

  const handleCancel = () => {
    closeEditPhoneModal();
  };

  if (!phone) {
    return (
      <div className="bg-white rounded-lg shadow-xl max-w-2xl mx-auto p-6">
        <div className="text-center">
          <p className="text-gray-500">דומיין לא נמצא</p>
        </div>
      </div>
    );
  }

  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-green-100 rounded-lg flex items-center justify-center ml-3">
            <Edit className="w-5 h-5 text-green-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>

          {/* 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>
        </div>

        {/* Notes */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            הערות
          </label>
          <textarea
            {...register('notes')}
            rows={4}
            placeholder="הוסף הערות נוספות..."
            className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          />
        </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-green-600 border border-transparent rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isSubmitting ? 'מעדכן...' : 'עדכן דומיין'}
          </button>
        </div>
      </form>
    </div>
  );
}