'use client';

import Alert from '@/components/Alert';
import Button from '@/components/Button';
import { cn } from '@/lib/helper';
import { Icon } from '@iconify/react';
import { useEffect, useRef } from 'react';

/**
 * Alert Unique Error List
 * @param formErrorList - Array of error messages
 * @param onClose - Function to close the alert
 */
const AlertErrorList = ({
  formErrorList,
  className,
  onClose,
  title,
}: {
  formErrorList: string[];
  className?: {
    alert?: string;
    button?: string;
    headerWrapper?: string;
    headerIcon?: string;
    headerText?: string;
    titleWrapper?: string;
    ul?: string;
    li?: string;
  };
  onClose: () => void;
  title?: string;
}) => {
  const alertRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (formErrorList.length > 0) {
      alertRef.current?.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
      });
    }
  }, [formErrorList.length]);

  if (formErrorList.length === 0) return null;

  return (
    <Alert
      ref={alertRef}
      color='error'
      className={cn(
        'w-full flex flex-col gap-2 px-3 rounded-lg',
        className?.alert
      )}
    >
      <div
        className={cn(
          'flex justify-between items-center gap-2 w-full',
          className?.headerWrapper
        )}
      >
        <div className={cn('flex items-center gap-2', className?.titleWrapper)}>
          <Icon
            icon='material-symbols:error-outline'
            className={cn(className?.headerIcon)}
            width={20}
            height={20}
          />
          <span className={cn('font-semibold text-sm', className?.headerText)}>
            {title || `Terdapat ${formErrorList.length} error pada form:`}
          </span>
        </div>
        <Button
          type='button'
          onClick={onClose}
          variant='link'
          className={cn('ml-auto p-0 w-fit text-white', className?.button)}
          color='none'
        >
          <Icon icon='material-symbols:close' width={20} height={20} />
        </Button>
      </div>
      <ul
        className={cn(
          'list-disc list-inside pl-4 space-y-1.5 w-full',
          className?.ul
        )}
      >
        {formErrorList.map((error, index) => (
          <li key={index} className={cn('text-sm', className?.li)}>
            {error}
          </li>
        ))}
      </ul>
    </Alert>
  );
};

export default AlertErrorList;
