// src/client/entities/blacklist/model/useBlacklistForm.ts
// Hook for managing blacklist form state and validation

import { ref, watch, type Ref } from 'vue';
import { z } from 'zod';
import type { BlacklistEntry } from '@shared/contracts/blacklist';
import { blacklistCreateSchema } from '@shared/contracts/blacklist';
import { formatPhoneNumberAsYouType, isValidPhoneNumber } from '@shared/utils/formatters';

export interface BlacklistFormErrors {
  name: string;
  phone: string;
  bookingEngineCheck: string;
}

export interface UseBlacklistFormOptions {
  mode: 'create' | 'edit';
  entry?: BlacklistEntry;
}

export interface UseBlacklistFormReturn {
  // Form state
  name: Ref<string>;
  phone: Ref<string>;
  bookingEngineCheck: Ref<'YES' | 'NO'>;
  comment: Ref<string>;

  // Validation errors
  errors: Ref<BlacklistFormErrors>;

  // Methods
  initForm: () => void;
  validate: () => boolean;
  getCreateData: () => { name: string; phone: string; bookingEngineCheck: 'YES' | 'NO'; comment?: string };
  getUpdateData: () => { name?: string; phone?: string; bookingEngineCheck?: 'YES' | 'NO'; comment?: string };
  handlePhoneInput: (event: Event) => void;
}

export function useBlacklistForm(options: UseBlacklistFormOptions): UseBlacklistFormReturn {
  // Form state
  const name = ref('');
  const phone = ref('');
  const bookingEngineCheck = ref<'YES' | 'NO'>('NO');
  const comment = ref('');
  
  // Validation errors
  const errors = ref<BlacklistFormErrors>({ name: '', phone: '', bookingEngineCheck: '' });

  // Initialize form based on mode and entry
  function initForm(): void {
    if (options.entry && options.mode === 'edit') {
      name.value = options.entry.name;
      // Strip leading + from phone if present (to avoid double + with visual prefix)
      phone.value = options.entry.phone.startsWith('+')
        ? options.entry.phone.substring(1)
        : options.entry.phone;
      bookingEngineCheck.value = options.entry.bookingEngineCheck;
      comment.value = options.entry.comment || '';
    } else if (options.mode === 'create') {
      // Reset form for create mode
      name.value = '';
      phone.value = '';
      bookingEngineCheck.value = 'NO';
      comment.value = '';
    }
  }

  // Handle phone input - clean and format as user types
  function handlePhoneInput(event: Event): void {
    const target = event.target as HTMLInputElement;
    // Remove all "+" symbols first to ensure complete cleanup
    const valueWithoutPlus = target.value.replace(/\+/g, '');
    // Then format the cleaned value
    phone.value = formatPhoneNumberAsYouType(valueWithoutPlus);
  }

  // Watch options.entry to reinitialize form when entry changes
  watch(() => options.entry, () => initForm(), { deep: true, immediate: true });

  // Validate form using Zod schema
  function validate(): boolean {
    // Clear previous errors
    errors.value = { name: '', phone: '', bookingEngineCheck: '' };

    // Validate name
    if (!name.value.trim()) {
      errors.value.name = 'Полное имя обязательно';
      return false;
    }

    // Validate phone using isValidPhoneNumber (checks 10-15 digits after cleanup)
    if (!phone.value.trim()) {
      errors.value.phone = 'Телефон обязателен';
      return false;
    }

    if (!isValidPhoneNumber(phone.value)) {
      errors.value.phone = 'Номер телефона должен содержать от 10 до 15 цифр';
      return false;
    }

    // Validate bookingEngineCheck
    if (!bookingEngineCheck.value) {
      errors.value.bookingEngineCheck = 'Проверка системы бронирования обязательна';
      return false;
    }

    return true;
  }

  // Get data for create operation
  function getCreateData(): { name: string; phone: string; bookingEngineCheck: 'YES' | 'NO'; comment?: string } {
    return {
      name: name.value,
      phone: phone.value,
      bookingEngineCheck: bookingEngineCheck.value,
      comment: comment.value || undefined,
    };
  }

  // Get data for update operation
  function getUpdateData(): { name?: string; phone?: string; bookingEngineCheck?: 'YES' | 'NO'; comment?: string } {
    return {
      name: name.value,
      phone: phone.value,
      bookingEngineCheck: bookingEngineCheck.value,
      comment: comment.value || undefined,
    };
  }

  // Watchers to clear errors when user starts typing
  watch(name, () => {
    if (errors.value.name) {
      errors.value.name = '';
    }
  });

  watch(phone, () => {
    if (errors.value.phone) {
      errors.value.phone = '';
    }
  });

  watch(bookingEngineCheck, () => {
    if (errors.value.bookingEngineCheck) {
      errors.value.bookingEngineCheck = '';
    }
  });

  return {
    name,
    phone,
    bookingEngineCheck,
    comment,
    errors,
    initForm,
    validate,
    getCreateData,
    getUpdateData,
    handlePhoneInput,
  };
}
