import React from 'react';

// Define interfaces for data structure (optional but good practice)
interface CompanyInfo {
  name: string;
  address: string;
  gstin: string;
  pan: string;
  phone: string;
  email: string;
}

interface Address {
  name: string;
  address: string;
  gstin?: string; // Optional for Ship To
  state: string;
  stateCode: string;
}

interface InvoiceItem {
  id: number;
  description: string;
  hsnSac: string;
  quantity: number;
  rate: number;
  gstRate: number; // Combined GST rate (e.g., 18 for 18%)
}

interface InvoiceDetails {
  invoiceNo: string;
  invoiceDate: string;
  dueDate: string;
  ewayBillNo?: string;
  ewayBillDate?: string;
}

const GstInvoicePage: React.FC = () => {
  // Sample Data (replace with actual data or props in a real app)
  const companyInfo: CompanyInfo = {
    name: 'Innovate Solutions Pvt. Ltd.',
    address: '123 Tech Park, Silicon Valley, Bangalore, Karnataka - 560001',
    gstin: '29ABCDE1234F1Z5',
    pan: 'ABCDE1234F',
    phone: '+91-9876543210',
    email: 'accounts@innovatesolutions.com',
  };

  const billTo: Address = {
    name: 'Client Corp.',
    address: '456 Business Hub, MG Road, Gurgaon, Haryana - 122002',
    gstin: '06FGHJI5678K1Z9',
    state: 'Haryana',
    stateCode: '06',
  };

  const shipTo: Address = {
    name: 'Client Corp. - Warehouse',
    address: '789 Industrial Area, Sector 18, Gurgaon, Haryana - 122015',
    // gstin: '06FGHJI5678K1Z9', // Often same as Bill To, can be omitted if so
    state: 'Haryana',
    stateCode: '06',
  };

  const invoiceDetails: InvoiceDetails = {
    invoiceNo: 'INV-2024-07-00123',
    invoiceDate: '2024-07-28',
    dueDate: '2024-08-12',
    ewayBillNo: 'EWB123456789012',
    ewayBillDate: '2024-07-29',
  };

  const items: InvoiceItem[] = [
    { id: 1, description: 'Cloud Hosting Services - Pro Plan', hsnSac: '998315', quantity: 1, rate: 5000, gstRate: 18 },
    { id: 2, description: 'Domain Registration (.com)', hsnSac: '998319', quantity: 1, rate: 800, gstRate: 18 },
    { id: 3, description: 'Custom Software Development (Module A)', hsnSac: '998314', quantity: 50, rate: 150, gstRate: 18 },
    { id: 4, description: 'Technical Support Package (Annual)', hsnSac: '998316', quantity: 1, rate: 12000, gstRate: 18 },
  ];

  const paymentTerms = 'Payment due within 15 days of invoice date. Late fees of 2% per month apply.';
  const bankDetails = 'Bank: Example Bank | A/C No: 1234567890 | IFSC: EXBK0001234 | Branch: Main Branch';

  // Calculations
  let subtotal = 0;
  const calculatedItems = items.map(item => {
    const amount = item.quantity * item.rate;
    const gstAmount = (amount * item.gstRate) / 100;
    const total = amount + gstAmount;
    subtotal += amount;
    return { ...item, amount, gstAmount, total };
  });

  // Determine GST type (assuming intra-state if Bill To state code matches Company state code prefix)
  const isIntraState = billTo.stateCode === companyInfo.gstin.substring(0, 2);
  const cgstRate = isIntraState ? 9 : 0; // Example fixed rate, adjust if items have different rates
  const sgstRate = isIntraState ? 9 : 0;
  const igstRate = isIntraState ? 0 : 18;

  const totalGstAmount = calculatedItems.reduce((sum, item) => sum + item.gstAmount, 0);
  const grandTotal = subtotal + totalGstAmount;

  // Basic number to words conversion (can be replaced with a more robust library if needed)
  const numberToWords = (num: number): string => {
    // This is a very basic implementation - extend as needed
    const units = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
    const teens = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
    const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
    // Limited implementation for simplicity
    if (num < 10) return units[num];
    if (num < 20) return teens[num - 10];
    if (num < 100) return tens[Math.floor(num / 10)] + (num % 10 !== 0 ? ' ' + units[num % 10] : '');
    // Extend for hundreds, thousands etc. for a full solution
    return `Number ${num} (add full conversion logic)`; // Placeholder
  };
  const amountInWords = `${numberToWords(Math.floor(grandTotal))} Rupees Only`; // Basic version

  return (
    <div className="bg-gray-100 p-4 print:bg-white">
      <div className="max-w-4xl mx-auto bg-white p-8 border border-gray-300 shadow-lg print:border-none print:shadow-none">
        {/* Invoice Header */}
        <div className="flex justify-between items-start mb-8 pb-4 border-b border-gray-200">
          <div className="flex items-center">
            <div className="bg-gray-200 border-2 border-dashed rounded-xl w-16 h-16 mr-4 print:border-gray-400"></div>
            <div>
              <h1 className="text-2xl font-bold text-blue-700">{companyInfo.name}</h1>
              <p className="text-xs text-gray-600 max-w-xs">{companyInfo.address}</p>
              <p className="text-xs text-gray-600">GSTIN: {companyInfo.gstin} | PAN: {companyInfo.pan}</p>
              <p className="text-xs text-gray-600">Phone: {companyInfo.phone} | Email: {companyInfo.email}</p>
            </div>
          </div>
          <div className="text-right">
            <h2 className="text-xl font-semibold text-gray-700">Tax Invoice</h2>
            <p className="text-xs text-gray-500">Original for Recipient</p>
            <div className="mt-2">
                <p className="text-xs text-gray-600"><span className="font-semibold">Invoice No:</span> {invoiceDetails.invoiceNo}</p>
                <p className="text-xs text-gray-600"><span className="font-semibold">Invoice Date:</span> {invoiceDetails.invoiceDate}</p>
                <p className="text-xs text-gray-600"><span className="font-semibold">Due Date:</span> {invoiceDetails.dueDate}</p>
            </div>
          </div>
        </div>

        {/* Address and Details Section */}
        <div className="grid grid-cols-2 gap-8 mb-8">
          {/* Bill To / Ship To */}
          <div>
            <h3 className="text-sm font-semibold text-gray-700 mb-1">Bill To:</h3>
            <p className="text-sm font-bold text-gray-800">{billTo.name}</p>
            <p className="text-xs text-gray-600">{billTo.address}</p>
            <p className="text-xs text-gray-600">State: {billTo.state} (Code: {billTo.stateCode})</p>
            {billTo.gstin && <p className="text-xs text-gray-600">GSTIN: {billTo.gstin}</p>}
          </div>
          <div>
            <h3 className="text-sm font-semibold text-gray-700 mb-1">Ship To:</h3>
            <p className="text-sm font-bold text-gray-800">{shipTo.name}</p>
            <p className="text-xs text-gray-600">{shipTo.address}</p>
            <p className="text-xs text-gray-600">State: {shipTo.state} (Code: {shipTo.stateCode})</p>
             {/* Optionally show ShipTo GSTIN if different */}
             {shipTo.gstin && shipTo.gstin !== billTo.gstin && <p className="text-xs text-gray-600">GSTIN: {shipTo.gstin}</p>}
          </div>
          {/* E-way Bill Details */}
           {(invoiceDetails.ewayBillNo || invoiceDetails.ewayBillDate) && (
             <div className="col-span-2 mt-4 pt-4 border-t border-gray-200">
                <h3 className="text-sm font-semibold text-gray-700 mb-1">E-Way Bill Details:</h3>
                {invoiceDetails.ewayBillNo && <p className="text-xs text-gray-600"><span className="font-semibold">E-Way Bill No:</span> {invoiceDetails.ewayBillNo}</p>}
                {invoiceDetails.ewayBillDate && <p className="text-xs text-gray-600"><span className="font-semibold">E-Way Bill Date:</span> {invoiceDetails.ewayBillDate}</p>}
            </div>
           )}
        </div>

        {/* Items Table */}
        <div className="mb-8">
          <table className="w-full border-collapse text-sm">
            <thead>
              <tr className="bg-gray-100 print:bg-gray-200">
                <th className="border border-gray-300 p-2 text-left font-semibold text-gray-700 text-xs">S.No</th>
                <th className="border border-gray-300 p-2 text-left font-semibold text-gray-700 text-xs w-2/5">Description</th>
                <th className="border border-gray-300 p-2 text-left font-semibold text-gray-700 text-xs">HSN/SAC</th>
                <th className="border border-gray-300 p-2 text-right font-semibold text-gray-700 text-xs">Qty</th>
                <th className="border border-gray-300 p-2 text-right font-semibold text-gray-700 text-xs">Rate</th>
                <th className="border border-gray-300 p-2 text-right font-semibold text-gray-700 text-xs">Amount</th>
                <th className="border border-gray-300 p-2 text-center font-semibold text-gray-700 text-xs">GST Rate</th>
                <th className="border border-gray-300 p-2 text-right font-semibold text-gray-700 text-xs">GST Amt</th>
                <th className="border border-gray-300 p-2 text-right font-semibold text-gray-700 text-xs">Total</th>
              </tr>
            </thead>
            <tbody>
              {calculatedItems.map((item, index) => (
                <tr key={item.id} className="hover:bg-gray-50">
                  <td className="border border-gray-300 p-2 text-center text-xs">{index + 1}</td>
                  <td className="border border-gray-300 p-2 text-left text-xs">{item.description}</td>
                  <td className="border border-gray-300 p-2 text-left text-xs">{item.hsnSac}</td>
                  <td className="border border-gray-300 p-2 text-right text-xs">{item.quantity}</td>
                  <td className="border border-gray-300 p-2 text-right text-xs">{item.rate.toFixed(2)}</td>
                  <td className="border border-gray-300 p-2 text-right text-xs">{item.amount.toFixed(2)}</td>
                  <td className="border border-gray-300 p-2 text-center text-xs">{item.gstRate}%</td>
                  <td className="border border-gray-300 p-2 text-right text-xs">{item.gstAmount.toFixed(2)}</td>
                  <td className="border border-gray-300 p-2 text-right text-xs">{item.total.toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Totals Section */}
        <div className="flex justify-end mb-8">
          <div className="w-full md:w-1/2 lg:w-1/3">
            <div className="space-y-1 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-600">Subtotal:</span>
                <span className="font-medium text-gray-800">{subtotal.toFixed(2)}</span>
              </div>
              {isIntraState ? (
                <>
                  <div className="flex justify-between">
                    <span className="text-gray-600">CGST ({cgstRate}%):</span>
                    <span className="font-medium text-gray-800">{(totalGstAmount / 2).toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-600">SGST ({sgstRate}%):</span>
                    <span className="font-medium text-gray-800">{(totalGstAmount / 2).toFixed(2)}</span>
                  </div>
                </>
              ) : (
                <div className="flex justify-between">
                  <span className="text-gray-600">IGST ({igstRate}%):</span>
                  <span className="font-medium text-gray-800">{totalGstAmount.toFixed(2)}</span>
                </div>
              )}
              <div className="flex justify-between border-t border-gray-300 pt-2 mt-2">
                <span className="font-bold text-gray-900">Grand Total:</span>
                <span className="font-bold text-gray-900">₹ {grandTotal.toFixed(2)}</span>
              </div>
            </div>
          </div>
        </div>

         {/* Amount in Words */}
         <div className="mb-8 text-sm text-gray-700">
            <span className="font-semibold">Amount in Words: </span>
            <span className="capitalize">{amountInWords}</span>
        </div>

        {/* Payment Terms & Bank Details */}
        <div className="grid grid-cols-2 gap-8 mb-8 pt-4 border-t border-gray-200">
             <div>
                <h3 className="text-sm font-semibold text-gray-700 mb-1">Payment Terms:</h3>
                <p className="text-xs text-gray-600">{paymentTerms}</p>
            </div>
            <div>
                 <h3 className="text-sm font-semibold text-gray-700 mb-1">Bank Details:</h3>
                 <p className="text-xs text-gray-600">{bankDetails}</p>
                 {/* Placeholder for QR Code */}
                 <div className="mt-2">
                    <div className="bg-gray-200 border-2 border-dashed rounded-md w-20 h-20 inline-block align-middle mr-2"></div>
                    <span className="text-xs text-gray-500 align-middle">Scan QR for UPI Payment</span>
                 </div>
            </div>
        </div>


        {/* Footer - Terms & Signature */}
        <div className="mt-12 pt-6 border-t border-gray-300 text-xs text-gray-500">
          <div className="grid grid-cols-2 gap-4">
            <div>
                <h4 className="font-semibold text-gray-600 mb-1">Terms & Conditions:</h4>
                <ol className="list-decimal list-inside space-y-1">
                    <li>Goods once sold will not be taken back or exchanged.</li>
                    <li>Interest @18% p.a. will be charged on overdue bills.</li>
                    <li>All disputes are subject to Bangalore jurisdiction only.</li>
                </ol>
            </div>
            <div className="text-right">
                <h4 className="font-semibold text-gray-700">For {companyInfo.name}</h4>
                <div className="mt-16 h-10"> {/* Space for signature */}
                </div>
                <p className="border-t border-gray-400 pt-1">Authorised Signatory</p>
            </div>
          </div>
          <p className="text-center mt-8 text-gray-400 print:hidden">This is a computer-generated invoice and does not require a signature.</p>
        </div>
      </div>
    </div>
  );
};

export default GstInvoicePage; convert above gst invoice to php coding