import React, { ReactElement, useEffect, useState } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import axios from 'axios';
import LayoutAuthenticated from '../../../layouts/Authenticated';
import { getPageTitle } from '../../../config';
import SectionMain from '../../../components/SectionMain';
import CardBox from '../../../components/CardBox';
import BaseButton from '../../../components/BaseButton';
import { mdiPrinter, mdiArrowLeft } from '@mdi/js';
import LoadingSpinner from '../../../components/LoadingSpinner';

const ErcaVatForm = () => {
  const router = useRouter();
  const { vat_declarationsId } = router.query;
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (vat_declarationsId) {
      axios.get(`/vat_declarations/${vat_declarationsId}/erca-data`)
        .then(res => {
          setData(res.data);
          setLoading(false);
        })
        .catch(err => {
          console.error(err);
          setLoading(false);
        });
    }
  }, [vat_declarationsId]);

  if (loading) return <LoadingSpinner />;
  if (!data) return <div className="p-6 text-center text-red-500">Data not found</div>;

  const { sectionA, sectionB, merchant, tax_period } = data;

  const formatCurrency = (val: number) => {
    return new Intl.NumberFormat('en-ET', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(val || 0);
  };

  const handlePrint = () => {
    window.print();
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('ERCA VAT Declaration')}</title>
      </Head>
      <SectionMain>
        <div className="flex justify-between items-center mb-6 no-print">
          <BaseButton
            label="Back"
            icon={mdiArrowLeft}
            onClick={() => router.back()}
          />
          <BaseButton
            label="Print Form"
            color="info"
            icon={mdiPrinter}
            onClick={handlePrint}
          />
        </div>

        <CardBox className="print:shadow-none print:border-none">
          <div className="p-8 font-sans text-sm text-black bg-white">
            {/* Header Section */}
            <div className="text-center mb-8">
              <h1 className="text-2xl font-bold mb-2">የፌዴራል ታክስ ባለስልጣን</h1>
              <h1 className="text-2xl font-bold mb-2">FEDERAL TAX AUTHORITY</h1>
              <h2 className="text-xl font-bold mb-4 underline">የተጨማሪ እሴት ታክስ ማስታወቂያ (VAT DECLARATION)</h2>
            </div>

            {/* Merchant Info */}
            <div className="grid grid-cols-2 gap-4 mb-6 border-b pb-4">
              <div>
                <p><strong>የግብር ከፋይ ስም:</strong> {merchant?.legal_name || merchant?.business_name}</p>
                <p><strong>Taxpayer Name:</strong> {merchant?.legal_name || merchant?.business_name}</p>
              </div>
              <div>
                <p><strong>የግብር ከፋይ መለያ ቁጥር:</strong> {merchant?.tin_number}</p>
                <p><strong>TIN Number:</strong> {merchant?.tin_number}</p>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4 mb-8">
              <div>
                <p><strong>ለታክስ የተፈለገበት ወቅት:</strong> {tax_period?.year_number} / {tax_period?.period_number}</p>
                <p><strong>Tax Period:</strong> {tax_period?.year_number} / {tax_period?.period_number}</p>
              </div>
            </div>

            {/* Section A - Computation of Output Tax */}
            <div className="mb-8">
              <h3 className="bg-gray-200 p-2 font-bold border border-black">ሀ. የሽያጭ ታክስ ስሌት (SECTION A — COMPUTATION OF OUTPUT TAX)</h3>
              <table className="w-full border-collapse border border-black text-xs">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="border border-black p-1 w-12 text-center">Line No</th>
                    <th className="border border-black p-2 text-left">መግለጫ (Description)</th>
                    <th className="border border-black p-2 text-right w-32">ጠቅላላ መጠን (Total Amount)</th>
                    <th className="border border-black p-2 text-right w-32">የታክስ መጠን (VAT Amount)</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td className="border border-black p-1 text-center font-bold">5</td>
                    <td className="border border-black p-2">ታክስ የሚከፈልበት አገልግሎት አቅርቦት / ሽያጭ (Taxable Sales / Supplies)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionA.line5.total)}</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionA.line5.vat)}</td>
                  </tr>
                  <tr>
                    <td className="border border-black p-1 text-center font-bold">15</td>
                    <td className="border border-black p-2">ዜሮ ምጣኔ ያላቸው ሽያጭ (Zero-rated Sales / Supplies)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionA.line15.total)}</td>
                    <td className="border border-black p-2 bg-gray-100"></td>
                  </tr>
                  <tr>
                    <td className="border border-black p-1 text-center font-bold">20</td>
                    <td className="border border-black p-2">ከታክስ ነፃ የሆነ ሽያጭ (Tax-exempt Sales / Supplies)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionA.line20.total)}</td>
                    <td className="border border-black p-2 bg-gray-100"></td>
                  </tr>
                  <tr>
                    <td className="border border-black p-1 text-center font-bold">25</td>
                    <td className="border border-black p-2">በገዢው ተይዞ የተሰበሰበ ሽያጭ (Services or Supplies subject to Reverse Taxation)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionA.line25.total)}</td>
                    <td className="border border-black p-2 bg-gray-100"></td>
                  </tr>
                  <tr>
                    <td className="border border-black p-1 text-center font-bold">35</td>
                    <td className="border border-black p-2">ታክስ የተስተካከለበት ዴቢት ሰነድ (አቅራቢ) (Tax adjustment with debit note for suppliers)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionA.line35.total)}</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionA.line35.vat)}</td>
                  </tr>
                  <tr>
                    <td className="border border-black p-1 text-center font-bold">45</td>
                    <td className="border border-black p-2">ታክስ የተስተካከለበት ክሬዲት ሰነድ (አቅራቢ) (Tax adjustment with credit note for suppliers)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionA.line45.total)}</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionA.line45.vat)}</td>
                  </tr>
                  <tr className="font-bold bg-gray-50">
                    <td className="border border-black p-1 text-center">55</td>
                    <td className="border border-black p-2 uppercase">ጠቅላላ አቅርቦት / ሽያጭ (Total Sales / Supplies) (5 + 15 + 20 + 25 + 35 − 45)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionA.line55.total)}</td>
                    <td className="border border-black p-2 bg-gray-200"></td>
                  </tr>
                  <tr className="font-bold bg-gray-50">
                    <td className="border border-black p-1 text-center">60</td>
                    <td className="border border-black p-2 uppercase">ጠቅላላ የሽያጭ ታክስ (Total Output VAT)</td>
                    <td className="border border-black p-2 bg-gray-200"></td>
                    <td className="border border-black p-2 text-right border-double">{formatCurrency(sectionA.line60.vat)}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            {/* Section B - Capital Asset Purchases */}
            <div className="mb-8">
              <h3 className="bg-gray-200 p-2 font-bold border border-black">ለ. የካፒታል ዕቃዎች ግዢ (SECTION B — CAPITAL ASSET PURCHASES)</h3>
              <table className="w-full border-collapse border border-black text-xs">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="border border-black p-1 w-12 text-center">Line No</th>
                    <th className="border border-black p-2 text-left">መግለጫ (Description)</th>
                    <th className="border border-black p-2 text-right w-32">ጠቅላላ መጠን (Total Amount)</th>
                    <th className="border border-black p-2 text-right w-32">የታክስ መጠን (VAT Amount)</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td className="border border-black p-1 text-center font-bold">65</td>
                    <td className="border border-black p-2">የአገር ውስጥ ካፒታል ዕቃ ግዢ (Local Purchase of Capital Assets)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionB.line65.total)}</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionB.line65.vat)}</td>
                  </tr>
                  <tr>
                    <td className="border border-black p-1 text-center font-bold">75</td>
                    <td className="border border-black p-2">የውጪ አገር ካፒታል ዕቃ ግዢ (Imported Capital Asset Purchase)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionB.line75.total)}</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionB.line75.vat)}</td>
                  </tr>
                  <tr>
                    <td className="border border-black p-1 text-center font-bold">85</td>
                    <td className="border border-black p-2">ታክስ ያልተከፈለበት ካፒታል ግዢ (Capital purchase with no VAT or unclaimed input)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionB.line85.total)}</td>
                    <td className="border border-black p-2 bg-gray-100"></td>
                  </tr>
                  <tr className="font-bold bg-gray-50">
                    <td className="border border-black p-1 text-center font-bold">90</td>
                    <td className="border border-black p-2 uppercase">ጠቅላላ የካፒታል ዕቃዎች ግዢ (TOTAL CAPITAL PURCHASES)</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionB.line90.total)}</td>
                    <td className="border border-black p-2 text-right">{formatCurrency(sectionB.line90.vat)}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            {/* Footer Signatures */}
            <div className="mt-12 grid grid-cols-2 gap-12">
              <div className="border-t border-black pt-2">
                <p><strong>የከፋዩ ፊርማ (Taxpayer Signature):</strong></p>
                <div className="h-12"></div>
                <p><strong>ቀን (Date):</strong> _________________</p>
              </div>
              <div className="border-t border-black pt-2">
                <p><strong>ለቢሮ አገልግሎት (For Office Use Only):</strong></p>
                <div className="h-12"></div>
                <p><strong>ፊርማ (Signature):</strong> _________________</p>
              </div>
            </div>
          </div>
        </CardBox>
      </SectionMain>
      <style jsx global>{`
        @media print {
          body * {
            visibility: hidden;
          }
          .print-section, .print-section * {
            visibility: visible;
          }
          .print-section {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
          }
          .no-print {
            display: none !important;
          }
          aside, nav {
            display: none !important;
          }
        }
      `}</style>
    </>
  );
};

ErcaVatForm.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission={'READ_VAT_DECLARATIONS'}>
      {page}
    </LayoutAuthenticated>
  );
};

export default ErcaVatForm;