"use client";

import Image from "next/image";
import Link from "next/link";
import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { ArrowRight, BadgeCheck, CheckCircle2, CreditCard, Gavel, Search, ShoppingCart, Truck } from "lucide-react";
import { HOME_IMAGES } from "@/lib/home/images";
import { cn } from "@/lib/utils";

type Step = {
  key: string;
  tab: string;
  icon: typeof Search;
  title: string;
  text: string;
  points: string[];
  image: string;
  imageAlt: string;
  cta: { label: string; href: string };
  mock: ReactNode;
};

function MockCard({ children }: { children: ReactNode }) {
  return (
    <div className="w-full max-w-[300px] rounded-2xl bg-white/95 p-4 text-xs text-slate-600 shadow-2xl ring-1 ring-black/5 backdrop-blur">
      {children}
    </div>
  );
}

const STEPS: Step[] = [
  {
    key: "discover",
    tab: "Discover",
    icon: Search,
    title: "Find the right material, fast",
    text: "Search the catalogue, compare grades and brands, and check today's mandi rates before you buy.",
    points: ["TMT, pipes, angles, channels, billets & more", "Live prices from key steel markets", "Seller ratings and verified listings"],
    image: HOME_IMAGES.structural,
    imageAlt: "Steel sections stocked in a warehouse",
    cta: { label: "Browse products", href: "/products" },
    mock: (
      <MockCard>
        <div className="flex items-center gap-2 rounded-lg bg-slate-100 px-2.5 py-2 text-slate-500">
          <Search size={13} aria-hidden /> MS TMT 12mm
        </div>
        {["MS TMT · Fe 500D", "MS TMT · Fe 550D", "MS Round Bar"].map((row, i) => (
          <div key={row} className="mt-2 flex items-center justify-between rounded-lg border border-slate-100 px-2.5 py-2">
            <span className="font-semibold text-slate-800">{row}</span>
            <span className="text-[10px] font-semibold text-emerald-600">{3 + i * 2} offers</span>
          </div>
        ))}
      </MockCard>
    ),
  },
  {
    key: "quote",
    tab: "Get quotes",
    icon: Gavel,
    title: "Sellers compete for your order",
    text: "Post a requirement once. Verified sellers bid live and you see the best landed price for your city.",
    points: ["15-minute live bidding window", "Anonymised offers — pure price competition", "Quotes typically within 30 minutes"],
    image: HOME_IMAGES.bars,
    imageAlt: "Steel bars stacked on warehouse racks",
    cta: { label: "Post a requirement", href: "#get-quote" },
    mock: (
      <MockCard>
        <div className="flex items-center justify-between">
          <span className="font-bold text-slate-900">Live bidding</span>
          <span className="rounded-full bg-red-50 px-2 py-0.5 text-[10px] font-bold text-[#CC1414]">08:42 left</span>
        </div>
        {[
          ["Offer A", "₹52,150", true],
          ["Offer B", "₹52,400", false],
          ["Offer C", "₹52,900", false],
        ].map(([label, price, best]) => (
          <div
            key={label as string}
            className={cn(
              "mt-2 flex items-center justify-between rounded-lg px-2.5 py-2",
              best ? "bg-emerald-50 ring-1 ring-emerald-200" : "border border-slate-100"
            )}
          >
            <span className="font-semibold text-slate-800">{label}</span>
            <span className={cn("font-bold", best ? "text-emerald-700" : "text-slate-700")}>
              {price}
              <span className="text-[10px] font-medium text-slate-400">/MT</span>
            </span>
          </div>
        ))}
      </MockCard>
    ),
  },
  {
    key: "buy",
    tab: "Buy",
    icon: ShoppingCart,
    title: "Lock the best price in one tap",
    text: "Accept the winning offer, pay a small token from your wallet, and the price is locked for you.",
    points: ["GST invoice on every order", "Quality check before dispatch", "Dedicated relationship manager"],
    image: HOME_IMAGES.coils,
    imageAlt: "Steel coils in storage",
    cta: { label: "See how buying works", href: "/products" },
    mock: (
      <MockCard>
        <div className="flex items-center gap-2 font-bold text-emerald-700">
          <CheckCircle2 size={16} aria-hidden /> Order confirmed
        </div>
        <div className="mt-3 grid grid-cols-2 gap-2">
          {[
            ["Product", "MS TMT"],
            ["Quantity", "25 MT"],
            ["Token paid", "₹50,000"],
            ["Delivery", "Pune"],
          ].map(([k, v]) => (
            <div key={k} className="rounded-lg bg-slate-50 px-2.5 py-2">
              <p className="text-[10px] text-slate-400">{k}</p>
              <p className="font-semibold text-slate-800">{v}</p>
            </div>
          ))}
        </div>
      </MockCard>
    ),
  },
  {
    key: "pay",
    tab: "Pay",
    icon: CreditCard,
    title: "Keep your working capital free",
    text: "Use Biznie credit and flexible payment terms so cash flow never holds up a purchase.",
    points: ["Credit for manufacturers & contractors", "Advance, credit or LC payment modes", "Clear ledger for every order"],
    image: HOME_IMAGES.factory,
    imageAlt: "Inside a large steel manufacturing plant",
    cta: { label: "Apply for credit", href: "/credit-request" },
    mock: (
      <MockCard>
        <p className="text-[10px] font-semibold uppercase tracking-wider text-slate-400">Credit available</p>
        <p className="mt-1 text-2xl font-extrabold text-slate-900">₹25,00,000</p>
        <div className="mt-3 h-2 overflow-hidden rounded-full bg-slate-100">
          <div className="h-full w-[38%] rounded-full bg-gradient-to-r from-[#CC1414] to-[#ff6b6b]" />
        </div>
        <div className="mt-2 flex justify-between text-[10px] text-slate-500">
          <span>Used ₹9,50,000</span>
          <span>45-day terms</span>
        </div>
      </MockCard>
    ),
  },
  {
    key: "track",
    tab: "Track",
    icon: Truck,
    title: "Know where your goods are",
    text: "Vehicle, driver and delivery status in your dashboard — or just ask Biznie AI in chat.",
    points: ["Vehicle & driver details", "Status updates to delivery", "Order ledger and invoices online"],
    image: HOME_IMAGES.truckRoad,
    imageAlt: "Truck driving on a highway through green fields",
    cta: { label: "Track an order", href: "/orders" },
    mock: (
      <MockCard>
        <div className="flex items-center justify-between">
          <span className="font-bold text-slate-900">OID-20260921-4821</span>
          <span className="rounded-full bg-blue-50 px-2 py-0.5 text-[10px] font-bold text-blue-600">Dispatched</span>
        </div>
        <ol className="mt-3 space-y-2">
          {["Confirmed", "Loading", "Dispatched", "Delivered"].map((s, i) => (
            <li key={s} className="flex items-center gap-2">
              <span
                className={cn(
                  "flex h-4 w-4 items-center justify-center rounded-full",
                  i < 3 ? "bg-[#CC1414] text-white" : "border border-slate-300"
                )}
              >
                {i < 3 ? <BadgeCheck size={10} aria-hidden /> : null}
              </span>
              <span className={i < 3 ? "font-semibold text-slate-800" : "text-slate-400"}>{s}</span>
            </li>
          ))}
        </ol>
      </MockCard>
    ),
  },
];

