import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
import Button from '@/components/Button';
import Card from '@/components/Card';
import { Icon } from '@iconify/react';
import { useRef, useMemo } from 'react';
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
import DeliveryOrderExport from '@/components/pages/marketing/pdf/DeliveryOrderExport';
import { Marketing } from '@/types/api/marketing/marketing';
import { Warehouse } from '@/types/api/master-data/warehouse';
import { DeliveryProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm.schema';

type DeliveryOrderProductTableProps = {
  data: DeliveryOrderProductFormValues[];
  formType?:
    | 'add'
    | 'edit'
    | 'add_deliver'
    | 'edit_deliver'
    | 'add_delivery'
    | 'edit_delivery'
    | 'detail'
    | 'rejected'
    | 'pending'
    | 'success'
    | string
    | null;
  marketing?: Marketing;
  onEdit: (id: number, values: DeliveryOrderProductFormValues) => void;
  onDelete: (id: number) => void;
  onAddProductClick: () => void;
};

const DeliveryOrderProductTable = ({
  data,
  formType,
  onEdit,
  onDelete,
  marketing,
}: DeliveryOrderProductTableProps) => {
  const onEditRef = useRef(onEdit);
  onEditRef.current = onEdit;
  const onDeleteRef = useRef(onDelete);
  onDeleteRef.current = onDelete;

  const approvalStepNumber = marketing?.latest_approval?.step_number;

  const hasDeliveryOrder = useMemo(() => {
    return (
      marketing?.delivery_order &&
      marketing.delivery_order.length > 0 &&
      marketing.delivery_order.some(
        (doItem) => doItem.deliveries && doItem.deliveries.length > 0
      )
    );
  }, [marketing?.delivery_order]);

  const deliveryItems = useMemo(() => {
    if (!hasDeliveryOrder) return [];

    return (
      marketing?.delivery_order?.flatMap((doItem) =>
        DeliveryProductToFieldValues(marketing?.sales_order, doItem).map(
          (delivery) => ({
            ...delivery,
            do_number: doItem.do_number,
            delivery_date: doItem.delivery_date,
            warehouse: doItem.warehouse,
          })
        )
      ) ?? []
    );
  }, [marketing?.delivery_order, hasDeliveryOrder]);

  const renderSalesOrderContent = (item: DeliveryOrderProductFormValues) => {
    const doItem = marketing?.delivery_order?.find(
      (doItem) => doItem.do_number === item.do_number
    );

    return (
      <>
        <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' &&
                (formType === 'add_delivery' ||
                  formType === 'edit_delivery' ||
                  formType === 'detail') && (
                  <div className='flex flex-row gap-1.5 items-center'>
                    <Button
                      type='button'
                      variant='ghost'
                      color='none'
                      onClick={() => {
                        onEditRef.current(item.id as number, item);
                      }}
                      className='p-0 hover:text-base-content'
                    >
                      <Icon icon='heroicons:pencil' width={20} height={20} />
                    </Button>
                  </div>
                )} */}
            </div>
          </th>
        </tr>
        <>
          <tr>
            <td className='text-sm px-4 py-3'>Gudang Fisik</td>
            <td className='text-sm px-4 py-3'>
              {doItem?.warehouse?.name ||
                item.marketing_product?.warehouse?.label ||
                item.marketing_product?.product_warehouse_data?.warehouse?.name}
            </td>
          </tr>
          <tr>
            <td className='text-sm px-4 py-3'>Produk</td>
            <td className='text-sm px-4 py-3'>
              {item.marketing_product?.product_warehouse?.label}
            </td>
          </tr>
          <tr>
            <td className='text-sm px-4 py-3'>Qty</td>
            <td className='text-sm px-4 py-3'>
              {item.qty !== undefined && item.qty !== null && item.qty !== ''
                ? `${formatNumber(parseFloat(item.qty as string))} ${item.marketing_product?.uom ?? ''}`
                : '-'}
            </td>
          </tr>
          {Number(item.avg_weight ?? 0) > 0 && (
            <tr>
              <td className='text-sm px-4 py-3'>Avg Bobot</td>
              <td className='text-sm px-4 py-3'>
                {formatNumber(Number(item.avg_weight))} Kg
              </td>
            </tr>
          )}
          {Number(item.total_weight ?? 0) > 0 && (
            <tr>
              <td className='text-sm px-4 py-3'>Total Bobot</td>
              <td className='text-sm px-4 py-3'>
                {formatNumber(Number(item.total_weight))} Kg
              </td>
            </tr>
          )}
          <tr>
            <td className='text-sm px-4 py-3'>
              Total Harga Satuan
              {item.convertion_unit?.label.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>
        </>
        <tr className='border-b border-t 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>
            </div>
          </th>
        </tr>
        <>
          {approvalStepNumber !== 1 && (
            <tr>
              <td className='text-sm px-4 py-3'>Tanggal Pengiriman</td>
              <td className='text-sm px-4 py-3'>
                {item.delivery_date ? (
                  formatDate(item.delivery_date, 'DD MMM YYYY')
                ) : formType === 'add_delivery' ||
                  formType === 'edit_delivery' ||
                  formType === 'detail' ? (
                  <span
                    className='text-error hover:text-error/70 cursor-pointer hover:underline underline-offset-4'
                    onClick={() => {
                      onEditRef.current(item.id as number, item);
                    }}
                  >
                    Belum diisi
                  </span>
                ) : (
                  <span className='text-error'>Belum diisi</span>
                )}
              </td>
            </tr>
          )}
          {item.do_number && (
            <tr>
              <td className='text-sm px-4 py-3'>No. Pengiriman</td>
              <td className='text-sm px-4 py-3'>{item.do_number}</td>
            </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>
          {doItem && (
            <tr>
              <td className='text-sm px-4 py-3'>Dokumen Pengiriman</td>
              <td className='text-sm px-4 py-3'>
                <DeliveryOrderExport data={marketing} deliveryOrder={doItem} />
              </td>
            </tr>
          )}
        </>
      </>
    );
  };

  const renderDeliveryOrderContent = (
    item: DeliveryOrderProductFormValues & {
      do_number: string;
      delivery_date: string;
      warehouse: Warehouse;
    }
  ) => {
    const parentDoItem = marketing?.delivery_order?.find(
      (doItem) => doItem.do_number === item.do_number
    );

    return (
      <>
        <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' &&
                (formType === 'add_delivery' ||
                  formType === 'edit_delivery' ||
                  formType === 'detail') && (
                  <div className='flex flex-row gap-1.5 items-center'>
                    <Button
                      type='button'
                      variant='ghost'
                      color='none'
                      onClick={() => {
                        onEditRef.current(item.id as number, item);
                      }}
                      className='p-0 hover:text-base-content'
                    >
                      <Icon icon='heroicons:pencil' width={20} height={20} />
                    </Button>
                  </div>
                )}
            </div>
          </th>
        </tr>
        <>
          <tr>
            <td className='text-sm px-4 py-3'>Gudang Fisik</td>
            <td className='text-sm px-4 py-3'>{item.warehouse?.name}</td>
          </tr>
          <tr>
            <td className='text-sm px-4 py-3'>Produk</td>
            <td className='text-sm px-4 py-3'>
              {item.marketing_product?.product_warehouse_data?.product.name}
            </td>
          </tr>
          <tr>
            <td className='text-sm px-4 py-3'>Qty</td>
            <td className='text-sm px-4 py-3'>
              {item.qty !== undefined && item.qty !== null && item.qty !== ''
                ? `${formatNumber(Number(item.qty))} ${item.marketing_product?.product_warehouse_data?.product.uom.name ?? ''}`
                : '-'}
            </td>
          </tr>
          {Number(item.avg_weight ?? 0) > 0 && (
            <tr>
              <td className='text-sm px-4 py-3'>Avg Bobot</td>
              <td className='text-sm px-4 py-3'>
                {formatNumber(Number(item.avg_weight))} Kg
              </td>
            </tr>
          )}
          {Number(item.total_weight ?? 0) > 0 && (
            <tr>
              <td className='text-sm px-4 py-3'>Total Bobot</td>
              <td className='text-sm px-4 py-3'>
                {formatNumber(Number(item.total_weight))}
              </td>
            </tr>
          )}
          <tr>
            <td className='text-sm px-4 py-3'>Total Harga Satuan</td>
            <td className='text-sm px-4 py-3'>
              {formatCurrency(Number(item.unit_price))}
            </td>
          </tr>
          <tr>
            <td className='text-sm px-4 py-3'>Total Penjualan</td>
            <td className='text-sm px-4 py-3'>
              {formatCurrency(Number(item.total_price))}
            </td>
          </tr>
        </>
        <tr className='border-b border-t 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>
            </div>
          </th>
        </tr>
        <>
          {approvalStepNumber !== 1 && (
            <tr>
              <td className='text-sm px-4 py-3'>Tanggal Pengiriman</td>
              <td className='text-sm px-4 py-3'>
                {item.delivery_date
                  ? formatDate(item.delivery_date, 'DD MMM YYYY')
                  : '-'}
              </td>
            </tr>
          )}
          {item.do_number && (
            <tr>
              <td className='text-sm px-4 py-3'>No. Pengiriman</td>
              <td className='text-sm px-4 py-3'>{item.do_number}</td>
            </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>
          {parentDoItem && (
            <tr>
              <td className='text-sm px-4 py-3'>Dokumen Pengiriman</td>
              <td className='text-sm px-4 py-3'>
                <DeliveryOrderExport
                  data={marketing}
                  deliveryOrder={parentDoItem}
                />
              </td>
            </tr>
          )}
        </>
      </>
    );
  };

  return (
    <>
      <div className='size-full flex flex-col relative overflow-x-hidden gap-3'>
        {hasDeliveryOrder
          ? deliveryItems.map((item, index) => (
              <div
                key={`do-table-${item.marketing_product?.product_warehouse?.value}-${index}`}
              >
                {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'>
                        {renderDeliveryOrderContent(item)}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <Card
                    key={`do-table-${item.marketing_product?.product_warehouse?.value}-${index}`}
                    title={
                      item.marketing_product?.product_warehouse_data?.product
                        .name || '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'>
                        {renderDeliveryOrderContent(item)}
                      </tbody>
                    </table>
                  </Card>
                )}
              </div>
            ))
          : 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'>
                        {renderSalesOrderContent(item)}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <Card
                    key={`table-${item.id}`}
                    title={
                      item.marketing_product?.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'>
                        {renderSalesOrderContent(item)}
                      </tbody>
                    </table>
                  </Card>
                )}
              </div>
            ))}
      </div>
    </>
  );
};

export default DeliveryOrderProductTable;
