'use client';

import { useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import { ClosingApi } from '@/services/api/closing';
import { isResponseSuccess } from '@/lib/api-helper';
import { formatNumber } from '@/lib/helper';
import ProductionDataClosingSkeleton from '@/components/pages/closing/skeleton/ProductionDataClosingSkeleton';
import Card from '@/components/Card';

interface ProductionDataClosingTabProps {
  projectFlockId: number;
}

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

  const { data: productionData, isLoading } = useSWR(
    `${ClosingApi.basePath}/${projectFlockId}/production-data?kandang_id=${kandangId ? `${kandangId}` : ''}`,
    () => ClosingApi.getProductionData(projectFlockId, Number(kandangId))
  );

  if (isLoading) {
    return <ProductionDataClosingSkeleton />;
  }

  if (!productionData || !isResponseSuccess(productionData)) {
    return (
      <ProductionDataClosingSkeleton
        iconName='heroicons:exclamation-circle'
        title='Gagal Memuat Data Produksi'
        subtitle='Terjadi kesalahan saat memuat data produksi. Silakan coba lagi.'
      />
    );
  }

  const { purchase, sales, performance } = productionData.data;

  // Helper for consistent row styling
  const DataRow = ({
    label,
    value,
    unit = '',
    valueClassName = 'font-bold text-gray-800',
    unitClassName = 'text-gray-500 w-12 text-right',
  }: {
    label: string;
    value: string | number;
    unit?: string;
    valueClassName?: string;
    unitClassName?: string;
  }) => (
    <div className='flex justify-between items-center py-1'>
      <span className='text-gray-500 text-sm font-medium w-1/2'>{label}</span>
      <div className='flex gap-2 w-1/2 justify-end items-center'>
        <span className={valueClassName}>{value}</span>
        {unit && <span className={unitClassName}>{unit}</span>}
      </div>
    </div>
  );

  return (
    <div className='w-full pt-3'>
      <Card
        className={{
          wrapper: 'w-full rounded-lg',
          body: 'p-0',
          title: 'px-2 py-1.5 font-normal text-sm bg-primary text-white',
          collapsible: 'rounded-lg',
        }}
        variant='bordered'
        title='Data Produksi'
        collapsible
        defaultCollapsed={false}
      >
        <div className='p-6'>
          <div className='grid grid-cols-1 lg:grid-cols-2 gap-x-24 gap-y-12 relative'>
            {/* Left Column */}
            <div className='space-y-10'>
              {/* Purchase Section */}
              <section>
                <h3 className='font-bold text-gray-700 mb-4 text-base'>
                  Pembelian
                </h3>
                <div className='space-y-1'>
                  <DataRow
                    label='Populasi Awal'
                    value={formatNumber(purchase.initial_population)}
                    unit='Ekor'
                  />
                  <DataRow
                    label='Claim Culling'
                    value={formatNumber(purchase.claim_culling)}
                    unit='Ekor'
                  />
                  <DataRow
                    label='Populasi Akhir'
                    value={formatNumber(purchase.final_population)}
                    unit='Ekor'
                  />
                  <DataRow
                    label='Pakan Masuk'
                    value={formatNumber(purchase.feed_in)}
                    unit='Kg'
                  />
                  <DataRow
                    label='Pakan Terpakai'
                    value={formatNumber(purchase.feed_used)}
                    unit='Kg'
                  />
                </div>
              </section>

              {/* Sales Section */}
              <section>
                <h3 className='font-bold text-gray-700 mb-4 text-base'>
                  Penjualan
                </h3>
                <div className='space-y-4'>
                  {/* Chicken Sales */}
                  <div className='space-y-1'>
                    <DataRow
                      label='Penjualan (Ekor)'
                      value={formatNumber(sales.chicken.sales_population)}
                      unit='Ekor'
                    />
                    <DataRow
                      label='Penjualan (Kg)'
                      value={formatNumber(sales.chicken.sales_weight)}
                      unit='Kg'
                    />
                    <DataRow
                      label='Bobot Rata-Rata'
                      value={formatNumber(sales.chicken.avg_weight)}
                      unit='Kg/Ekor'
                    />
                    <DataRow
                      label='Harga Jual Rata-Rata'
                      value={formatNumber(sales.chicken.avg_selling_price)}
                      unit='Rupiah'
                    />
                  </div>

                  {/* Egg Sales (if available) */}
                  {sales.egg && (
                    <>
                      <div className='h-px bg-gray-100 my-2' />
                      <div className='space-y-1'>
                        <DataRow
                          label='Telur (Butir)'
                          value={formatNumber(sales.egg.egg_pieces)}
                          unit='Butir'
                        />
                        <DataRow
                          label='Telur (Kg)'
                          value={formatNumber(sales.egg.egg_mass)}
                          unit='Kg'
                        />
                        <DataRow
                          label='Berat Telur Rata-Rata'
                          value={formatNumber(sales.egg.avg_egg_weight)}
                          unit='Kg'
                        />
                        <DataRow
                          label='Harga Jual Telur Rata-Rata'
                          value={formatNumber(sales.egg.avg_selling_price)}
                          unit='Rupiah'
                        />
                      </div>
                    </>
                  )}
                </div>
              </section>
            </div>

            {/* Divider Line (Absolute centered) */}
            <div className='hidden lg:block absolute left-1/2 top-0 bottom-0 w-px bg-gray-200 -translate-x-1/2' />

            {/* Right Column */}
            <div className='space-y-10 flex flex-col h-full'>
              {/* Performance Section */}
              <section>
                <h3 className='font-bold text-gray-700 mb-4 text-base'>
                  Performance
                </h3>
                <div className='space-y-1'>
                  <DataRow
                    label='Deplesi'
                    value={formatNumber(performance.depletion)}
                    unit='Ekor'
                  />
                  <DataRow
                    label='Umur'
                    value={formatNumber(performance.age_day)}
                    unit='Hari'
                  />
                  <DataRow
                    label='Mortalitas Std'
                    value={formatNumber(performance.mor_std)}
                    unitClassName='hidden'
                  />
                  <DataRow
                    label='Mortalitas Act'
                    value={formatNumber(performance.mor_act)}
                    unitClassName='hidden'
                  />
                  <DataRow
                    label='DEFF Mortalitas'
                    value={formatNumber(performance.mor_diff)}
                    unitClassName='hidden'
                  />
                  {/* <DataRow
                    label='AWG Std'
                    value={formatNumber(performance.awg_std)}
                    unit='Gr/Hari'
                  />
                  <DataRow
                    label='AWG Act'
                    value={formatNumber(performance.awg_act)}
                    unit='Gr/Hari'
                  /> */}
                  <DataRow
                    label='Feed Intake Std'
                    value={formatNumber(performance.feed_intake_std)}
                    unitClassName='hidden'
                  />
                  <DataRow
                    label='Feed Intake Act'
                    value={formatNumber(performance.feed_intake)}
                    unitClassName='hidden'
                  />
                  <DataRow
                    label='FCR Std'
                    value={formatNumber(performance.fcr_std)}
                    unitClassName='hidden'
                  />
                  <DataRow
                    label='FCR Act'
                    value={formatNumber(performance.fcr_act)}
                    unitClassName='hidden'
                  />
                  <DataRow
                    label='DEFF FCR'
                    value={formatNumber(performance.fcr_diff)}
                    unitClassName='hidden'
                  />

                  {/* Laying Specific Fields */}
                  {performance.hen_day_act !== undefined && (
                    <>
                      <DataRow
                        label='Hen Day Std'
                        value={formatNumber(performance.hen_day_std!)}
                        unit='%'
                      />
                      <DataRow
                        label='Hen Day Act'
                        value={formatNumber(performance.hen_day_act)}
                        unit='%'
                      />
                    </>
                  )}

                  {performance.egg_mass !== undefined && (
                    <>
                      <DataRow
                        label='Egg Mass Std'
                        value={formatNumber(performance.egg_mass_std!)}
                        unit='Kg'
                      />
                      <DataRow
                        label='Egg Mass Act'
                        value={formatNumber(performance.egg_mass)}
                        unit='Kg'
                      />
                    </>
                  )}

                  {performance.egg_weight !== undefined && (
                    <>
                      <DataRow
                        label='Egg Weight Std'
                        value={formatNumber(performance.egg_weight_std!)}
                        unit='Gr'
                      />
                      <DataRow
                        label='Egg Weight Act'
                        value={formatNumber(performance.egg_weight)}
                        unit='Gr'
                      />
                    </>
                  )}

                  {performance.hen_housed_act !== undefined && (
                    <>
                      <DataRow
                        label='Hen Housed Std'
                        value={formatNumber(performance.hen_housed_std!)}
                        unit='%'
                      />
                      <DataRow
                        label='Hen Housed Act'
                        value={formatNumber(performance.hen_housed_act)}
                        unit='%'
                      />
                    </>
                  )}
                </div>
              </section>
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
};

export default ProductionDataClosingTab;
