import { toast } from 'sonner';

export interface CustomerProps {
  id: string;
  msisdn: string;
  email: string;
  fullname: string;
  username: string;
}

export interface RoleListProps {
  id: string;
  name: string;
  roles: string;
  status: string;
}

export interface CreateUserParams {
  email: string;
  username: string;
  password: string;
  retype_password: string;
  name: string;
  id_role: string;
  status: string;
}

export const initialStateCreateUser: {
  email: string;
  username: string;
  password: string;
  retype_password: string;
  name: string;
  id_role: string;
  status: string;
  customerid: string;
} = {
  email: '',
  username: '',
  password: '',
  retype_password: '',
  name: '',
  id_role: '',
  status: '',
  customerid: ''
};

export const validateFormCreateUser = (
  formField: typeof initialStateCreateUser,
  setErrors: React.Dispatch<React.SetStateAction<Record<string, string>>>,
  mode: 'create' | 'update' = 'create'
) => {
  const requiredFields =
    mode === 'create'
      ? [
          { key: 'name', label: 'Name' },
          { key: 'username', label: 'Username' },
          { key: 'email', label: 'Email' },
          { key: 'customerid', label: 'Customer ID' },
          { key: 'id_role', label: 'Role' },
          { key: 'status', label: 'Status' },
          { key: 'password', label: 'Password' },
          { key: 'retype_password', label: 'Retype Password' }
        ]
      : [
          { key: 'name', label: 'Name' },
          { key: 'username', label: 'Username' },
          { key: 'customerid', label: 'Customer ID' },
          { key: 'email', label: 'Email' },
          { key: 'id_role', label: 'Role' },
          { key: 'status', label: 'Status' }
        ];

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

  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;
    }
  });

  setErrors(newErrors);
  return isValid;
};
