"use client";

import { cn } from "@/lib/utils";
import {
  Bike,
  BusFront,
  CarFront,
  Check,
  Factory,
  Gauge,
  Landmark,
  Network,
  Store,
  Truck,
  Users,
  type LucideIcon,
} from "lucide-react";
import { useEffect, useRef, useState, type KeyboardEvent } from "react";

type SolutionTabId = "b2c" | "b2b" | "b2x";

interface SolutionItem {
  id: string;
  label: string;
  icon: LucideIcon;
}

interface SolutionTab {
  id: SolutionTabId;
  label: string;
  title: string;
  tagline: string;
  paragraphs: readonly string[];
  highlights?: readonly SolutionHighlight[];
  listTitle?: string;
  listItems?: readonly string[];
  supportingText?: string;
  closingStatement: string;
  items: readonly SolutionItem[];
}

interface SolutionHighlight {
  title: string;
  description: string;
}

const solutionTabs: readonly SolutionTab[] = [
  {
    id: "b2c",
    label: "B2C",
    title: "Public Charging for Everyday EV Drivers",
    tagline: "Two wheels or four—one app serves them all.",
    paragraphs: [
      "TIAR AI gives CPOs one white-label app for cars, motorcycles, and scooters alike. Drivers find a nearby station, navigate there with Google Maps, pay through local payment channels, and start charging in seconds.",
      "Fully OCPP-compliant and hardware-agnostic—so you build the network your market needs.",
    ],
    highlights: [
      {
        title: "Monetization Dashboard",
        description:
          "Run pricing, automated financial reporting, business intelligence, loyalty, CRM, and revenue performance in one place.",
      },
      {
        title: "CSMS Dashboard",
        description:
          "Watch the whole network from HQ: active and offline chargers, error reports, downtime, network health, and recommended fixes.",
      },
    ],
    closingStatement:
      "White-label ready—your country, your customers, your brand.",
    items: [
      { id: "ev", label: "EV", icon: CarFront },
      { id: "e-scooter", label: "eScooter", icon: Gauge },
      { id: "e-bike", label: "eBike", icon: Bike },
    ],
  },
  {
    id: "b2b",
    label: "B2B",
    title: "Charging Built Around Your Fleet",
    tagline:
      "For fleets, mobility platforms, logistics, public transport, and institutions.",
    paragraphs: [
      "TIAR AI powers every B2B charging model—taxi fleets, ride-hailing, logistics, rental cars, e-microbuses (angkot), e-buses, e-trucks, government vehicles, police patrols, and institutional fleets.",
      "Subsidized tariffs, driver-specific pricing, daily fees, per-kilometer billing, flat rates, or something entirely your own—we configure the platform to your business logic.",
      "From ride-hailing to logistics to public transport electrification, you control charging access, pricing, reporting, and branding from one place.",
    ],
    closingStatement:
      "Have a unique business model? Let’s design the right payment scheme or strategy and select the best options for your business.",
    items: [
      { id: "taxi", label: "Taxi", icon: CarFront },
      { id: "microbus", label: "MicroBus", icon: Users },
      { id: "bus", label: "Bus", icon: BusFront },
      { id: "truck", label: "Truck", icon: Truck },
    ],
  },
  {
    id: "b2x",
    label: "B2X",
    title: "Partnership-Based Charging Models",
    tagline: "Turn chargers into branding, loyalty, and partnership assets.",
    paragraphs: [
      "Automotive brands, dealers, banks, and corporate partners want deeper customer engagement through EV charging—without running a CPO business themselves.",
      "TIAR AI builds and operates the network under your brand, exclusively or non-exclusively.",
    ],
    listTitle: "Ideal for:",
    listItems: [
      "Automotive brands and EV manufacturers",
      "Showroom and dealer networks",
      "Banks and financial institutions",
      "Property owners and landlords",
      "Retail brands and corporate sponsors",
      "Partners entering the EV ecosystem",
    ],
    supportingText:
      "Automakers and dealers gain branded stations that lift satisfaction and visibility. Banks and sponsors get priority placement in payment channels, presence across the network, and a hook into customer campaigns.",
    closingStatement:
      "Tell us your goals and budget—we’ll shape the partnership around them.",
    items: [
      {
        id: "business-to-any",
        label: "Business to Any Model",
        icon: Network,
      },
      { id: "auto-maker", label: "Auto Maker", icon: Factory },
      {
        id: "bank-sponsorship",
        label: "Bank Sponsorship",
        icon: Landmark,
      },
      { id: "car-dealer", label: "Car Dealer", icon: Store },
    ],
  },
];

