"use client";

import { useId, useRef, useState, type KeyboardEvent } from "react";
import {
  CalendarClock,
  Clock,
  Handshake,
  Lock,
  Percent,
  RefreshCw,
  TrendingUp,
  Truck,
  type LucideIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";

type Step = { icon: LucideIcon; label: string; note?: string };

const VIEWS: { key: string; tab: string; caption: string; steps: Step[] }[] = [
  {
    key: "without",
    tab: "Without Biznie",
    caption: "Each step is what the one before it causes.",
    steps: [
      { icon: Clock, label: "Payments are delayed" },
      { icon: Lock, label: "Working capital gets blocked" },
      { icon: Percent, label: "Borrowing costs increase" },
      { icon: Truck, label: "The supply chain suffers" },
    ],
  },
  {
    key: "with",
    tab: "With Biznie",
    caption: "Credit for the buyer and faster payment for the seller — on the same order.",
    steps: [
      { icon: CalendarClock, label: "Buyers get 30–90 days of trade credit", note: "Subject to eligibility and approval" },
      {
        icon: Handshake,
        label: "Suppliers are paid within 7 days of acceptance",
        note: "Subject to the applicable transaction terms",
      },
      { icon: RefreshCw, label: "Working capital moves faster" },
      { icon: TrendingUp, label: "Both sides can grow without waiting on each other" },
    ],
  },
];

/** "Without / With Biznie" switch over the problem chain — a two-tab tablist, arrow-key navigable. */
export default function ProblemToggle() {
  const [active, setActive] = useState(0);
  const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const baseId = useId();
  const view = VIEWS[active];
  const positive = view.key === "with";

  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (event.key !== "ArrowRight" && event.key !== "ArrowLeft") return;
    event.preventDefault();
    const next = (active + 1) % VIEWS.length;
    setActive(next);
    tabRefs.current[next]?.focus();
  };

  return (
    <div className="rounded-3xl bg-slate-50 p-4 ring-1 ring-slate-100 sm:p-5">
      <div
        role="tablist"
        aria-label="The working-capital chain"
        onKeyDown={onKeyDown}
        className="grid grid-cols-2 gap-1 rounded-2xl bg-white p-1 shadow-sm ring-1 ring-slate-200"
      >
        {VIEWS.map((v, i) => {
          const selected = i === active;
          return (
            <button
              key={v.key}
              ref={(el) => {
                tabRefs.current[i] = el;
              }}
              id={`${baseId}-tab-${v.key}`}
              type="button"
              role="tab"
              aria-selected={selected}
              aria-controls={`${baseId}-panel`}
              tabIndex={selected ? 0 : -1}
              onClick={() => setActive(i)}
              className={cn(
                "rounded-xl px-3 py-2.5 text-sm font-semibold transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#CC1414]/40",
                selected
                  ? v.key === "with"
                    ? "bg-[#CC1414] text-white shadow-md"
                    : "bg-slate-900 text-white shadow-md"
                  : "text-slate-500 hover:text-slate-900"
              )}
            >
              {v.tab}
            </button>
          );
        })}
      </div>

      <div id={`${baseId}-panel`} role="tabpanel" aria-labelledby={`${baseId}-tab-${view.key}`} className="mt-4">
        <ol className="space-y-0">
          {view.steps.map(({ icon: Icon, label, note }, i) => (
            <li
              key={`${view.key}-${label}`}
              style={{ animationDelay: `${i * 80}ms` }}
              className="animate-[fade-in-up_0.45s_ease-out_both] motion-reduce:animate-none"
            >
              <div className="flex items-center gap-4 rounded-2xl bg-white p-3.5 shadow-sm ring-1 ring-slate-100 sm:p-4">
                <span
                  className={cn(
                    "flex h-11 w-11 shrink-0 items-center justify-center rounded-xl",
                    positive ? "bg-emerald-50 text-emerald-600" : "bg-red-50 text-[#CC1414]"
                  )}
                >
                  <Icon size={20} aria-hidden />
                </span>
                <span className="min-w-0 flex-1">
                  <span className="block text-sm font-semibold leading-snug text-slate-900">{label}</span>
                  {note ? <span className="mt-0.5 block text-xs text-slate-500">{note}</span> : null}
                </span>
                <span className="text-xs font-bold text-slate-300" aria-hidden>
                  0{i + 1}
                </span>
              </div>
              {i < view.steps.length - 1 ? (
                <span
                  aria-hidden
                  className={cn(
                    "ml-[35px] block h-4 w-px bg-gradient-to-b to-transparent sm:ml-[37px]",
                    positive ? "from-emerald-300" : "from-slate-300"
                  )}
                />
              ) : null}
            </li>
          ))}
        </ol>
        <p className="mt-3 px-1 text-xs text-slate-500">{view.caption}</p>
      </div>
    </div>
  );
}
