import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";

// ─── Types ────────────────────────────────────────────────────────────────────

export type LoanWizardSection = {
  value: string;
  label: string;
  disabled?: boolean;
};

export type LoanWizardApplicantOption = {
  id: string;
  label: string;
};

export type LoanWizardShellProps = {
  // Header
  /** Broker logo / wordmark rendered in the top-left. */
  logo?: React.ReactNode;
  onSaveAndLogOut?: () => void;
  /** Label for the primary header action. Defaults to "Login App". */
  loginAppLabel?: string;
  onLoginApp?: () => void;

  // Hero
  /** Application headline. Defaults to WealthX copy. */
  heroTitle?: string;
  heroSubtitle?: string;
  /** Broker info block rendered on the right of the hero. */
  brokerSlot?: React.ReactNode;

  // Tab navigation
  sections: LoanWizardSection[];
  activeSection: string;
  onSectionChange: (section: string) => void;

  // Applicant switcher (optional — shows a Main / Co-Applicant toggle)
  applicantOptions?: LoanWizardApplicantOption[];
  activeApplicantId?: string;
  onApplicantChange?: (id: string) => void;

  // Content
  children?: React.ReactNode;

  // Bottom navigation
  onPrev?: () => void;
  onNext?: () => void;
  nextLabel?: string;
  /** Disable the bottom "Next" — e.g. the active section's step is incomplete. */
  nextDisabled?: boolean;

  className?: string;
};

export type { LoanWizardSection as LoanWizardSectionItem };
export type { LoanWizardApplicantOption as LoanWizardApplicant };

// ─── Component ────────────────────────────────────────────────────────────────

