'use client';

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

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

import { ColumnDef } from '@tanstack/react-table';
import { cn, formatDate, formatNumber } from '@/lib/helper';
import { TransferToLayingFormValues } from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm.schema';
import { Color } from '@/types/theme';
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
import { isResponseSuccess } from '@/lib/api-helper';

interface TransferToLayingConfirmationModalProps
  extends Omit<ConfirmationModalProps, 'children' | 'primaryButton'> {
  ref: RefObject<HTMLDialogElement | null>;
  type?: 'info' | 'success' | 'error';
  transferToLayingIds?: number[];
  transferToLayingForm?: TransferToLayingFormValues;
  onClose?: () => void;

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

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

interface TransferToLayingConfirmationTableDataType {
  label: string;
  value: string;
  subRows?: TransferToLayingConfirmationTableDataType[];
}

const TransferToLayingConfirmationModalTable = ({
  transferToLayingForm,
  transferToLayingId,
}: {
  transferToLayingForm?: TransferToLayingFormValues;
  transferToLayingId?: number;
}) => {
  const { data: transferToLaying, isLoading: isLoadingTransferToLaying } =
    useSWR(
      transferToLayingId
        ? ['detail-transfer-to-laying', String(transferToLayingId)]
        : undefined,
      ([id]) => TransferToLayingApi.getSingle(Number(id))
    );

  const confirmationTableColumns: ColumnDef<TransferToLayingConfirmationTableDataType>[] =
    [
      {
        header: 'Label',
        accessorKey: 'label',
        enableSorting: false,
        cell: ({ row }) => {
          const isSubRow = row.depth > 0;

          return (
            <>
              {!isSubRow && row.original.label}

              {isSubRow && (
                <div
                  className={cn('w-full min-h-full flex items-stretch gap-0')}
                >
                  <div className='w-px mx-4 bg-base-content/10' />
                  <span className='p-3'>{row.original.label}</span>
                </div>
              )}
            </>
          );
        },
      },
      {
        header: 'Value',
        accessorKey: 'value',
        enableSorting: false,
      },
    ];

  const confirmationTableData: TransferToLayingConfirmationTableDataType[] = [
    {
      label: 'Tanggal',
      value: formatDate(
        transferToLayingId && isResponseSuccess(transferToLaying)
          ? transferToLaying.data.transfer_date
          : transferToLayingForm?.transfer_date,
        'DD MMMM YYYY'
      ),
    },
    {
      label: 'Flock Asal',
      value:
        transferToLayingId && isResponseSuccess(transferToLaying)
          ? transferToLaying.data.from_project_flock.flock_name
          : (transferToLayingForm?.flockSource?.label ?? '-'),
      subRows:
        transferToLayingId && isResponseSuccess(transferToLaying)
          ? (transferToLaying.data.sources?.map(
              (sourceProjectFlockKandang) => ({
                label:
                  sourceProjectFlockKandang.source_project_flock_kandang.kandang
                    .name,
                value: formatNumber(
                  Number(sourceProjectFlockKandang.qty),
                  'en-US'
                ),
              })
            ) ?? [])
          : (transferToLayingForm?.flockSourceKandangs?.map((kandang) => ({
              label: kandang.kandang.label,
              value: formatNumber(Number(kandang.quantity), 'en-US'),
            })) ?? []),
    },
    {
      label: 'Flock Tujuan',
      value:
        transferToLayingId && isResponseSuccess(transferToLaying)
          ? transferToLaying.data.to_project_flock.flock_name
          : (transferToLayingForm?.flockDestination?.label ?? '-'),
      subRows:
        transferToLayingId && isResponseSuccess(transferToLaying)
          ? (transferToLaying.data.targets?.map(
              (targetProjectFlockKandang) => ({
                label:
                  targetProjectFlockKandang.target_project_flock_kandang.kandang
                    .name,
                value: formatNumber(
                  Number(targetProjectFlockKandang.qty),
                  'en-US'
                ),
              })
            ) ?? [])
          : (transferToLayingForm?.flockDestinationKandangs?.map((kandang) => ({
              label: kandang.kandang.label,
              value: formatNumber(Number(kandang.quantity), 'en-US'),
            })) ?? []),
    },
    {
      label: 'Jumlah Transfer',
      value: formatNumber(
        transferToLayingId && isResponseSuccess(transferToLaying)
          ? Number(
              transferToLaying.data.sources.reduce(
                (total, source) => total + Number(source.qty),
                0
              )
            )
          : Number(transferToLayingForm?.totalQuantity),
        'en-US'
      ),
    },
    {
      label: 'Notes',
      value:
        transferToLayingId && isResponseSuccess(transferToLaying)
          ? (transferToLaying.data.notes ?? '-')
          : (transferToLayingForm?.reason ?? '-'),
    },
  ];

  return (
    <Table<TransferToLayingConfirmationTableDataType>
      columns={confirmationTableColumns}
      data={confirmationTableData}
      isLoading={
        isLoadingTransferToLaying ||
        (!transferToLayingId && !transferToLayingForm)
      }
      withPagination={false}
      pageSize={10000}
      expanded={true}
      getSubRows={(row) => row.subRows}
      className={{
        headerRowClassName: 'border-b border-base-content/10',
        bodyRowClassName: 'border-none',
        bodySubRowClassName: () => 'border-none',
        bodySubRowColumnClassName: () => 'first:p-0',
      }}
    />
  );
};

const TransferToLayingConfirmationModal = ({
  ref,
  type = 'success',
  transferToLayingForm,
  transferToLayingIds,
  onClose,
  withNote,
  rows = 4,
  noteLabel,
  placeholder = 'Alasan Transfer',
  primaryButton,
  secondaryButton,
  ...props
}: TransferToLayingConfirmationModalProps) => {
  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}
      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'>
        {!transferToLayingIds && transferToLayingForm && (
          <TransferToLayingConfirmationModalTable
            transferToLayingForm={transferToLayingForm}
          />
        )}

        {transferToLayingIds &&
          !transferToLayingForm &&
          transferToLayingIds.map((transferToLayingId, idx) => (
            <TransferToLayingConfirmationModalTable
              key={idx}
              transferToLayingId={transferToLayingId}
            />
          ))}

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

export default TransferToLayingConfirmationModal;
