import React from "react";
import { cn } from "@/lib/utils";
import { colorMixSwatch } from "@/lib/colors";
import { Button } from "./button";
import { EditableMoneyItem } from "./editable-money-item";
import { CalculatorInputItem } from "./calculator-input-item";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "./accordion";

/**
 * Right-panel organism for the Borrowing Capacity page.
 *
 * Composes:
 * - Collapsible income accordion with editable sub-items
 * - Expense rows (editable + read-only) separated by dividers
 * - Stacked proportional bar visualising income vs expenses
 * - Apply footer button
 *
 * All values are pre-formatted strings — business logic stays in the app layer.
 */

const INCOME_COLOR = "#39FD99";
const SURPLUS_COLOR = "#C65AFF";
const EXPENSES_COLOR = "#9B9EA1";
const DEBT_COLOR = "#162029";
// Distinct opacities let viewers distinguish HEM row from debt row sharing the same hue
const HEM_FILL_OPACITY = 0.7;
const DEBT_FILL_OPACITY = 0.8;

export interface CalculatorIncomeItem {
  key: string;
  /** e.g. "Avg Income Per Month" */
  label: string;
  /** Pre-formatted e.g. "$8,500" */
  value: string;
}

export interface CalculatorSectionProps {
  // ── Income accordion ─────────────────────────────────
  /** Formatted total of all income sources, e.g. "$12,500" */
  incomeTotalFormatted: string;
  /** Individual income line items shown when accordion is open */
  incomeItems: CalculatorIncomeItem[];
  /** Initial open/closed state of the accordion (uncontrolled after mount) */
  defaultIncomeExpanded?: boolean;
  onIncomeExpandChange?: (open: boolean) => void;
  /** Called with the item key when a pencil button is clicked */
  onIncomeItemEdit?: (key: string) => void;

  // ── Expense rows ──────────────────────────────────────
  currentExpensesValue: string;
  currentExpensesTooltip?: string;
  /**
   * Raw number — enables inline editing directly in the row.
   * Must be paired with `onCurrentExpensesChange`.
   */
  currentExpenses?: number;
  onCurrentExpensesChange?: (value: number) => void;
  /** Fallback: called when pencil is clicked (no inline edit) */
  onCurrentExpensesEdit?: () => void;

  optimisedEstimateValue: string;
  optimisedEstimateTooltip?: string;

  debtRepaymentsValue: string;
  /**
   * Raw number — enables inline editing directly in the row.
   * Must be paired with `onDebtRepaymentsChange`.
   */
  debtRepayments?: number;
  onDebtRepaymentsChange?: (value: number) => void;
  /** Fallback: called when pencil is clicked (no inline edit) */
  onDebtRepaymentsEdit?: () => void;

  surplusIncomeValue: string;

  // ── Bar proportions (0–100) ───────────────────────────
  surplusPercent: number;
  currentExpensesPercent: number;
  debtRepaymentsPercent: number;

  // ── Footer ────────────────────────────────────────────
  /** Enables the Save button */
  hasChanges?: boolean;
  /** Shows loading state on the Save button */
  isSaving?: boolean;
  onSave?: () => void;

  className?: string;
}

function RowDivider() {
  return <div className="border-t border-border" />;
}

