'use client';

import { ChangeEventHandler, useId, useState } from 'react';

import ConfirmationModal, {
  ConfirmationModalProps,
} from '@/components/modal/ConfirmationModal';
import TextArea from '@/components/input/TextArea';

import { Color } from '@/types/theme';

interface ConfirmationModalWithNotesProps
  extends Omit<ConfirmationModalProps, 'children' | 'primaryButton'> {
  rows?: number;
  placeholder?: string;
  onClose?: () => void;

  primaryButton?: {
    text?: string;
    color?: Color;
    isLoading?: boolean;
    onClick?: (notes: string) => void;
  };
}

const ConfirmationModalWithNotes: React.FC<ConfirmationModalWithNotesProps> = ({
  ref,
  type = 'info',
  text,
  closeOnBackdrop,
  primaryButton,
  secondaryButton,
  className,
  rows = 3,
  placeholder = 'Catatan...',
  onClose,
  ...props
}) => {
  const randomId = useId();
  const [notes, setNotes] = useState('');

  const notesChangeHandler: ChangeEventHandler<HTMLTextAreaElement> = (e) => {
    setNotes(e.target.value);
  };

  const closeModalHandler = () => {
    onClose?.();
    ref.current?.close();
  };

  return (
    <ConfirmationModal
      ref={ref}
      type={type}
      text={text}
      closeOnBackdrop={closeOnBackdrop}
      primaryButton={{
        ...primaryButton,
        onClick: () => {
          if (primaryButton && primaryButton?.onClick) {
            primaryButton?.onClick?.(notes);
          } else {
            closeModalHandler();
          }

          setNotes('');
        },
      }}
      secondaryButton={
        secondaryButton
          ? {
              ...secondaryButton,
              text: secondaryButton?.text ?? 'Tidak',
              onClick: (e) => {
                if (secondaryButton && secondaryButton?.onClick) {
                  secondaryButton.onClick?.(e);
                } else {
                  closeModalHandler();
                }

                setNotes('');
              },
            }
          : undefined
      }
      className={className}
      {...props}
    >
      <TextArea
        name={randomId}
        placeholder={placeholder}
        value={notes}
        onChange={notesChangeHandler}
        rows={rows}
      />
    </ConfirmationModal>
  );
};

export default ConfirmationModalWithNotes;
