'use client';

import { ChangeEventHandler, RefObject, useId, useState } from 'react';
import useSWR from 'swr';

import ConfirmationModal, {
  ConfirmationModalProps,
} from '@/components/modal/ConfirmationModal';
import TextArea from '@/components/input/TextArea';
import { ProjectFlockFormConfirmationTable } from '@/components/pages/production/project-flock/form/ProjectFlockForm';

import { ProjectFlockFormValues } from '@/components/pages/production/project-flock/form/ProjectFlockForm.schema';
import { Color } from '@/types/theme';
import { isResponseSuccess } from '@/lib/api-helper';
import { KandangApi } from '@/services/api/master-data';

interface ProjectFlockConfirmationModalProps
  extends Omit<ConfirmationModalProps, 'children' | 'primaryButton'> {
  ref: RefObject<HTMLDialogElement | null>;
  type?: 'info' | 'success' | 'error';
  projectFlockIds?: number[];
  projectFlockForm?: ProjectFlockFormValues;
  onClose?: () => void;

  withNote?: boolean;
  noteLabel?: string;
  rows?: number;
  placeholder?: string;

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

const ProjectFlockConfirmationModal = ({
  ref,
  type = 'success',
  projectFlockForm,
  projectFlockIds,
  onClose,
  withNote,
  rows = 4,
  noteLabel,
  placeholder = 'Alasan',
  primaryButton,
  secondaryButton,
  ...props
}: ProjectFlockConfirmationModalProps) => {
  const randomId = useId();

  const [notes, setNotes] = useState('');

  const kandangUrl = `${KandangApi.basePath}?${new URLSearchParams({
    search: '',
    location_id: projectFlockForm?.location_id
      ? String(projectFlockForm?.location_id)
      : '',
    limit: '500',
  }).toString()}`;
  const { data: kandang } = useSWR(kandangUrl, KandangApi.getAllFetcher);

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

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

  return (
    <ConfirmationModal
      ref={ref}
      iconPosition='left'
      type={type}
      primaryButton={{
        ...primaryButton,
        text: primaryButton?.text ?? 'Oke',
        color: primaryButton?.color ?? 'primary',
        className: 'rounded-lg',
        onClick: () => {
          if (withNote) {
            primaryButton?.onClick?.(notes);
          } else if (primaryButton && primaryButton?.onClick) {
            primaryButton?.onClick?.('');
          } else {
            closeModalHandler();
          }

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

                setNotes('');
              },
            }
          : undefined
      }
      className={{
        modalBox: 'max-h-full',
      }}
      {...props}
    >
      <div className='flex flex-col gap-4'>
        {!projectFlockIds && projectFlockForm && (
          <ProjectFlockFormConfirmationTable
            projectFlockForm={projectFlockForm}
            kandangs={
              isResponseSuccess(kandang) && kandang?.data ? kandang.data : []
            }
          />
        )}

        {/* {projectFlockIds &&
          !projectFlockForm &&
          projectFlockIds.map((projectFlockId, idx) => (
            <ProjectFlockFormConfirmationTable
              key={idx}
              projectFlockId={projectFlockId}
              kandangs={
                isResponseSuccess(kandang) && kandang?.data ? kandang.data : []
              }
            />
          ))} */}

        {withNote && (
          <TextArea
            name={randomId}
            label={noteLabel}
            placeholder={placeholder}
            value={notes}
            onChange={notesChangeHandler}
            rows={rows}
          />
        )}
      </div>
    </ConfirmationModal>
  );
};

export default ProjectFlockConfirmationModal;
