import { toast } from 'sonner';

export interface selectedNotification {
  customers: string[];
  all_customer: string;
  type: string;
  via: string;
  subject: string;
  content: string;
}

export const initialStateNotification: selectedNotification = {
  customers: [],
  all_customer: '',
  type: '',
  via: '',
  subject: '',
  content: ''
};

export const validateFormNotification = (
  formField: typeof initialStateNotification,
  setErrors: React.Dispatch<React.SetStateAction<Record<string, string>>>
) => {
  const requiredFields = [
    { key: 'all_customer', label: 'Send To' },
    { key: 'type', label: 'Type' },
    { key: 'via', label: 'Via' }
  ];

  const newErrors: Record<string, string> = {};
  let isValid = true;

  // Validasi field yang wajib secara umum
  requiredFields.forEach(({ key, label }) => {
    if (
      formField[key as keyof typeof formField] === '' ||
      formField[key as keyof typeof formField] === null ||
      formField[key as keyof typeof formField] === undefined
    ) {
      newErrors[key] = `${label} is required`;
      toast.error(`${label} is required`);
      isValid = false;
    }
  });

  // Validasi khusus content
  if (formField.via === 'whatsapp') {
    if (!formField.content || !/^\d{5}$/.test(formField.content)) {
      newErrors.content = 'Content harus berupa 5 digit angka (OTP)';
      toast.error('Content harus berupa 5 digit angka (OTP)');
      isValid = false;
    }
  } else {
    if (!formField.content || formField.content.trim() === '') {
      newErrors.content = 'Content is required';
      toast.error('Content is required');
      isValid = false;
    }
  }

  setErrors(newErrors);
  return isValid;
};
