'use client';

import Button from '@/components/Button';
import Card from '@/components/Card';
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
import { formatCurrency, formatNumber } from '@/lib/helper';
import { Icon } from '@iconify/react';
import { useRef } from 'react';

type SalesOrderProductTableProps = {
  data: SalesOrderProductFormValues[];
  formType: 'add' | 'edit' | 'add_deliver' | 'edit_deliver' | 'success';
  onDelete: (id: number) => void;
  onEdit: (id: number) => void;
  onAddProductClick: () => void;
};

const SalesOrderProductTable = ({
  data,
  formType,
  onDelete,
  onEdit,
  onAddProductClick,
}: SalesOrderProductTableProps) => {
  const onDeleteRef = useRef(onDelete);
  onDeleteRef.current = onDelete;
  const onEditRef = useRef(onEdit);
  onEditRef.current = onEdit;

  const renderTableContent = (item: SalesOrderProductFormValues) => (
    <>
      <tr className='border-b border-tools-table-outline border-base-content/5'>
        <th className='w-1/3 text-start not-first:font-medium text-base-content/50 text-sm px-4 py-3'>
          Label
        </th>
        <th className='text-start font-medium text-base-content/50 text-sm px-4 py-3'>
          <div className='flex w-full flex-row gap-1 items-center justify-between h-full'>
            <div>Value</div>
            {formType !== 'success' && (
              <div className='flex flex-row gap-1.5 items-center'>
                <Button
                  type='button'
                  variant='ghost'
                  color='none'
                  onClick={() => {
                    onEditRef.current(item.id as number);
                  }}
                  className='p-0 hover:text-base-content'
                >
                  <Icon icon='heroicons:pencil' width={20} height={20} />
                </Button>
                {data.length > 1 && (
                  <Button
                    type='button'
                    variant='ghost'
                    color='none'
                    onClick={() => {
                      onDeleteRef.current(item.id as number);
                    }}
                    className='p-0 text-error hover:text-base-content'
                  >
                    <Icon icon='heroicons:trash' width={20} height={20} />
                  </Button>
                )}
              </div>
            )}
          </div>
        </th>
      </tr>
      <>
        <tr>
          <td className='text-sm px-4 py-3'>No. Polisi</td>
          <td className='text-sm px-4 py-3'>{item.vehicle_number}</td>
        </tr>
        <tr>
          <td className='text-sm px-4 py-3'>Gudang Fisik</td>
          <td className='text-sm px-4 py-3'>
            {item.warehouse?.label ?? item.kandang?.label}
          </td>
        </tr>
        <tr>
          <td className='text-sm px-4 py-3'>Kategori</td>
          <td className='text-sm px-4 py-3'>{item.marketing_type?.label}</td>
        </tr>
        <tr>
          <td className='text-sm px-4 py-3'>Produk</td>
          <td className='text-sm px-4 py-3'>{item.product_warehouse?.label}</td>
        </tr>
        {item.marketing_type?.value.toLowerCase() === 'telur' && (
          <tr>
            <td className='text-sm px-4 py-3'>Tipe Konversi</td>
            <td className='text-sm px-4 py-3'>{item.convertion_unit?.label}</td>
          </tr>
        )}
        {item.marketing_type?.value.toLowerCase() === 'ayam_pullet' && (
          <tr>
            <td className='text-sm px-4 py-3'>Tipe Konversi</td>
            <td className='text-sm px-4 py-3'>Week {item.week}</td>
          </tr>
        )}
        {item.convertion_unit?.value.toLowerCase() === 'peti' && (
          <tr>
            <td className='text-sm px-4 py-3'>Total Peti</td>
            <td className='text-sm px-4 py-3'>
              {item.total_peti} {item.convertion_unit?.label}
            </td>
          </tr>
        )}
        {item.marketing_type?.value.toLowerCase() !== 'trading' && (
          <>
            <tr>
              <td className='text-sm px-4 py-3'>Total Bobot</td>
              <td className='text-sm px-4 py-3'>
                {item.total_weight
                  ? formatNumber(parseFloat(item.total_weight as string)) +
                    ' Kg'
                  : '0 Kg'}
              </td>
            </tr>
            <tr>
              <td className='text-sm px-4 py-3'>Avg Bobot</td>
              <td className='text-sm px-4 py-3'>
                {item.avg_weight
                  ? formatNumber(parseFloat(item.avg_weight as string)) + ' Kg'
                  : '0 Kg'}
              </td>
            </tr>
          </>
        )}
        <tr>
          <td className='text-sm px-4 py-3'>
            {item.marketing_type?.value === 'telur'
              ? 'Total Butir Telur'
              : 'Qty'}
          </td>
          <td className='text-sm px-4 py-3'>
            {`${formatNumber(parseFloat(item.qty as string))} ${item.uom || ''}`}
          </td>
        </tr>
        {item.convertion_unit?.value.toLowerCase() === 'peti' && (
          <tr>
            <td className='text-sm px-4 py-3'>Harga Satuan Per Peti</td>
            <td className='text-sm px-4 py-3'>
              {formatCurrency(
                parseFloat(item.unit_price as string) *
                  parseFloat(String(item.weight_per_convertion))
              )}
            </td>
          </tr>
        )}
        <tr>
          <td className='text-sm px-4 py-3'>
            Harga Satuan
            {item.convertion_unit?.value.toLowerCase() === 'peti' && ' (Kg)'}
          </td>
          <td className='text-sm px-4 py-3'>
            {formatCurrency(parseFloat(item.unit_price as string))}
          </td>
        </tr>
        <tr>
          <td className='text-sm px-4 py-3'>Total Penjualan</td>
          <td className='text-sm px-4 py-3'>
            {formatCurrency(parseFloat(item.total_price as string))}
          </td>
        </tr>
      </>
    </>
  );

  return (
    <>
      <div className='size-full flex flex-col relative overflow-x-hidden gap-3'>
        {data.map((item) => (
          <div key={`table-${item.id}`}>
            {formType === 'success' ? (
              <div className='rounded-lg border border-tools-table-outline border-base-content/5'>
                <table
                  style={{
                    borderRadius: '0.5rem',
                  }}
                  className='border-none w-full'
                >
                  <tbody className='w-full'>{renderTableContent(item)}</tbody>
                </table>
              </div>
            ) : (
              <Card
                title={item.product_warehouse?.label || 'Produk'}
                collapsible={true}
                defaultCollapsed={false}
                variant='bordered'
                className={{
                  wrapper: 'w-full rounded-lg',
                  body: 'p-0',
                  title: 'px-2 py-1.5 font-normal text-sm',
                  collapsible: 'rounded-lg',
                }}
              >
                <table
                  style={{
                    borderRadius: '0.5rem',
                  }}
                  className='border-none w-full'
                >
                  <tbody className='w-full'>{renderTableContent(item)}</tbody>
                </table>
              </Card>
            )}
          </div>
        ))}
        {formType != 'add_deliver' &&
          formType != 'edit_deliver' &&
          formType != 'success' && (
            <Button
              type='button'
              variant='outline'
              className='justify-center p-3 w-full rounded-lg text-center text-sm mt-3'
              onClick={onAddProductClick}
            >
              Tambah Produk
            </Button>
          )}
      </div>
    </>
  );
};

export default SalesOrderProductTable;