export function CalculatorSection({
  incomeTotalFormatted,
  incomeItems,
  defaultIncomeExpanded = false,
  onIncomeExpandChange,
  onIncomeItemEdit,
  currentExpensesValue,
  currentExpensesTooltip,
  currentExpenses,
  onCurrentExpensesChange,
  onCurrentExpensesEdit,
  optimisedEstimateValue,
  optimisedEstimateTooltip,
  debtRepaymentsValue,
  debtRepayments,
  onDebtRepaymentsChange,
  onDebtRepaymentsEdit,
  surplusIncomeValue,
  surplusPercent,
  currentExpensesPercent,
  debtRepaymentsPercent,
  hasChanges = false,
  isSaving = false,
  onSave,
  className,
}: CalculatorSectionProps) {
  const [accordionValue, setAccordionValue] = React.useState<string[]>(
    defaultIncomeExpanded ? ["income"] : [],
  );

  return (
    <div className={cn("flex flex-col gap-4 p-4", className)}>
      <p className="text-center text-base font-bold text-foreground">
        Calculator Used
      </p>

      <div className="flex flex-col">
        <Accordion
          value={accordionValue}
          onValueChange={(vals: string[]) => {
            setAccordionValue(vals);
            onIncomeExpandChange?.(vals.includes("income"));
          }}
        >
          <AccordionItem value="income" className="border-b-0">
            <AccordionTrigger className="px-0 py-0 hover:no-underline hover:bg-transparent">
              <div className="flex min-w-0 flex-1 items-center gap-2 py-2">
                <span
                  aria-hidden
                  className="h-5 w-5 shrink-0 border"
                  style={{
                    borderColor: INCOME_COLOR,
                    backgroundColor: colorMixSwatch(INCOME_COLOR),
                  }}
                />
                <span className="truncate text-sm text-foreground">
                  After tax income
                </span>
              </div>
              <span className="mr-2 text-base font-semibold tabular-nums text-foreground">
                {incomeTotalFormatted}
              </span>
            </AccordionTrigger>
            <AccordionContent className="pb-0">
              <div className="flex flex-col pl-7">
                {incomeItems.map((item, idx) => (
                  <React.Fragment key={item.key}>
                    {idx > 0 && <RowDivider />}
                    <CalculatorInputItem
                      label={item.label}
                      value={item.value}
                      onEdit={
                        onIncomeItemEdit
                          ? () => onIncomeItemEdit(item.key)
                          : undefined
                      }
                    />
                  </React.Fragment>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>

        <RowDivider />

        <EditableMoneyItem
          label="Current Expenses"
          value={currentExpensesValue}
          color={EXPENSES_COLOR}
          tooltip={currentExpensesTooltip}
          numericValue={currentExpenses}
          onValueChange={onCurrentExpensesChange}
          onEdit={onCurrentExpensesChange ? undefined : onCurrentExpensesEdit}
        />

        <RowDivider />

        <EditableMoneyItem
          label="Optimised Estimate (HEM)"
          value={optimisedEstimateValue}
          color={DEBT_COLOR}
          fillOpacity={HEM_FILL_OPACITY}
          tooltip={optimisedEstimateTooltip}
        />

        <RowDivider />

        <EditableMoneyItem
          label="Debt Repayments"
          value={debtRepaymentsValue}
          color={DEBT_COLOR}
          fillOpacity={DEBT_FILL_OPACITY}
          numericValue={debtRepayments}
          onValueChange={onDebtRepaymentsChange}
          onEdit={onDebtRepaymentsChange ? undefined : onDebtRepaymentsEdit}
        />

        <RowDivider />

        <EditableMoneyItem
          label="Surplus Income"
          value={surplusIncomeValue}
          color={SURPLUS_COLOR}
        />
      </div>

      <div className="flex flex-col gap-1">
        <div
          className="h-5 w-full border"
          style={{
            borderColor: INCOME_COLOR,
            backgroundColor: colorMixSwatch(INCOME_COLOR),
          }}
          aria-hidden
        />
        <div className="flex h-5 gap-0.5" aria-hidden>
          <div
            className="shrink-0 border"
            style={{
              width: `${surplusPercent}%`,
              borderColor: SURPLUS_COLOR,
              backgroundColor: colorMixSwatch(SURPLUS_COLOR),
            }}
          />
          <div
            className="shrink-0 border"
            style={{
              width: `${currentExpensesPercent}%`,
              borderColor: EXPENSES_COLOR,
              backgroundColor: colorMixSwatch(EXPENSES_COLOR),
            }}
          />
          <div
            className="shrink-0 border"
            style={{
              width: `${debtRepaymentsPercent}%`,
              borderColor: DEBT_COLOR,
              backgroundColor: colorMixSwatch(DEBT_COLOR, DEBT_FILL_OPACITY),
            }}
          />
        </div>
      </div>

      <div className="flex justify-end">
        <Button
          variant="outline-secondary"
          disabled={!hasChanges || isSaving}
          onClick={onSave}
        >
          {isSaving ? "Saving…" : "Apply"}
        </Button>
      </div>
    </div>
  );
}
