import React from 'react';
import { groupOwnersByUnit, combineOwnerNames, collectAllAddresses } from '@/lib/ownerAddressUtils';
import { formatMailingAddress } from '@/lib/formatMailingAddress';
const SingleCouponComponent = ({ 
  clientName, 
  associationAddress, 
  owner, 
  coupon,
  index,
  totalCoupons
}) => {
  const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const parts = dateStr.split('-');
    if (parts.length === 3) return `${parts[1]}/${parts[2]}/${parts[0]}`;
    return new Date(dateStr).toLocaleDateString('en-US', {
      timeZone: 'America/New_York',
      month: '2-digit',
      day: '2-digit',
      year: 'numeric'
    });
  };

  const getMailingAddressLines = (owner) => {
    const { lines } = formatMailingAddress(owner);
    return lines.length > 0 ? lines : [''];
  };

  const getAssociationAddressLines = () => {
    if (associationAddress) {
      return associationAddress.split('\n').filter(line => line.trim() !== '');
    }
    return [];
  };

  const ownerName = owner.owner_name || `${owner.first_name || ''} ${owner.last_name || ''}`.trim();
  const ownerLines = getMailingAddressLines(owner);
  const assocLines = getAssociationAddressLines();

  return (
    <div 
      className="w-full relative bg-white text-black font-mono box-border" 
      style={{ 
        height: '3.66in',
        width: '8.5in',
        fontFamily: "'JetBrains Mono', monospace",
        pageBreakInside: 'avoid',
        borderBottom: index < totalCoupons - 1 ? '1px dashed #ccc' : 'none',
        position: 'relative',
        overflow: 'hidden'
      }}
    >
      {/* INSTRUCTION TEXT */}
      <div style={{ 
        position: 'absolute',
        top: '0.10in',
        left: '0.4in',
        right: '0.4in',
        textAlign: 'center'
      }}>
        <div className="text-[9px] text-muted-foreground leading-tight">
          Please return this portion with your payment and make your check payable to {clientName}
        </div>
      </div>

      {/* HEADER STRIP */}
      <div style={{
        position: 'absolute',
        top: '0.22in',
        left: '0.4in',
        right: '0.4in',
        height: '0.25in',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        borderBottom: '1px solid hsl(var(--border))',
        paddingBottom: '2px'
      }}>
        <div className="flex items-center gap-1.5 w-1/4">
          <span className="text-muted-foreground text-[9px] font-bold uppercase tracking-wide">PAYMENT NO.</span>
          <span className="bg-foreground text-background px-2 py-[0.1rem] text-[10px] min-w-[40px] text-center font-bold">
            {coupon.paymentNumber || ""}
          </span>
        </div>
        
        <div className="flex items-center justify-center gap-1.5 w-2/4 px-2 overflow-hidden">
          <span className="text-muted-foreground text-[9px] font-bold uppercase tracking-wide whitespace-nowrap">PROPERTY</span>
          <span className="bg-foreground text-background px-2 py-[0.1rem] text-[10px] text-center truncate w-full font-bold">
            {owner.property_address || ""}
          </span>
        </div>

        <div className="flex items-center justify-end gap-1.5 w-1/4">
          <span className="text-muted-foreground text-[9px] font-bold uppercase tracking-wide">ACCOUNT</span>
          <span className="bg-foreground text-background px-2 py-[0.1rem] text-[10px] min-w-[60px] text-center font-bold">
            {owner.units?.account_number || ""}
          </span>
        </div>
      </div>

      {/* RETURN ADDRESS */}
      <div style={{
        position: 'absolute',
        top: '0.75in',
        left: '0.4in',
        width: '3.5in'
      }}>
        <div className="text-[10px] font-bold uppercase leading-tight text-foreground">
          <div className="mb-0.5 text-[11px]">{clientName}</div>
          {assocLines.map((line, i) => (
            <div key={i}>{line}</div>
          ))}
        </div>
      </div>

      {/* PAYMENT TABLE */}
      <div style={{
        position: 'absolute',
        top: '0.75in',
        right: '0.4in',
        width: '2.0in'
      }}>
        <div className="border-[1.5px] border-foreground">
          <div className="flex">
            <div className="w-1/2 border-r-[1.5px] border-foreground flex flex-col">
              <div className="bg-muted text-center py-1 border-b-[1.5px] border-foreground">
                <span className="text-[9px] font-extrabold uppercase">DUE DATE</span>
              </div>
              <div className="py-2 text-center flex-1 flex items-center justify-center">
                <span className="text-[12px] font-bold">{formatDate(coupon.dueDate)}</span>
              </div>
            </div>
            <div className="w-1/2 flex flex-col">
              <div className="bg-muted text-center py-1 border-b-[1.5px] border-foreground">
                <span className="text-[9px] font-extrabold uppercase">AMOUNT DUE</span>
              </div>
              <div className="py-2 text-center flex-1 flex items-center justify-center">
                <span className="text-[13px] font-bold">{coupon.amount ? `$${Number(coupon.amount).toFixed(2)}` : ""}</span>
              </div>
            </div>
          </div>
        </div>

        <div className="text-right mt-2 px-1">
          <div className="text-[8px] font-bold text-muted-foreground mb-0.5">LATE FEES ACCRUE AFTER</div>
          <div className="text-[10px] font-bold">{formatDate(coupon.lateFeeDate)}</div>
        </div>

        <div className="flex items-end justify-end gap-1 mt-2">
          <span className="text-muted-foreground text-base mb-0.5 font-bold">$</span>
          {[1,2,3,4].map(i => (
            <div key={`d-${i}`} className="w-6 h-6 border border-border bg-background"></div>
          ))}
          <span className="text-muted-foreground text-xl mx-0.5 leading-none self-end mb-0.5 font-bold">.</span>
          {[1,2].map(i => (
            <div key={`c-${i}`} className="w-6 h-6 border border-border bg-background"></div>
          ))}
        </div>
      </div>

      {/* RECIPIENT ADDRESS */}
      <div style={{
        position: 'absolute',
        top: '2.5in',
        left: '0.6in',
        width: '4.0in'
      }}>
        <div className="text-[12px] font-bold uppercase leading-snug text-foreground">
          <div className="mb-1">{ownerName}</div>
          {ownerLines.map((line, i) => (
            <div key={i}>{line}</div>
          ))}
        </div>
      </div>
    </div>
  );
};

