import Button from '@/components/Button';
import { BaseDeliveryOrder, Marketing } from '@/types/api/marketing/marketing';
import { Icon } from '@iconify/react';
import { Document, Page, pdf, Text, View } from '@react-pdf/renderer';
import { useMemo, useState } from 'react';
import { formatDate, formatNumber, formatVechicleNumber } from '@/lib/helper';
import pdfStyles from '@/components/pages/marketing/pdf/styles/MarketingPDFStyles';
import toast from 'react-hot-toast';
import { useSearchParams } from 'next/navigation';

interface DeliveryOrderExportProps {
  data?: Marketing;
  deliveryOrder: BaseDeliveryOrder;
  className?: string;
}

const DeliveryOrderExport = ({
  data,
  deliveryOrder,
}: DeliveryOrderExportProps) => {
  const [isGeneratingPDF, setIsGeneratingPDF] = useState(false);
  const salesData = data;
  const searchParams = useSearchParams();
  const action = searchParams.get('action');
  const id = searchParams.get('id');

  const handleDownloadPDF = async () => {
    if (!salesData) {
      toast.error('No sales order data available');
      return;
    }
    setIsGeneratingPDF(true);
    try {
      const blob = await pdf(
        <PDFDocument data={salesData} deliveryOrder={deliveryOrder} />
      ).toBlob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.download = `${deliveryOrder?.do_number || 'delivery-order'}.pdf`;
      link.setAttribute('target', '_blank');
      link.setAttribute('rel', 'noopener noreferrer');
      document.body.appendChild(link);
      link.click();

      // Delay cleanup to ensure download starts
      setTimeout(() => {
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      }, 150);
    } catch {
      toast.error('Failed to generate PDF. Please try again.');
    } finally {
      setIsGeneratingPDF(false);
      window.location.href = `/marketing?action=${action}&id=${id}`;
    }
  };

  if (!salesData) {
    return (
      <div className='flex items-start justify-start'>
        <div className='text-gray-500'>No sales order data available</div>
      </div>
    );
  }

  return deliveryOrder?.do_number ? (
    <Button
      variant='outline'
      color='none'
      className='w-fit text-sm px-3 py-2.5 rounded-lg border-base-content/10 text-base-content/50'
      onClick={handleDownloadPDF}
      isLoading={isGeneratingPDF}
      type='button'
    >
      <Icon icon='heroicons:document-text' width={20} height={20} />
      {deliveryOrder.do_number}
    </Button>
  ) : null;
};

