"use client";

import { cn } from "@/lib/utils";
import {
  Activity,
  CheckCircle2,
  Gauge,
  KeyRound,
  PlugZap,
  ShieldCheck,
  Stethoscope,
  UploadCloud,
  type LucideIcon,
} from "lucide-react";
import Image from "next/image";
import { useRef, useState, type KeyboardEvent } from "react";

interface OcppTab {
  id: string;
  label: string;
  description: string;
  items: readonly string[];
  icon: LucideIcon;
}

const ocppTabs: readonly OcppTab[] = [
  {
    id: "charging-station",
    label: "Charging Station",
    description:
      "Connect and manage charging stations from different hardware manufacturers through one OCPP-compatible platform.",
    items: [
      "Register and connect OCPP charging stations",
      "Monitor charger and connector availability",
      "Receive online, offline, and fault status updates",
      "Control charging stations remotely",
    ],
    icon: PlugZap,
  },
  {
    id: "authorization",
    label: "Authorization",
    description:
      "Control who can use your charging network and validate each charging request securely.",
    items: [
      "Authorize RFID cards and customer identities",
      "Approve or reject charging access requests",
      "Maintain local authorization lists",
      "Support customer, fleet, and corporate access",
    ],
    icon: KeyRound,
  },
  {
    id: "session",
    label: "Session",
    description:
      "Track every charging session from the moment it starts until the final energy consumption is recorded.",
    items: [
      "Start and stop charging transactions",
      "Capture session timestamps and meter values",
      "Track energy usage during active sessions",
      "Review completed charging-session history",
    ],
    icon: Activity,
  },
  {
    id: "smart-charging",
    label: "Smart Charging",
    description:
      "Manage charger power intelligently to protect site capacity and optimize energy distribution.",
    items: [
      "Create charging profiles and schedules",
      "Set power and current limits",
      "Balance available power across chargers",
      "Prioritize selected chargers or customer groups",
    ],
    icon: Gauge,
  },
  {
    id: "security",
    label: "Security",
    description:
      "Protect communication between charging stations and the central management platform.",
    items: [
      "Use secure charger-to-platform connections",
      "Manage charging-station certificates",
      "Authenticate connected charging hardware",
      "Record important operational and access events",
    ],
    icon: ShieldCheck,
  },
  {
    id: "firmware",
    label: "Firmware",
    description:
      "Keep charging-station software current without requiring a technician to visit every location.",
    items: [
      "Schedule remote firmware updates",
      "Track firmware download and installation status",
      "Review charger firmware versions",
      "Coordinate updates across multiple locations",
    ],
    icon: UploadCloud,
  },
  {
    id: "diagnostic",
    label: "Diagnostic",
    description:
      "Collect the information your operations team needs to investigate charger issues faster.",
    items: [
      "Request diagnostic files remotely",
      "Collect charger logs for troubleshooting",
      "Review fault and error information",
      "Support faster technical issue resolution",
    ],
    icon: Stethoscope,
  },
];

export function OcppFeatureTabs() {
  const [activeTabId, setActiveTabId] = useState(ocppTabs[0].id);
  const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
  const activeTab =
    ocppTabs.find((ocppTab) => ocppTab.id === activeTabId) ?? ocppTabs[0];

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

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

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

    if (!nextTab) {
      return;
    }

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

  return (
    <div>
      <div className="overflow-x-auto pb-2">
        <div
          role="tablist"
          aria-label="OCPP capabilities"
          aria-orientation="horizontal"
          className="flex min-w-max gap-2 rounded-2xl border border-gray-200 bg-gray-100 p-2"
        >
          {ocppTabs.map((ocppTab, index) => {
            const TabIcon = ocppTab.icon;
            const isActive = ocppTab.id === activeTabId;

            return (
              <button
                key={ocppTab.id}
                ref={(element) => {
                  tabRefs.current[index] = element;
                }}
                id={`ocpp-tab-${ocppTab.id}`}
                type="button"
                role="tab"
                aria-selected={isActive}
                aria-controls={`ocpp-panel-${ocppTab.id}`}
                tabIndex={isActive ? 0 : -1}
                onClick={() => setActiveTabId(ocppTab.id)}
                onKeyDown={(event) => handleTabKeyDown(event, index)}
                className={cn(
                  "flex items-center gap-2 rounded-xl px-4 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"
                    : "bg-white text-gray-600 hover:bg-green-50 hover:text-green-700",
                )}
              >
                <TabIcon aria-hidden="true" className="size-4" />
                {ocppTab.label}
              </button>
            );
          })}
        </div>
      </div>

      <div
        id={`ocpp-panel-${activeTab.id}`}
        role="tabpanel"
        aria-labelledby={`ocpp-tab-${activeTab.id}`}
        tabIndex={0}
        className="mt-6 overflow-hidden rounded-3xl border border-green-100 bg-gradient-to-br from-white to-green-50 p-4 shadow-sm focus-visible:ring-2 focus-visible:ring-green-600 focus-visible:outline-none sm:p-6 lg:p-8"
      >
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-[1.15fr_0.85fr] lg:items-center lg:gap-8">
          <div className="overflow-hidden rounded-2xl border border-gray-200 bg-white p-2 shadow-md sm:p-3">
            <Image
              src="/images/OcppConection.png"
              alt="OCPP-connected charger and charging management dashboard"
              width={1518}
              height={1036}
              sizes="(max-width: 1023px) 100vw, 55vw"
              className="h-auto w-full rounded-xl object-contain"
            />
          </div>

          <ul className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-1">
            {activeTab.items.map((item) => (
              <li
                key={item}
                className="flex items-start gap-3 rounded-2xl border border-green-100 bg-white p-4 text-gray-700 shadow-sm transition-transform duration-200 motion-safe:hover:-translate-y-0.5"
              >
                <CheckCircle2
                  aria-hidden="true"
                  className="mt-0.5 size-5 shrink-0 text-green-600"
                />
                <span className="leading-relaxed font-medium">{item}</span>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
}
