import React, { useState } from 'react';
import { Akun, Jurnal, ProfilPerusahaan, PeriodeAkuntansi } from '../../types/accounting';
import { AccountingEngine } from '../../services/accountingEngine';
import { ExcelService } from '../../services/excelService';
import { PrintHeader, PrintSignature } from '../common/PrintHeader';
import { Download, Printer, CheckCircle2, Search, Calendar, Table2 } from 'lucide-react';

interface NeracaLajurViewProps {
  akuns: Akun[];
  journals: Jurnal[];
  profile: ProfilPerusahaan;
  periodes: PeriodeAkuntansi[];
  activePeriode: PeriodeAkuntansi;
}

export const NeracaLajurView: React.FC<NeracaLajurViewProps> = ({
  akuns,
  journals,
  profile,
  periodes,
  activePeriode,
}) => {
  const [selectedBulan, setSelectedBulan] = useState<string>(
    activePeriode?.namaPeriode || 'Januari 2026'
  );
  const [searchTerm, setSearchTerm] = useState('');
  const [hideZero, setHideZero] = useState(false);

  React.useEffect(() => {
    if (activePeriode?.namaPeriode) {
      setSelectedBulan(activePeriode.namaPeriode);
    }
  }, [activePeriode?.namaPeriode]);

  // Konsep Saldo Berjalan (Carrying Balance) untuk periode bulanan
  const { carryingAkuns, periodJournals } = AccountingEngine.getCarryingAkunsForPeriod(
    selectedBulan,
    akuns,
    journals,
    periodes || [],
    profile
  );

  const worksheet = AccountingEngine.calculateNeracaLajur(carryingAkuns, periodJournals);

  // Filter rows
  const filteredRows = worksheet.rows.filter((row) => {
    const matchesSearch =
      row.akun.kodeAkun.toLowerCase().includes(searchTerm.toLowerCase()) ||
      row.akun.namaAkun.toLowerCase().includes(searchTerm.toLowerCase());

    const hasValue =
      row.nsDebet > 0 ||
      row.nsKredit > 0 ||
      row.ajpDebet > 0 ||
      row.ajpKredit > 0 ||
      row.nsdDebet > 0 ||
      row.nsdKredit > 0 ||
      row.rugiLabaDebet > 0 ||
      row.rugiLabaKredit > 0 ||
      row.neracaDebet > 0 ||
      row.neracaKredit > 0;

    return matchesSearch && (!hideZero || hasValue);
  });

  const handleExportExcel = () => {
    const headers = [
      'Kode Akun',
      'Nama Akun',
      'NS (Debet)',
      'NS (Kredit)',
      'AJP (Debet)',
      'AJP (Kredit)',
      'NSD (Debet)',
      'NSD (Kredit)',
      'Rugi Laba (Debet)',
      'Rugi Laba (Kredit)',
      'Neraca (Debet)',
      'Neraca (Kredit)',
    ];

    const rows: (string | number)[][] = filteredRows.map((r) => [
      r.akun.kodeAkun,
      r.akun.namaAkun,
      r.nsDebet,
      r.nsKredit,
      r.ajpDebet,
      r.ajpKredit,
      r.nsdDebet,
      r.nsdKredit,
      r.rugiLabaDebet,
      r.rugiLabaKredit,
      r.neracaDebet,
      r.neracaKredit,
    ]);

    // Add Net Profit Row
    rows.push([
      '-',
      'LABA BERSIH TAHUN BERJALAN',
      0,
      0,
      0,
      0,
      0,
      0,
      worksheet.labaBersihRugiLaba > 0 ? worksheet.labaBersihRugiLaba : 0,
      worksheet.labaBersihRugiLaba < 0 ? Math.abs(worksheet.labaBersihRugiLaba) : 0,
      worksheet.labaBersihNeraca < 0 ? Math.abs(worksheet.labaBersihNeraca) : 0,
      worksheet.labaBersihNeraca > 0 ? worksheet.labaBersihNeraca : 0,
    ]);

    // Add Grand Total Row
    rows.push([
      'TOTAL',
      'GRAND TOTAL SEIMBANG',
      worksheet.totalNS.debet,
      worksheet.totalNS.kredit,
      worksheet.totalAJP.debet,
      worksheet.totalAJP.kredit,
      worksheet.totalNSD.debet,
      worksheet.totalNSD.kredit,
      worksheet.grandTotalRugiLaba.debet,
      worksheet.grandTotalRugiLaba.kredit,
      worksheet.grandTotalNeraca.debet,
      worksheet.grandTotalNeraca.kredit,
    ]);

    ExcelService.exportToStyledExcel(
      `Neraca_Lajur_10_Kolom_${selectedBulan.replace(/\s+/g, '_')}`,
      `KERTAS KERJA / NERACA LAJUR (WORKSHEET) 10-KOLOM - ${selectedBulan.toUpperCase()}`,
      headers,
      rows
    );
  };

  return (
    <div className="space-y-5">
      {/* Print View Header */}
      <div className="hidden print:block">
        <PrintHeader
          profile={profile}
          title="NERACA LAJUR / KERTAS KERJA (ACCOUNTING WORKSHEET 10-KOLOM)"
          subtitle="Neraca Saldo, Penyesuaian (AJP), Neraca Disesuaikan, Laba Rugi, dan Neraca"
          periode={selectedBulan === 'SEMUA' ? activePeriode.namaPeriode : selectedBulan}
        />
      </div>

      {/* Screen Card */}
      <div className="rounded-lg border border-slate-200 bg-white shadow-xs print:border-none print:shadow-none">
        {/* Card Header */}
        <div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-200 bg-slate-50/70 px-5 py-3.5 print:hidden">
          <div className="flex items-center gap-2">
            <Table2 className="h-4 w-4 text-blue-600" />
            <h2 className="text-sm font-bold uppercase tracking-wider text-slate-800">
              Neraca Lajur (10-Kolom Worksheet)
            </h2>
            <span className="rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-semibold text-blue-800">
              Kertas Kerja Lengkap
            </span>
          </div>

          <div className="flex flex-wrap items-center gap-2">
            <button
              onClick={handleExportExcel}
              className="inline-flex items-center gap-1.5 rounded border border-slate-300 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50"
            >
              <Download className="h-3.5 w-3.5 text-blue-600" />
              Download Excel (.xls)
            </button>
            <button
              onClick={() => window.print()}
              className="inline-flex items-center gap-1.5 rounded border border-slate-300 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50"
            >
              <Printer className="h-3.5 w-3.5 text-slate-600" />
              Cetak / PDF
            </button>
          </div>
        </div>

        {/* Filters */}
        <div className="flex flex-wrap items-center justify-between gap-3 px-5 py-3 border-b border-slate-100 print:hidden">
          <div className="flex flex-wrap items-center gap-3">
            <div className="relative min-w-[200px]">
              <Search className="absolute left-3 top-2.5 h-3.5 w-3.5 text-slate-400" />
              <input
                type="text"
                placeholder="Cari kode atau nama akun..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full rounded border border-slate-300 pl-9 pr-3 py-1.5 text-xs focus:border-blue-500 focus:outline-hidden"
              />
            </div>

            <div className="flex items-center gap-1.5">
              <Calendar className="h-3.5 w-3.5 text-slate-500" />
              <select
                value={selectedBulan}
                onChange={(e) => setSelectedBulan(e.target.value)}
                className="rounded border border-slate-300 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-700 focus:border-blue-500 focus:outline-hidden"
              >
                <option value="SEMUA">Semua Periode (Akumulasi)</option>
                {periodes.map((p) => (
                  <option key={p.id} value={p.namaPeriode}>
                    Periode: {p.namaPeriode}
                  </option>
                ))}
              </select>
            </div>

            <label className="flex items-center gap-1.5 text-xs text-slate-600 cursor-pointer select-none">
              <input
                type="checkbox"
                checked={hideZero}
                onChange={(e) => setHideZero(e.target.checked)}
                className="rounded border-slate-300 text-blue-600 focus:ring-0"
              />
              Sembunyikan Baris Nol
            </label>
          </div>

          <div className="flex items-center gap-2">
            <span className="rounded bg-emerald-100 text-emerald-800 px-3 py-1 text-xs font-semibold flex items-center gap-1.5">
              <CheckCircle2 className="h-3.5 w-3.5" />
              Laba Bersih: Rp {worksheet.labaBersihRugiLaba.toLocaleString('id-ID')}
            </span>
          </div>
        </div>

        {/* 10-Kolom Table */}
        <div className="overflow-x-auto">
          <table className="w-full text-left text-[11px] border-collapse">
            <thead>
              <tr className="border-b border-slate-300 bg-slate-100 text-slate-700 font-semibold uppercase text-center">
                <th rowSpan={2} className="py-2 px-2.5 w-20 text-left border-r border-slate-200">
                  Kode
                </th>
                <th rowSpan={2} className="py-2 px-2.5 w-44 text-left border-r border-slate-200">
                  Nama Akun
                </th>
                <th colSpan={2} className="py-1 px-1 border-r border-slate-200 bg-slate-200/80">
                  Neraca Saldo
                </th>
                <th colSpan={2} className="py-1 px-1 border-r border-slate-200 bg-amber-100/70">
                  AJP (Penyesuaian)
                </th>
                <th colSpan={2} className="py-1 px-1 border-r border-slate-200 bg-blue-100/70">
                  Neraca Disesuaikan (NSD)
                </th>
                <th colSpan={2} className="py-1 px-1 border-r border-slate-200 bg-emerald-100/70">
                  Rugi Laba
                </th>
                <th colSpan={2} className="py-1 px-1 bg-purple-100/70">
                  Neraca
                </th>
              </tr>
              <tr className="border-b border-slate-300 bg-slate-100 text-slate-600 text-center font-medium">
                <th className="py-1 px-1 w-24 text-right border-r border-slate-200">Debet</th>
                <th className="py-1 px-1 w-24 text-right border-r border-slate-200">Kredit</th>
                <th className="py-1 px-1 w-24 text-right border-r border-slate-200">Debet</th>
                <th className="py-1 px-1 w-24 text-right border-r border-slate-200">Kredit</th>
                <th className="py-1 px-1 w-24 text-right border-r border-slate-200 font-bold">Debet</th>
                <th className="py-1 px-1 w-24 text-right border-r border-slate-200 font-bold">Kredit</th>
                <th className="py-1 px-1 w-24 text-right border-r border-slate-200">Debet</th>
                <th className="py-1 px-1 w-24 text-right border-r border-slate-200">Kredit</th>
                <th className="py-1 px-1 w-24 text-right border-r border-slate-200">Debet</th>
                <th className="py-1 px-1 w-24 text-right">Kredit</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200 font-mono text-[11px]">
              {filteredRows.map((r) => (
                <tr key={r.akun.id} className="hover:bg-blue-50/20">
                  <td className="py-1.5 px-2.5 font-bold text-blue-900 border-r border-slate-200">
                    {r.akun.kodeAkun}
                  </td>
                  <td className="py-1.5 px-2.5 font-sans font-medium text-slate-800 border-r border-slate-200 truncate max-w-[180px]">
                    {r.akun.namaAkun}
                  </td>
                  {/* NS */}
                  <td className="py-1.5 px-1 text-right text-slate-700 border-r border-slate-200">
                    {r.nsDebet > 0 ? r.nsDebet.toLocaleString('id-ID') : '-'}
                  </td>
                  <td className="py-1.5 px-1 text-right text-slate-700 border-r border-slate-200">
                    {r.nsKredit > 0 ? r.nsKredit.toLocaleString('id-ID') : '-'}
                  </td>
                  {/* AJP */}
                  <td className="py-1.5 px-1 text-right text-amber-800 border-r border-slate-200">
                    {r.ajpDebet > 0 ? r.ajpDebet.toLocaleString('id-ID') : '-'}
                  </td>
                  <td className="py-1.5 px-1 text-right text-amber-800 border-r border-slate-200">
                    {r.ajpKredit > 0 ? r.ajpKredit.toLocaleString('id-ID') : '-'}
                  </td>
                  {/* NSD */}
                  <td className="py-1.5 px-1 text-right font-bold text-blue-950 border-r border-slate-200 bg-blue-50/20">
                    {r.nsdDebet > 0 ? r.nsdDebet.toLocaleString('id-ID') : '-'}
                  </td>
                  <td className="py-1.5 px-1 text-right font-bold text-blue-950 border-r border-slate-200 bg-blue-50/20">
                    {r.nsdKredit > 0 ? r.nsdKredit.toLocaleString('id-ID') : '-'}
                  </td>
                  {/* Rugi Laba */}
                  <td className="py-1.5 px-1 text-right text-emerald-800 border-r border-slate-200">
                    {r.rugiLabaDebet > 0 ? r.rugiLabaDebet.toLocaleString('id-ID') : '-'}
                  </td>
                  <td className="py-1.5 px-1 text-right text-emerald-800 border-r border-slate-200">
                    {r.rugiLabaKredit > 0 ? r.rugiLabaKredit.toLocaleString('id-ID') : '-'}
                  </td>
                  {/* Neraca */}
                  <td className="py-1.5 px-1 text-right text-purple-800 border-r border-slate-200">
                    {r.neracaDebet > 0 ? r.neracaDebet.toLocaleString('id-ID') : '-'}
                  </td>
                  <td className="py-1.5 px-1 text-right text-purple-800">
                    {r.neracaKredit > 0 ? r.neracaKredit.toLocaleString('id-ID') : '-'}
                  </td>
                </tr>
              ))}

              {/* Subtotal Before Profit Row */}
              <tr className="border-t-2 border-slate-300 bg-slate-100 font-bold text-slate-800">
                <td colSpan={2} className="py-2 px-2.5 text-right font-sans uppercase">
                  Jumlah Sebelum Laba:
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200">
                  {worksheet.totalNS.debet.toLocaleString('id-ID')}
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200">
                  {worksheet.totalNS.kredit.toLocaleString('id-ID')}
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200 text-amber-900">
                  {worksheet.totalAJP.debet.toLocaleString('id-ID')}
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200 text-amber-900">
                  {worksheet.totalAJP.kredit.toLocaleString('id-ID')}
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200 text-blue-900">
                  {worksheet.totalNSD.debet.toLocaleString('id-ID')}
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200 text-blue-900">
                  {worksheet.totalNSD.kredit.toLocaleString('id-ID')}
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200 text-emerald-900">
                  {worksheet.totalRugiLaba.debet.toLocaleString('id-ID')}
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200 text-emerald-900">
                  {worksheet.totalRugiLaba.kredit.toLocaleString('id-ID')}
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200 text-purple-900">
                  {worksheet.totalNeraca.debet.toLocaleString('id-ID')}
                </td>
                <td className="py-2 px-1 text-right text-purple-900">
                  {worksheet.totalNeraca.kredit.toLocaleString('id-ID')}
                </td>
              </tr>

              {/* Laba Bersih Penyeimbang Row */}
              <tr className="bg-emerald-50 font-bold text-emerald-900 border-t border-b border-emerald-200">
                <td colSpan={2} className="py-2 px-2.5 text-right font-sans uppercase">
                  Laba Bersih Tahun Berjalan (Penyeimbang):
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200">-</td>
                <td className="py-2 px-1 text-right border-r border-slate-200">-</td>
                <td className="py-2 px-1 text-right border-r border-slate-200">-</td>
                <td className="py-2 px-1 text-right border-r border-slate-200">-</td>
                <td className="py-2 px-1 text-right border-r border-slate-200">-</td>
                <td className="py-2 px-1 text-right border-r border-slate-200">-</td>
                {/* RL column: if profit > 0 put on debet to balance */}
                <td className="py-2 px-1 text-right border-r border-slate-200 text-emerald-800">
                  {worksheet.labaBersihRugiLaba > 0
                    ? worksheet.labaBersihRugiLaba.toLocaleString('id-ID')
                    : '-'}
                </td>
                <td className="py-2 px-1 text-right border-r border-slate-200 text-emerald-800">
                  {worksheet.labaBersihRugiLaba < 0
                    ? Math.abs(worksheet.labaBersihRugiLaba).toLocaleString('id-ID')
                    : '-'}
                </td>
                {/* Neraca column: if profit > 0 put on credit to balance */}
                <td className="py-2 px-1 text-right border-r border-slate-200 text-emerald-800">
                  {worksheet.labaBersihNeraca < 0
                    ? Math.abs(worksheet.labaBersihNeraca).toLocaleString('id-ID')
                    : '-'}
                </td>
                <td className="py-2 px-1 text-right text-emerald-800">
                  {worksheet.labaBersihNeraca > 0
                    ? worksheet.labaBersihNeraca.toLocaleString('id-ID')
                    : '-'}
                </td>
              </tr>
            </tbody>

            {/* Grand Total Balances */}
            <tfoot className="border-t-2 border-slate-900 bg-slate-900 text-white font-mono font-bold text-[11px]">
              <tr>
                <td colSpan={2} className="py-2.5 px-2.5 text-right font-sans uppercase">
                  Grand Total Seimbang:
                </td>
                <td className="py-2.5 px-1 text-right border-r border-slate-700">
                  {worksheet.totalNS.debet.toLocaleString('id-ID')}
                </td>
                <td className="py-2.5 px-1 text-right border-r border-slate-700">
                  {worksheet.totalNS.kredit.toLocaleString('id-ID')}
                </td>
                <td className="py-2.5 px-1 text-right border-r border-slate-700 text-amber-300">
                  {worksheet.totalAJP.debet.toLocaleString('id-ID')}
                </td>
                <td className="py-2.5 px-1 text-right border-r border-slate-700 text-amber-300">
                  {worksheet.totalAJP.kredit.toLocaleString('id-ID')}
                </td>
                <td className="py-2.5 px-1 text-right border-r border-slate-700 text-cyan-300">
                  {worksheet.totalNSD.debet.toLocaleString('id-ID')}
                </td>
                <td className="py-2.5 px-1 text-right border-r border-slate-700 text-cyan-300">
                  {worksheet.totalNSD.kredit.toLocaleString('id-ID')}
                </td>
                <td className="py-2.5 px-1 text-right border-r border-slate-700 text-emerald-300">
                  {worksheet.grandTotalRugiLaba.debet.toLocaleString('id-ID')}
                </td>
                <td className="py-2.5 px-1 text-right border-r border-slate-700 text-emerald-300">
                  {worksheet.grandTotalRugiLaba.kredit.toLocaleString('id-ID')}
                </td>
                <td className="py-2.5 px-1 text-right border-r border-slate-700 text-purple-300">
                  {worksheet.grandTotalNeraca.debet.toLocaleString('id-ID')}
                </td>
                <td className="py-2.5 px-1 text-right text-purple-300">
                  {worksheet.grandTotalNeraca.kredit.toLocaleString('id-ID')}
                </td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>

      {/* Print Signature Section */}
      <div className="hidden print:block">
        <PrintSignature profile={profile} />
      </div>
    </div>
  );
};