export default DeliveryOrderExport;
const PDFDocument = ({
  data,
  deliveryOrder,
}: {
  data: Marketing;
  deliveryOrder: BaseDeliveryOrder;
}) => {
  const grandTotal = useMemo(() => {
    return (
      deliveryOrder.deliveries?.reduce((a, b) => a + b.total_price, 0) ?? 0
    );
  }, []);

  return (
    <Document>
      <Page size='A4' style={pdfStyles.page}>
        {/* Header Section */}
        <View style={pdfStyles.header}>
          <Text style={pdfStyles.companyInfo}>PT LUMBUNG TELUR INDONESIA</Text>
          <Text style={pdfStyles.address}>
            Setra Duta Raya No.L3 No.7, Ciwaruga, Kec. Parongpong, Kabupaten
            Bandung Barat, Jawa Barat 40514
          </Text>
          <View style={pdfStyles.divider} />
        </View>

        {/* Delivery Order Title */}
        <View style={pdfStyles.titleSection}>
          <Text style={pdfStyles.title}>DELIVERY ORDER</Text>
          <View style={pdfStyles.poInfo}>
            <Text>{deliveryOrder.do_number || '-'}</Text>
          </View>
        </View>

        {/* Depature Table */}
        <View style={pdfStyles.table}>
          <View style={[pdfStyles.tableRow, pdfStyles.tableHeader]}>
            <View style={pdfStyles.tableCellHeader}>
              <Text>Ship To</Text>
            </View>
            <View style={pdfStyles.tableCellHeaderLast}>
              <Text>Depature From</Text>
            </View>
          </View>
          <View style={pdfStyles.tableRow}>
            <View style={pdfStyles.tableCell}>
              <Text style={{ fontWeight: 'bold' }}>
                {data?.customer?.name || '-'} ({data?.customer?.type || '-'})
              </Text>
              <Text style={{ marginTop: '2px' }}>
                {data?.customer.email || ''} - {data?.customer.phone || ''}
              </Text>
              <Text></Text>
              <Text>{data?.customer.address || ''}</Text>
              <Text style={{ fontSize: '7px', marginTop: '3px' }}></Text>
            </View>
            <View style={pdfStyles.tableCellLast}>
              <Text style={{ fontWeight: 'bold' }}>
                {deliveryOrder.warehouse?.name || '-'}
              </Text>
              <Text style={{ marginTop: '2px' }}>
                {formatDate(deliveryOrder.delivery_date, 'DD MMM YYYY')}
              </Text>
              <Text>{deliveryOrder.warehouse?.area?.name}</Text>
            </View>
          </View>
        </View>

        {/* Delivery Table */}
        <Text style={pdfStyles.sectionTitle}>Product Shipped</Text>
        <View style={pdfStyles.table}>
          <View style={[pdfStyles.tableRow, pdfStyles.tableHeader]}>
            <View style={pdfStyles.tableCellHeader}>
              <Text>Item Description</Text>
            </View>
            <View style={pdfStyles.tableCellHeader}>
              <Text>Vehicle Number</Text>
            </View>
            <View style={pdfStyles.tableCellHeader}>
              <Text>Unit Price</Text>
            </View>
            <View style={pdfStyles.tableCellHeader}>
              <Text>Quantity</Text>
            </View>
            <View style={pdfStyles.tableCellHeaderLast}>
              <Text>Total Amount</Text>
            </View>
          </View>
          {deliveryOrder.deliveries?.map((item, index) => {
            return (
              <View key={index} style={[pdfStyles.tableRow]}>
                <View style={pdfStyles.tableCell}>
                  <Text>{item.product_warehouse?.product?.name || '-'}</Text>
                </View>
                <View style={pdfStyles.tableCell}>
                  <Text>
                    {formatVechicleNumber(item.vehicle_number) || '-'}
                  </Text>
                </View>
                <View style={pdfStyles.tableCellRight}>
                  <Text>Rp{formatNumber(item.unit_price || 0)}</Text>
                </View>
                <View style={pdfStyles.tableCellRight}>
                  <Text>{formatNumber(item.qty || 0)}</Text>
                </View>
                <View style={pdfStyles.tableCellRightLast}>
                  <Text>Rp{formatNumber(item.total_price || 0)}</Text>
                </View>
              </View>
            );
          }) || []}

          {/* Grand Total Row inside table */}
          <View style={pdfStyles.grandTotalRow}>
            <View style={[pdfStyles.tableCell, { borderRightWidth: 0 }]}>
              <Text></Text>
            </View>
            <View style={[pdfStyles.tableCell, { borderRightWidth: 0 }]}>
              <Text></Text>
            </View>
            <View style={[pdfStyles.tableCellRight, { borderRightWidth: 0 }]}>
              <Text></Text>
            </View>
            <View style={pdfStyles.tableCellRight}>
              <Text style={{ fontWeight: 'bold' }}>Grand Total</Text>
            </View>
            <View
              style={[pdfStyles.tableCellRightLast, { fontWeight: 'bold' }]}
            >
              <Text>Rp{formatNumber(grandTotal)}</Text>
            </View>
          </View>
        </View>

        {/* Footer with Special Instructions */}
        <View style={pdfStyles.footer}>
          <View style={pdfStyles.specialInstructionTable}>
            <View style={[pdfStyles.tableRow, pdfStyles.tableHeader]}>
              <View style={pdfStyles.tableCellHeaderLast}>
                <Text>From Sales Order</Text>
              </View>
            </View>
            <View style={pdfStyles.tableRow}>
              <View style={pdfStyles.tableCellLast}>
                <Text>
                  {data?.so_number || '-'} -{' '}
                  {formatDate(data.so_date, 'DD MMM YYYY')}
                </Text>
              </View>
            </View>
          </View>
          <View style={pdfStyles.footerCompany}>
            <Text>PT LUMBUNG TELUR INDONESIA</Text>
          </View>
        </View>
      </Page>
    </Document>
  );
};