export function PaymentCouponHTMLPreview({ 
  selectedClientData, 
  selectedOwners, 
  couponData,
  associationAddress
}) {
  if (!selectedOwners || selectedOwners.length === 0) return null;

  // Group owners by unit to combine co-owner names & generate per address
  const unitGroups = groupOwnersByUnit(selectedOwners);
  const pages = [];

  for (const [, groupOwners] of unitGroups) {
    const combinedName = combineOwnerNames(groupOwners);
    const allAddresses = collectAllAddresses(groupOwners);
    const primaryOwner = groupOwners[0];

    // Create a merged "owner" object for each address copy
    for (const addrCopy of allAddresses) {
      const mergedOwner = {
        ...primaryOwner,
        owner_name: combinedName,
        mailing_address: addrCopy.address,
      };
      pages.push({ key: `${primaryOwner.id}-${addrCopy.label}`, owner: mergedOwner });
    }
  }

  return (
    <div className="w-full bg-muted p-8 flex flex-col items-center gap-8">
      {pages.map(({ key, owner }) => (
        <div 
          key={key} 
          className="coupon-pdf-page bg-background shadow-xl"
          style={{ 
            width: '8.5in', 
            height: '11in', 
            position: 'relative',
            pageBreakAfter: 'always'
          }}
        >
          {couponData.map((coupon, couponIdx) => (
            <SingleCouponComponent
              key={`${key}-${coupon.id}`}
              clientName={selectedClientData?.name || "ASSOCIATION NAME"}
              associationAddress={associationAddress} 
              owner={owner}
              coupon={coupon}
              index={couponIdx}
              totalCoupons={couponData.length}
            />
          ))}
        </div>
      ))}
    </div>
  );
}

export { SingleCouponComponent as SingleCoupon };