export function LoanWizardShell({
  logo,
  onSaveAndLogOut,
  loginAppLabel = "Login App",
  onLoginApp,
  heroTitle = "Quick Online Application,\nThat Gets You Answers Fast!",
  heroSubtitle = "(This does not affect your credit score)",
  brokerSlot,
  sections,
  activeSection,
  onSectionChange,
  applicantOptions,
  activeApplicantId,
  onApplicantChange,
  children,
  onPrev,
  onNext,
  nextLabel = "Next",
  nextDisabled = false,
  className,
}: LoanWizardShellProps) {
  const tabListRef = React.useRef<HTMLDivElement>(null);

  // Keep the active tab fully in view whenever it changes — e.g. stepping
  // through sections via Prev/Next can land on a tab that's scrolled out of
  // the overflow-x-auto tab bar on narrow viewports. Computed manually
  // (rather than scrollIntoView) so the active tab is always fully visible,
  // even the last tab where native "center"/"nearest" alignment can fall
  // short of the container's max scroll position. Queries the active
  // TabsTrigger via its data-active attribute rather than a ref, since the
  // shared TabsTrigger is a plain function component (no forwardRef) under
  // React 18.
  React.useEffect(() => {
    const container = tabListRef.current;
    const button = container?.querySelector<HTMLElement>(
      '[data-slot="tabs-trigger"][data-active]',
    );
    if (!container || !button) return;

    const margin = 16;
    const buttonLeft = button.offsetLeft;
    const buttonRight = buttonLeft + button.offsetWidth;
    const visibleLeft = container.scrollLeft;
    const visibleRight = visibleLeft + container.clientWidth;

    let target = container.scrollLeft;
    if (buttonRight + margin > visibleRight) {
      target = buttonRight + margin - container.clientWidth;
    } else if (buttonLeft - margin < visibleLeft) {
      target = buttonLeft - margin;
    }
    target = Math.max(
      0,
      Math.min(target, container.scrollWidth - container.clientWidth),
    );
    container.scrollTo({ left: target, behavior: "auto" });
  }, [activeSection]);

  return (
    <div
      className={cn(
        "flex min-h-screen flex-col bg-background font-sans",
        className,
      )}
    >
      {/* ── Header ── */}
      <header className="flex shrink-0 items-center justify-between border-b border-border px-4 py-4 sm:px-8 sm:py-5 lg:px-[200px]">
        <div className="flex items-center">{logo}</div>
        <div className="flex items-center gap-3">
          {onSaveAndLogOut && (
            <Button variant="outline" size="sm" onClick={onSaveAndLogOut}>
              Save &amp; Log Out
            </Button>
          )}
          {onLoginApp && (
            <Button size="sm" onClick={onLoginApp}>
              {loginAppLabel}
            </Button>
          )}
        </div>
      </header>

      {/* ── Hero ── */}
      <div className="flex shrink-0 items-center justify-between px-4 py-8 sm:px-8 sm:py-12 lg:px-[200px]">
        <div className="flex flex-col gap-2">
          <h1 className="text-display-small text-foreground">
            {heroTitle.split("\n").map((line, i) => (
              <React.Fragment key={i}>
                {line}
                {i < heroTitle.split("\n").length - 1 && <br />}
              </React.Fragment>
            ))}
          </h1>
          {heroSubtitle && (
            <p className="text-body-small text-muted-foreground">
              {heroSubtitle}
            </p>
          )}
          <div className="mt-2 h-[3px] w-24 bg-primary" />
        </div>
        {brokerSlot && <div className="hidden lg:flex">{brokerSlot}</div>}
      </div>

      {/* ── Tab navigation ── */}
      {/* pb-2 keeps the active-tab underline (rendered at bottom-[-5px]) from
          being clipped by this overflow-x-auto scroll container */}
      <div
        ref={tabListRef}
        className="shrink-0 overflow-x-auto px-4 pb-2 sm:px-8 lg:px-[200px]"
      >
        <Tabs
          value={activeSection}
          onValueChange={onSectionChange}
          className="w-max"
        >
          <TabsList
            variant="line"
            className="h-auto w-max justify-start gap-0 border-b border-border"
          >
            {sections.map((s) => (
              <TabsTrigger
                key={s.value}
                value={s.value}
                disabled={s.disabled}
                className="shrink-0 whitespace-nowrap px-3 py-1"
              >
                {s.label}
              </TabsTrigger>
            ))}
          </TabsList>
        </Tabs>
      </div>

      {/* ── Content area ── */}
      <div className="flex flex-1 flex-col gap-6 px-4 pb-10 pt-6 sm:px-8 sm:pb-16 sm:pt-10 lg:px-[200px]">
        {/* Applicant switcher */}
        {applicantOptions && applicantOptions.length > 1 && (
          <Tabs
            value={activeApplicantId}
            onValueChange={onApplicantChange}
            className="w-fit"
          >
            <TabsList>
              {applicantOptions.map((opt) => (
                <TabsTrigger key={opt.id} value={opt.id}>
                  {opt.label}
                </TabsTrigger>
              ))}
            </TabsList>
          </Tabs>
        )}

        {/* sr-only h2 establishes heading hierarchy: h1 (hero) → h2 (section) → h3 (organisms) */}
        <h2 className="sr-only">
          {sections.find((s) => s.value === activeSection)?.label}
        </h2>

        {/* Section content — constrained to ~628px matching design */}
        <div className="w-full max-w-[628px]">{children}</div>
      </div>

      {/* ── Bottom navigation ── */}
      {/* Sticky to the bottom of the viewport on mobile, where a section's
          content commonly runs taller than the screen — reverts to normal
          in-flow positioning at sm+ (unchanged from the original design). */}
      {(onPrev || onNext) && (
        <div className="sticky bottom-0 z-10 shrink-0 border-t border-border bg-background px-4 pb-4 pt-3 sm:static sm:border-t-0 sm:bg-transparent sm:px-8 sm:pb-10 sm:pt-0 lg:px-[200px]">
          <div className="flex max-w-[628px] items-center justify-between sm:border-t sm:border-border sm:pt-6">
            {onPrev ? (
              <Button variant="outline" onClick={onPrev}>
                <ChevronLeft className="mr-1 size-4" />
                Previous
              </Button>
            ) : (
              <span />
            )}
            {onNext && (
              <Button
                variant="outline"
                onClick={onNext}
                disabled={nextDisabled}
              >
                {nextLabel}
                <ChevronRight className="ml-1 size-4" />
              </Button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