const DEFAULT_TAB_ID: SolutionTabId = "b2c";

function isSolutionTabId(value: string): value is SolutionTabId {
  return solutionTabs.some((solutionTab) => solutionTab.id === value);
}

function getTabIdFromHash(hash: string): SolutionTabId {
  const hashValue = hash.replace(/^#/, "").toLowerCase();

  return isSolutionTabId(hashValue) ? hashValue : DEFAULT_TAB_ID;
}

export function SolutionTabs() {
  const [activeTabId, setActiveTabId] = useState<SolutionTabId>(DEFAULT_TAB_ID);
  const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);

  useEffect(() => {
    function syncTabWithHash() {
      setActiveTabId(getTabIdFromHash(window.location.hash));
    }

    syncTabWithHash();
    window.addEventListener("hashchange", syncTabWithHash);

    return () => window.removeEventListener("hashchange", syncTabWithHash);
  }, []);

  function handleTabChange(tabId: SolutionTabId) {
    setActiveTabId(tabId);
    window.history.replaceState(null, "", `#${tabId}`);
  }

  function handleTabKeyDown(
    event: KeyboardEvent<HTMLButtonElement>,
    currentIndex: number,
  ) {
    let nextIndex = currentIndex;

    if (event.key === "ArrowRight") {
      nextIndex = (currentIndex + 1) % solutionTabs.length;
    } else if (event.key === "ArrowLeft") {
      nextIndex =
        (currentIndex - 1 + solutionTabs.length) % solutionTabs.length;
    } else if (event.key === "Home") {
      nextIndex = 0;
    } else if (event.key === "End") {
      nextIndex = solutionTabs.length - 1;
    } else {
      return;
    }

    event.preventDefault();
    const nextTab = solutionTabs[nextIndex];

    if (!nextTab) {
      return;
    }

    handleTabChange(nextTab.id);
    tabRefs.current[nextIndex]?.focus();
  }

  return (
    <div>
      <div className="overflow-x-auto">
        <div
          role="tablist"
          aria-label="Solution categories"
          aria-orientation="horizontal"
          className="flex min-w-max gap-2 rounded-2xl border border-gray-200 bg-white p-2 shadow-sm"
        >
          {solutionTabs.map((solutionTab, index) => {
            const isActive = solutionTab.id === activeTabId;

            return (
              <button
                key={solutionTab.id}
                ref={(element) => {
                  tabRefs.current[index] = element;
                }}
                id={solutionTab.id}
                type="button"
                role="tab"
                aria-selected={isActive}
                aria-controls={`solution-panel-${solutionTab.id}`}
                tabIndex={isActive ? 0 : -1}
                onClick={() => handleTabChange(solutionTab.id)}
                onKeyDown={(event) => handleTabKeyDown(event, index)}
                className={cn(
                  "min-w-28 scroll-mt-24 rounded-xl px-6 py-3 text-sm font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-green-600 focus-visible:ring-offset-2 focus-visible:outline-none",
                  isActive
                    ? "bg-green-600 text-white shadow-sm"
                    : "text-gray-600 hover:bg-green-50 hover:text-green-700",
                )}
              >
                {solutionTab.label}
              </button>
            );
          })}
        </div>
      </div>

      {solutionTabs.map((solutionTab) => {
        const isActive = solutionTab.id === activeTabId;

        return (
          <div
            key={solutionTab.id}
            id={`solution-panel-${solutionTab.id}`}
            role="tabpanel"
            aria-labelledby={solutionTab.id}
            tabIndex={isActive ? 0 : -1}
            hidden={!isActive}
            className="mt-6 focus-visible:ring-2 focus-visible:ring-green-600 focus-visible:outline-none"
          >
            <div className="rounded-3xl border border-gray-200 bg-white p-6 shadow-sm sm:p-8 lg:p-10">
              <div className="max-w-4xl">
                <h3 className="text-3xl font-bold tracking-tight text-gray-950 sm:text-4xl">
                  {solutionTab.title}
                </h3>
                <p className="mt-3 text-lg font-semibold text-green-600 sm:text-xl">
                  {solutionTab.tagline}
                </p>

                <div className="mt-6 space-y-4 text-base leading-relaxed text-gray-600 sm:text-lg">
                  {solutionTab.paragraphs.map((paragraph) => (
                    <p key={paragraph}>{paragraph}</p>
                  ))}
                </div>
              </div>

              {solutionTab.highlights ? (
                <div className="mt-8">
                  <h4 className="text-xl font-bold text-gray-950 sm:text-2xl">
                    Built-In Dashboards for Smarter Operations
                  </h4>
                  <div className="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
                    {solutionTab.highlights.map((highlight) => (
                      <article
                        key={highlight.title}
                        className="rounded-2xl bg-green-50 p-5 sm:p-6"
                      >
                        <h5 className="text-lg font-semibold text-green-950">
                          {highlight.title}
                        </h5>
                        <p className="mt-2 leading-relaxed text-gray-600">
                          {highlight.description}
                        </p>
                      </article>
                    ))}
                  </div>
                </div>
              ) : null}

              {solutionTab.listTitle && solutionTab.listItems ? (
                <div className="mt-8">
                  <h4 className="text-xl font-bold text-gray-950">
                    {solutionTab.listTitle}
                  </h4>
                  <ul className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
                    {solutionTab.listItems.map((listItem) => (
                      <li
                        key={listItem}
                        className="flex items-start gap-3 rounded-xl bg-gray-50 p-4 text-gray-700"
                      >
                        <span className="mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-full bg-green-100 text-green-600">
                          <Check aria-hidden="true" className="size-4" />
                        </span>
                        <span>{listItem}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              ) : null}

              {solutionTab.supportingText ? (
                <p className="mt-6 max-w-4xl text-base leading-relaxed text-gray-600 sm:text-lg">
                  {solutionTab.supportingText}
                </p>
              ) : null}

              <p className="mt-8 rounded-2xl border border-green-100 bg-green-50 p-5 leading-relaxed font-semibold text-green-950 sm:p-6 sm:text-lg">
                {solutionTab.closingStatement}
              </p>
            </div>

            <ul
              className={cn(
                "mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2",
                solutionTab.items.length === 3
                  ? "lg:grid-cols-3"
                  : "lg:grid-cols-4",
              )}
            >
              {solutionTab.items.map((solutionItem) => {
                const SolutionIcon = solutionItem.icon;

                return (
                  <li
                    key={solutionItem.id}
                    className="flex min-h-44 flex-col justify-between rounded-2xl border border-gray-200 bg-white p-6 shadow-sm"
                  >
                    <span className="flex size-11 items-center justify-center rounded-xl bg-green-100 text-green-600">
                      <SolutionIcon aria-hidden="true" className="size-5" />
                    </span>
                    <h4 className="mt-8 text-xl font-semibold text-gray-950">
                      {solutionItem.label}
                    </h4>
                  </li>
                );
              })}
            </ul>
          </div>
        );
      })}
    </div>
  );
}
