'use client';

import React, { useMemo } from 'react';
import { ColumnDef } from '@tanstack/react-table';
import Table from '@/components/Table';
import Card from '@/components/Card';
import { formatCurrency } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { BaseExpeditionCost } from '@/types/api/closing';
import { ClosingApi } from '@/services/api/closing';
import { useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import HppExpeditionClosingSkeleton from '@/components/pages/closing/skeleton/HppExpeditionClosingSkeleton';

interface HppExpeditionClosingTableProps {
  projectFlockId: number;
}

const HppExpeditionClosingTable = ({
  projectFlockId,
}: HppExpeditionClosingTableProps) => {
  const searchParams = useSearchParams();
  const kandangId = searchParams.get('kandangId');

  const { data: hppExpedition, isLoading } = useSWR(
    kandangId
      ? `/closing/hpp-expedition/${projectFlockId}/${kandangId}`
      : `/closing/hpp-expedition/${projectFlockId}`,
    () =>
      kandangId
        ? ClosingApi.getHppEkspedisiByKandang(projectFlockId, Number(kandangId))
        : ClosingApi.getHppEkspedisi(projectFlockId)
  );

  const costOfRevenueExpeditionData: BaseExpeditionCost[] = useMemo(() => {
    if (isResponseSuccess(hppExpedition)) {
      return hppExpedition.data.expedition_costs || [];
    }
    return [];
  }, [hppExpedition]);

  const totals = useMemo(() => {
    if (isResponseSuccess(hppExpedition)) {
      return {
        totalHpp: hppExpedition.data.total_hpp_amount || 0,
      };
    }
    return {
      totalHpp: 0,
    };
  }, [hppExpedition]);

  const costOfRevenueExpeditionColumns: ColumnDef<BaseExpeditionCost>[] =
    useMemo(
      () => [
        {
          id: 'id',
          accessorKey: 'id',
          header: 'No',
          cell: (props) => {
            return <div>{props.row.index + 1}</div>;
          },
          footer: () => (
            <div className='font-semibold text-gray-900'>
              Total HPP Ekspedisi
            </div>
          ),
        },
        {
          id: 'expedition_vendor_name',
          accessorKey: 'expedition_vendor_name',
          header: 'Nama Ekspedisi',
          cell: (props) => props.getValue() || '-',
        },
        {
          id: 'hpp_amount',
          accessorKey: 'hpp_amount',
          header: 'HPP Ekspedisi',
          cell: (props) => {
            const value = props.getValue() as number;
            return <div className='text-right'>{formatCurrency(value)}</div>;
          },
          footer: () => (
            <div className='text-right font-semibold text-gray-900'>
              {formatCurrency(totals.totalHpp)}
            </div>
          ),
        },
      ],
      [totals]
    );

  return (
    <div className='w-full pt-3'>
      <Card
        className={{
          wrapper: 'w-full rounded-lg border-none',
          body: 'p-0',
          title: 'px-2 py-1.5 font-normal text-sm bg-primary text-white',
          collapsible: 'rounded-lg',
        }}
        variant='bordered'
        title='HPP Ekspedisi'
        collapsible
        defaultCollapsed={false}
      >
        {isLoading ? (
          <HppExpeditionClosingSkeleton
            columns={costOfRevenueExpeditionColumns}
          />
        ) : costOfRevenueExpeditionData.length === 0 ? (
          <HppExpeditionClosingSkeleton
            columns={costOfRevenueExpeditionColumns}
            iconName='heroicons:chart-bar'
          />
        ) : (
          <Table
            data={costOfRevenueExpeditionData}
            columns={costOfRevenueExpeditionColumns}
            isLoading={isLoading}
            renderFooter={costOfRevenueExpeditionData.length > 0}
            className={{
              containerClassName: 'w-full mb-0!',
              tableWrapperClassName:
                'overflow-x-auto rounded-tr-none rounded-tl-none',
              tableClassName: 'w-full table-auto text-sm',
              headerRowClassName: 'border-b border-b-gray-200 bg-gray-50',
              headerColumnClassName:
                'px-4 py-3 text-xs font-semibold text-gray-700 text-left border border-gray-200',
              bodyRowClassName:
                'hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200',
              bodyColumnClassName:
                'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
              tableFooterClassName:
                'bg-gray-100 font-semibold border border-gray-200',
              footerRowClassName: 'border-t-2 border-gray-300',
              footerColumnClassName:
                'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
            }}
          />
        )}
      </Card>
    </div>
  );
};

export default HppExpeditionClosingTable;
