import { useFormContext, useFieldArray, useWatch } from 'react-hook-form';

import {
  SortableAttachment,
  UpdateAttachmentData,
} from 'src/types/attachments';

import Attachments, { AttachmentsProps } from './Attachments';

export type FormAttachmentsValues = {
  [k: string]: SortableAttachment[];
};

export type FormAttachmentsProps = {
  name: string;
  inputProps?: Omit<AttachmentsProps, 'attachments' | 'editing'>;
};

const FormAttachments = ({ name, inputProps = {} }: FormAttachmentsProps) => {
  const { control } = useFormContext<FormAttachmentsValues>();

  const { remove, update, append, replace } = useFieldArray({
    control,
    name,
  });

  const attachments = useWatch({
    control,
    name,
  });

  const handleDeleteAttachment = (
    attachment: SortableAttachment,
    index: number,
  ) => {
    remove(index);
    inputProps.onDelete?.(attachment, index);
  };

  const handleAddAttachments = (newAttachments: SortableAttachment[]) => {
    append(newAttachments);
    inputProps.onAdd?.(newAttachments);
  };

  const handleEditAttachment = (
    attachment: SortableAttachment,
    index: number,
    values: UpdateAttachmentData,
  ) => {
    const { name: attachmentName, extension } = values;
    const newAttachment = {
      ...attachment,
      name: extension ? `${attachmentName}.${extension}` : attachmentName,
    };

    update(index, newAttachment);
    inputProps.onEdit?.(attachment, index, values);
  };

  const handleSortAttachments = (newAttachments: SortableAttachment[]) => {
    replace(newAttachments);
    inputProps.onSort?.(newAttachments);
  };

  return (
    <Attachments
      {...inputProps}
      editing
      attachments={attachments}
      onDelete={handleDeleteAttachment}
      onAdd={handleAddAttachments}
      onEdit={handleEditAttachment}
      onSort={handleSortAttachments}
    />
  );
};

export default FormAttachments;
