"use client";

import { useState, useCallback } from "react";
import type { LeaderReport } from "@/types/leader";
import LeaderReportMainCard from "./LeaderReportMainCard";
import LeaderReportTripSummaryCard from "./LeaderReportTripSummaryCard";
import LeaderReportFinanceSummaryCard from "./LeaderReportFinanceSummaryCard";
import LeaderReportSupportCard from "./LeaderReportSupportCard";
import LeaderReportTrustStrip from "./LeaderReportTrustStrip";
import styles from "./LeaderReportComponents.module.css";
import pageStyles from "@/app/(public)/leader-report/[token]/LeaderReportPage.module.css";

interface Props {
  token: string;
  report: LeaderReport;
}

export default function LeaderReportContainer({ token, report }: Props) {
  // Initial calculation matching backend
  const initialRentals = (report.rentals || []).reduce(
    (sum, r) => sum + (Number(r.unit_price) || 0) * (Number(r.quantity) || 0),
    0
  );
  const initialExpenses = (report.expenses || []).reduce(
    (sum, e) => sum + (Number(e.unit_price) || 0) * (Number(e.quantity) || 0),
    0
  );
  const initialLogistics = (report.logistics || []).reduce(
    (sum, l) => sum + (Number(l.unit_price) || 0) * (Number(l.quantity) || 0),
    0
  );
  const initialIncome =
    (Number(report.reported_cash_amount) || 0) +
    (Number(report.reported_transfer_amount) || 0) +
    initialRentals;
  const initialExpense = initialExpenses + initialLogistics;
  const initialBalance = initialIncome - initialExpense;

  const [totals, setTotals] = useState({
    totalIncome: initialIncome,
    totalExpense: initialExpense,
    balance: initialBalance,
  });

  const handleTotalsChange = useCallback(
    (newTotals: { totalIncome: number; totalExpense: number; balance: number }) => {
      setTotals(newTotals);
    },
    []
  );

  return (
    <>
      <div className={pageStyles.mainGrid}>
        {/* LEFT COLUMN: Main Report Form Card */}
        <div className={pageStyles.leftColumn}>
          <LeaderReportMainCard
            token={token}
            report={report}
            onTotalsChange={handleTotalsChange}
          />
        </div>

        {/* RIGHT COLUMN: Sticky Sidebar on Desktop */}
        <aside className={pageStyles.rightColumn}>
          <div className={styles.stickySidebar}>
            <div className={styles.sidebarContainer}>
              <LeaderReportTripSummaryCard report={report} />
              <LeaderReportFinanceSummaryCard
                totalIncome={totals.totalIncome}
                totalExpense={totals.totalExpense}
                balance={totals.balance}
              />
              <LeaderReportSupportCard reportCode={report.report_code} />
            </div>
          </div>
        </aside>
      </div>

      {/* Trust Strip */}
      <LeaderReportTrustStrip />
    </>
  );
}
