import Button from '@/components/Button';
import Card from '@/components/Card';
import { FormHeader } from '@/components/helper/form/FormHeader';
import RequirePermission from '@/components/helper/RequirePermission';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import Table from '@/components/Table';
import {
  FINANCE_INITIAL_BALANCE_STATUS,
  FINANCE_TRANSACTION_STATUS,
  FINANCE_INJECTION_STATUS,
} from '@/config/constant';
import { formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
import { FinanceApi } from '@/services/api/finance';
import { Finance } from '@/types/api/finance/finance';
import { Icon } from '@iconify/react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import toast from 'react-hot-toast';

const FinanceDetail = ({ finance }: { finance: Finance }) => {
  const router = useRouter();
  const deleteModal = useModal();
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);
  const informasiUmum = [
    {
      label: 'ID',
      value: finance.payment_code || '-',
    },
    {
      label: 'Jenis Transaksi',
      value: formatTitleCase(
        (finance.transaction_type || '').split('_').join(' ')
      ),
    },
    {
      label: 'Pihak',
      value: finance.party?.id ? finance.party?.name : '-',
    },
    {
      label: 'Tanggal',
      value: finance.payment_date
        ? formatDate(finance.payment_date, 'DD MMM yyyy')
        : '-',
    },
    {
      label: 'Metode Pembayaran',
      value: finance.payment_method || '-',
    },
    {
      label: 'Catatan',
      value: finance.notes || '-',
    },
  ];
  const informasiTransfer = [
    {
      label: 'No. Referensi',
      value: finance.reference_number ?? '-',
    },
    {
      label: 'Nomor Rekening',
      value: finance.bank?.alias
        ? `${finance.bank?.alias} - ${finance.bank?.account_number} - ${finance.bank?.owner}`
        : '-',
    },
    {
      label: `Rekening ${formatTitleCase(finance.party?.type || '')}`,
      value: finance.party?.account_number || '-',
    },
    {
      label: 'Nominal',
      value: formatCurrency(
        finance.transaction_type === 'INJECTION'
          ? finance.nominal || 0
          : Math.abs(finance.nominal || 0)
      ),
    },
  ].filter((item) => {
    // Hide party account number row if transaction type is INJECTION
    if (
      FINANCE_INJECTION_STATUS.includes(finance.transaction_type || '') &&
      item.label === `Rekening ${formatTitleCase(finance.party?.type || '')}`
    ) {
      return false;
    }
    return true;
  });

  const confirmationModalDeleteClickHandler = async () => {
    setIsDeleteLoading(true);

    await FinanceApi.delete(finance.id as number);
    router.back();

    deleteModal.closeModal();
    toast.success('Successfully delete Finance!');
    setIsDeleteLoading(false);
  };

  return (
    <div className='flex flex-col gap-6 p-6'>
      <FormHeader title='' backUrl='/finance' />

      <Card
        title='Detail Keuangan'
        className={{
          wrapper: 'w-full',
        }}
        variant='bordered'
      >
        <div className='grid grid-cols-2 gap-4 mb-6'>
          <Table
            data={informasiUmum}
            columns={[
              {
                header: '',
                id: 'label',
                accessorKey: 'label',
              },
              {
                header: '',
                id: 'value',
                accessorKey: 'value',
              },
            ]}
            className={{
              headerRowClassName: 'hidden',
              paginationClassName: 'hidden',
              containerClassName: 'mb-0',
            }}
          />
          <Table
            data={informasiTransfer}
            columns={[
              {
                header: '',
                id: 'label',
                accessorKey: 'label',
              },
              {
                header: '',
                id: 'value',
                accessorKey: 'value',
              },
            ]}
            className={{
              headerRowClassName: 'hidden',
              paginationClassName: 'hidden',
              containerClassName: 'mb-0',
            }}
          />
        </div>
      </Card>

      <div className='flex flex-row gap-2 justify-end'>
        {FINANCE_TRANSACTION_STATUS.includes(finance.transaction_type || '') &&
          finance.party?.type !== 'SUPPLIER' && (
            <RequirePermission permissions='lti.finance.payments.update'>
              <Button
                color='warning'
                className='min-w-24'
                href={`/finance/detail/edit?financeId=${finance.id}`}
              >
                <Icon icon='mdi:pencil-outline' />
                Edit
              </Button>
            </RequirePermission>
          )}
        {FINANCE_INITIAL_BALANCE_STATUS.includes(
          finance.transaction_type || ''
        ) && (
          <RequirePermission permissions='lti.finance.initial_balances.update'>
            <Button
              color='warning'
              className='min-w-24'
              href={`/finance/detail/edit/initial-balance?financeId=${finance.id}`}
            >
              <Icon icon='mdi:pencil-outline' />
              Edit
            </Button>
          </RequirePermission>
        )}
        {FINANCE_INJECTION_STATUS.includes(finance.transaction_type || '') && (
          <RequirePermission permissions='lti.finance.injections.update'>
            <Button
              color='warning'
              className='min-w-24'
              href={`/finance/detail/edit/injection?financeId=${finance.id}`}
            >
              <Icon icon='mdi:pencil-outline' />
              Edit
            </Button>
          </RequirePermission>
        )}
        <RequirePermission permissions='lti.finance.transactions.delete'>
          <Button
            color='error'
            className='min-w-24'
            onClick={() => deleteModal.openModal()}
          >
            <Icon icon='mdi:delete-outline' />
            Delete
          </Button>
        </RequirePermission>
      </div>
      <ConfirmationModal
        ref={deleteModal.ref}
        type='error'
        text={`Apakah anda yakin ingin menghapus data Finance ini (${finance?.payment_code || ''})?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          isLoading: isDeleteLoading,
          onClick: confirmationModalDeleteClickHandler,
        }}
      />
    </div>
  );
};

export default FinanceDetail;
