import * as React from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { formatCurrency } from "@/lib/format-currency";

export type ExpenseCategoryData = {
  label: string;
  color: string;
  monthlyAmounts: number[];
};

export type ApplicantExpensesSectionProps = {
  applicantName: string;
  /** Three states: loading, access granted, access not granted. */
  state: "loading" | "connected" | "pending-access";
  /** Last 12 month labels (e.g. "Jan", "Feb" …). Required when state = "connected". */
  monthLabels?: string[];
  /** Per-category breakdown. Required when state = "connected". */
  categories?: ExpenseCategoryData[];
  /** Total spend over the loaded period. */
  totalAmount?: number;
  onConnectMore?: () => void;
  onAddManually?: () => void;
  onSendRequest?: () => void;
  className?: string;
};

export function ApplicantExpensesSection({
  applicantName,
  state,
  monthLabels = [],
  categories = [],
  totalAmount = 0,
  onConnectMore,
  onAddManually,
  onSendRequest,
  className,
}: ApplicantExpensesSectionProps) {
  return (
    <div className={cn("flex flex-col gap-4 font-sans", className)}>
      <h3 className="text-sm font-semibold text-foreground">
        {applicantName}&apos;s Expenses
      </h3>

      {state === "loading" && <LoadingState />}

      {state === "connected" && (
        <ConnectedState
          monthLabels={monthLabels}
          categories={categories}
          totalAmount={totalAmount}
          onConnectMore={onConnectMore}
          onAddManually={onAddManually}
        />
      )}

      {state === "pending-access" && (
        <PendingAccessState
          applicantName={applicantName}
          onSendRequest={onSendRequest}
        />
      )}
    </div>
  );
}

// ─── Sub-states ───────────────────────────────────────────────────────────────

function LoadingState() {
  return (
    <div className="flex h-48 items-center justify-center border border-border bg-muted/30">
      <div className="flex items-center gap-2 text-sm text-muted-foreground">
        <SpinnerIcon className="size-4 animate-spin" />
        Loading banking data…
      </div>
    </div>
  );
}

function ConnectedState({
  monthLabels,
  categories,
  totalAmount,
  onConnectMore,
  onAddManually,
}: {
  monthLabels: string[];
  categories: ExpenseCategoryData[];
  totalAmount: number;
  onConnectMore?: () => void;
  onAddManually?: () => void;
}) {
  const maxValue = Math.max(
    ...monthLabels.map((_, mi) =>
      categories.reduce((sum, cat) => sum + (cat.monthlyAmounts[mi] ?? 0), 0),
    ),
    1,
  );

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div className="flex flex-col gap-0.5">
          <span className="text-title-medium font-semibold text-foreground">
            {formatCurrency(totalAmount)}
          </span>
          <span className="text-xs text-muted-foreground">
            Total latest 12 months
          </span>
        </div>
        <div className="flex flex-col gap-2">
          <Button size="sm" onClick={onConnectMore}>
            Connect More Accounts
          </Button>
          {onAddManually && (
            <Button size="sm" variant="outline" onClick={onAddManually}>
              Add Manually
            </Button>
          )}
        </div>
      </div>

      {/* Mini stacked bar chart */}
      {monthLabels.length > 0 && categories.length > 0 && (
        <div className="overflow-x-auto">
          <div className="flex min-w-0 items-end gap-1">
            {monthLabels.map((month, mi) => {
              const colTotal = categories.reduce(
                (sum, cat) => sum + (cat.monthlyAmounts[mi] ?? 0),
                0,
              );
              const heightPct = (colTotal / maxValue) * 100;
              return (
                <div
                  key={month}
                  className="flex flex-1 flex-col items-center gap-1"
                >
                  <div
                    className="flex w-full flex-col-reverse overflow-hidden"
                    style={{ height: 80 }}
                    title={`${month}: ${formatCurrency(colTotal)}`}
                  >
                    <div
                      className="flex w-full flex-col-reverse"
                      style={{ height: `${heightPct}%` }}
                    >
                      {categories.map((cat) => {
                        const segPct =
                          colTotal > 0
                            ? ((cat.monthlyAmounts[mi] ?? 0) / colTotal) * 100
                            : 0;
                        return (
                          <div
                            key={cat.label}
                            style={{
                              height: `${segPct}%`,
                              backgroundColor: cat.color,
                            }}
                          />
                        );
                      })}
                    </div>
                  </div>
                  <span className="text-[10px] text-muted-foreground">
                    {month}
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Legend */}
      {categories.length > 0 && (
        <div className="flex flex-wrap gap-3">
          {categories.map((cat) => (
            <div key={cat.label} className="flex items-center gap-1.5">
              <div
                className="size-2.5 shrink-0"
                style={{ backgroundColor: cat.color }}
              />
              <span className="text-xs text-muted-foreground">{cat.label}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function PendingAccessState({
  applicantName,
  onSendRequest,
}: {
  applicantName: string;
  onSendRequest?: () => void;
}) {
  return (
    <div className="flex flex-col items-center gap-4 border border-border py-10 text-center">
      <LockIcon className="size-8 text-muted-foreground" />
      <div className="flex flex-col gap-1">
        <p className="text-sm font-medium text-foreground">
          Requires access to banking data
        </p>
        <p className="text-xs text-muted-foreground">
          Send {applicantName} an invitation to connect their bank accounts.
        </p>
      </div>
      <Button onClick={onSendRequest}>Send request to {applicantName}</Button>
    </div>
  );
}

// ─── Icons ────────────────────────────────────────────────────────────────────

function SpinnerIcon({ className }: { className?: string }) {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      fill="none"
      viewBox="0 0 24 24"
      className={className}
      aria-hidden="true"
    >
      <circle
        className="opacity-25"
        cx="12"
        cy="12"
        r="10"
        stroke="currentColor"
        strokeWidth="4"
      />
      <path
        className="opacity-75"
        fill="currentColor"
        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
      />
    </svg>
  );
}

function LockIcon({ className }: { className?: string }) {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      strokeLinecap="round"
      strokeLinejoin="round"
      className={className}
      aria-hidden="true"
    >
      <rect x="3" y="11" width="18" height="11" rx="0" />
      <path d="M7 11V7a5 5 0 0 1 10 0v4" />
    </svg>
  );
}
