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

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

import { type FormAttachmentsProps, type FormAttachmentsValues } from './types';
import Attachments from '.';

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

  useFieldArray({ control, name });

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

  const handleDeleteAttachment = (
    attachment: SortableAttachment,
    index: number,
  ) => {
    const newValue = attachments.toSpliced(index, 1);
    setValue(name, newValue, { shouldDirty: true });
    inputProps.onDelete?.(attachment, index);
  };

  const handleAddAttachments = (newAttachments: SortableAttachment[]) => {
    const positionedAttachments = newAttachments.map((attachment, index) => ({
      ...attachment,
      position: attachments.length + index,
    }));

    const newValue = attachments.concat(positionedAttachments);
    setValue(name, newValue, { shouldDirty: true });
    inputProps.onAdd?.(positionedAttachments);
  };

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

    const newValue = attachments.toSpliced(index, 1, newAttachment);
    setValue(name, newValue, { shouldDirty: true });
    inputProps.onEdit?.(attachment, index, values);
  };

  const handleSortAttachments = (newValue: SortableAttachment[]) => {
    const positionedAttachments = newValue.map((attachment, index) => ({
      ...attachment,
      position: index,
    }));

    setValue(name, positionedAttachments, { shouldDirty: true });
    inputProps.onSort?.(positionedAttachments);
  };

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

export default FormAttachments;
