'use client';

import React, { useEffect } from 'react';
import type { Order, ShopProfile } from '@/lib/data';
import Image from 'next/image';

type InvoiceProps = {
  order: Order;
  profile: ShopProfile;
  onPrintComplete: () => void;
};

export function Invoice({ order, profile, onPrintComplete }: InvoiceProps) {
  const totalAmount = order.totalAmount || 0;
  const paidAmount = order.paidAmount || 0;
  const dueAmount = totalAmount - paidAmount;

  useEffect(() => {
    const handleAfterPrint = () => {
      onPrintComplete();
      window.removeEventListener('afterprint', handleAfterPrint);
    };
    
    window.addEventListener('afterprint', handleAfterPrint);

    return () => {
      window.removeEventListener('afterprint', handleAfterPrint);
    };
  }, [onPrintComplete]);


  return (
    <div className="bg-background text-foreground font-sans text-sm p-4 sm:p-8 print:p-0">
      <style jsx global>{`
        @media print {
          body * {
            visibility: hidden;
          }
          .invoice-section, .invoice-section * {
            visibility: visible;
          }
          .invoice-section {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            padding: 2rem;
          }
          .no-print {
            display: none;
          }
        }
      `}</style>

      <div className="max-w-4xl mx-auto bg-card p-6 sm:p-10 rounded-lg shadow-sm border border-border invoice-section">
        <header className="flex justify-between items-start pb-6 border-b border-border">
          <div className="flex items-center gap-4">
            {profile.logoUrl && (
              <Image
                src={profile.logoUrl}
                alt={`${profile.shopName} Logo`}
                width={64}
                height={64}
                className="rounded-lg object-cover"
              />
            )}
            <div>
              <h1 className="text-2xl font-bold font-headline text-primary">{profile.shopName}</h1>
              <p className="text-muted-foreground">{profile.address}</p>
              <p className="text-muted-foreground">{profile.email} | {profile.contact}</p>
            </div>
          </div>
          <div className="text-right">
            <h2 className="text-xl font-semibold text-primary">INVOICE</h2>
            <p className="text-muted-foreground">Order ID: #{order.id}</p>
            {order.memoId && <p className="text-muted-foreground">Memo ID: #{order.memoId}</p>}
            <p className="text-muted-foreground">Date: {new Date(order.date).toLocaleDateString()}</p>
          </div>
        </header>

        <section className="grid grid-cols-1 sm:grid-cols-2 gap-8 my-8">
          <div>
            <h3 className="font-semibold mb-2 text-primary">Bill To:</h3>
            <p className="font-medium">{order.customer}</p>
            <p className="text-muted-foreground">{order.phone}</p>
          </div>
          <div className="sm:text-right">
             <h3 className="font-semibold mb-2 text-primary">Delivery Date:</h3>
             <p>{order.deliveryDate ? new Date(order.deliveryDate).toLocaleDateString() : 'Not set'}</p>
          </div>
        </section>

        <section>
          <table className="w-full text-left">
            <thead className="bg-muted/50">
              <tr>
                <th className="p-3 font-semibold">Item</th>
                <th className="p-3 font-semibold text-center">Quantity</th>
                <th className="p-3 font-semibold text-right">Price</th>
                <th className="p-3 font-semibold text-right">Total</th>
              </tr>
            </thead>
            <tbody>
              {order.items.map(item => (
                <tr key={item.id} className="border-b border-border">
                  <td className="p-3">
                      <p className="font-medium">{item.name}</p>
                      {item.measurements && <p className="text-xs text-muted-foreground">{item.measurements}</p>}
                  </td>
                  <td className="p-3 text-center">{item.quantity}</td>
                  <td className="p-3 text-right">৳{item.price.toFixed(2)}</td>
                  <td className="p-3 text-right">৳{(item.price * item.quantity).toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>

        <section className="flex justify-end mt-8">
          <div className="w-full max-w-xs space-y-2">
            <div className="flex justify-between">
              <span className="text-muted-foreground">Subtotal</span>
              <span className="font-medium">৳{order.totalAmount.toFixed(2)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">Paid Amount</span>
              <span className="font-medium text-green-600">৳{order.paidAmount.toFixed(2)}</span>
            </div>
            <div className="border-t border-border my-2"></div>
            <div className="flex justify-between font-bold text-lg text-primary">
              <span>Due Amount</span>
              <span>৳{dueAmount.toFixed(2)}</span>
            </div>
          </div>
        </section>

        <footer className="mt-12 pt-6 border-t border-border text-center text-muted-foreground text-xs">
          <p>Thank you for your business!</p>
          <p>Please contact us with any questions regarding this invoice.</p>
        </footer>
      </div>
    </div>
  );
}