/** "How Biznie works" — five steps, one tab each, keyboard navigable. */
export default function PlatformTabs() {
  const [active, setActive] = useState(0);
  const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const baseId = useId();
  const step = STEPS[active];

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

  return (
    <div>
      <div
        role="tablist"
        aria-label="How Biznie works"
        onKeyDown={onKeyDown}
        className="-mx-4 flex gap-2 overflow-x-auto px-4 pb-2 [scrollbar-width:none] sm:mx-0 sm:justify-center sm:px-0 [&::-webkit-scrollbar]:hidden"
      >
        {STEPS.map((s, i) => {
          const Icon = s.icon;
          const selected = i === active;
          return (
            <button
              key={s.key}
              ref={(el) => {
                tabRefs.current[i] = el;
              }}
              id={`${baseId}-tab-${s.key}`}
              role="tab"
              type="button"
              aria-selected={selected}
              aria-controls={`${baseId}-panel`}
              tabIndex={selected ? 0 : -1}
              onClick={() => setActive(i)}
              className={cn(
                "flex shrink-0 items-center gap-2 rounded-full border px-4 py-2.5 text-sm font-semibold transition-all",
                selected
                  ? "border-[#CC1414] bg-[#CC1414] text-white shadow-lg shadow-red-500/25"
                  : "border-white/15 bg-white/5 text-white/70 hover:border-white/30 hover:text-white"
              )}
            >
              <span
                className={cn(
                  "flex h-6 w-6 items-center justify-center rounded-full text-[11px]",
                  selected ? "bg-white/20" : "bg-white/10"
                )}
              >
                {i + 1}
              </span>
              <Icon size={15} aria-hidden />
              {s.tab}
            </button>
          );
        })}
      </div>

      <div
        id={`${baseId}-panel`}
        role="tabpanel"
        aria-labelledby={`${baseId}-tab-${step.key}`}
        className="mt-8 grid items-center gap-8 lg:grid-cols-2 lg:gap-12"
      >
        <div key={step.key} className="animate-[fade-in-up_0.5s_ease-out] order-2 lg:order-1">
          <h3 className="text-2xl font-extrabold tracking-tight text-white sm:text-3xl">{step.title}</h3>
          <p className="mt-3 text-base leading-relaxed text-white/70">{step.text}</p>
          <ul className="mt-6 space-y-3">
            {step.points.map((p) => (
              <li key={p} className="flex items-start gap-3 text-white/85">
                <CheckCircle2 size={18} className="mt-0.5 shrink-0 text-[#ff6b6b]" aria-hidden />
                {p}
              </li>
            ))}
          </ul>
          <Link
            href={step.cta.href}
            className="mt-8 inline-flex h-12 items-center gap-2 rounded-xl bg-white px-6 text-sm font-semibold text-slate-900 transition-colors hover:bg-red-50"
          >
            {step.cta.label} <ArrowRight size={16} aria-hidden />
          </Link>
        </div>

        <div className="relative order-1 aspect-[4/3] overflow-hidden rounded-3xl ring-1 ring-white/10 lg:order-2">
          {STEPS.map((s, i) => (
            <Image
              key={s.key}
              src={s.image}
              alt={i === active ? s.imageAlt : ""}
              fill
              sizes="(max-width: 1024px) 100vw, 600px"
              className={cn(
                "object-cover transition-all duration-700",
                i === active ? "scale-100 opacity-100" : "scale-105 opacity-0"
              )}
            />
          ))}
          <div className="absolute inset-0 bg-gradient-to-t from-slate-950/70 via-transparent to-transparent" />
          <div key={step.key} className="absolute bottom-4 left-4 right-4 flex justify-end animate-[fade-in-up_0.5s_ease-out] sm:bottom-6 sm:right-6">
            {step.mock}
          </div>
        </div>
      </div>
    </div>
  );
}
