'use client';

import { Controller, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

import { TextArea, TextInput } from '@/components/input';
import { ModalForm } from '@/components/modal';
import { useDialogsStore } from '@/stores/dialogs';

import { type IUpdateBlockDTO, schemaUpdateBlock } from '../backend/types';
import { useUpdateBlock } from '../backend/use-update-block';
import { SelectParent } from '../components/select-parent';
import { type IBlock } from '../models/oss';
import { type LayoutManager } from '../models/oss-layout-api';

export interface DlgEditBlockProps {
  manager: LayoutManager;
  target: IBlock;
}

export function DlgEditBlock() {
  const { manager, target } = useDialogsStore(state => state.props as DlgEditBlockProps);
  const { updateBlock } = useUpdateBlock();

  const {
    handleSubmit,
    control,
    register,
    formState: { errors, isValid }
  } = useForm<IUpdateBlockDTO>({
    resolver: zodResolver(schemaUpdateBlock),
    defaultValues: {
      target: target.id,
      item_data: {
        title: target.title,
        description: target.description,
        parent: target.parent
      },
      layout: manager.layout
    },
    mode: 'onChange'
  });

  function onSubmit(data: IUpdateBlockDTO) {
    if (data.item_data.parent !== target.parent) {
      manager.onBlockChangeParent(data.target, data.item_data.parent);
    }
    return updateBlock({ itemID: manager.oss.id, data });
  }

  return (
    <ModalForm
      header='Редактирование блока'
      submitText='Сохранить'
      canSubmit={isValid}
      onSubmit={event => void handleSubmit(onSubmit)(event)}
      className='w-160 px-6 pb-2 h-fit cc-column'
    >
      <TextInput
        id='operation_title' //
        label='Название'
        {...register('item_data.title')}
        error={errors.item_data?.title}
      />
      <Controller
        name='item_data.parent'
        control={control}
        render={({ field }) => (
          <SelectParent
            items={manager.oss.blocks.filter(block => block.id !== target.id)}
            value={field.value ? manager.oss.blockByID.get(field.value) ?? null : null}
            placeholder='Блок содержания не выбран'
            onChange={value => field.onChange(value ? value.id : null)}
          />
        )}
      />

      <TextArea
        id='operation_comment' //
        label='Описание'
        noResize
        rows={5}
        {...register('item_data.description')}
      />
    </ModalForm>
  );
}
