"use client";

import React, { useState, useRef } from "react";
import Link from "next/link";
import { PhoneDeviceFrame } from "@/components/phone-frame";
import { SyncedCallPlayer, type SyncedCallPlayerHandle } from "@/components/synced-call-player";
import { USE_CASES_DATA, type UseCaseEntry } from "@/lib/use-cases-data";
import { Phone, Globe, MessageCircle, Play, Pause, Volume2, VolumeX, ArrowRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

export function UseCasesSection() {
  const [activeStage, setActiveStage] = useState<"Activate" | "Retain" | "Support">("Activate");
  const [activeEntryIndex, setActiveEntryIndex] = useState(0);

  // Playback control states for the floating controls
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [playbackRate, setPlaybackRate] = useState(1);

  const playerRef = useRef<SyncedCallPlayerHandle | null>(null);

  const stageData = USE_CASES_DATA.find((s) => s.stage === activeStage) || USE_CASES_DATA[0];
  const activeEntry: UseCaseEntry = stageData.entries[activeEntryIndex] || stageData.entries[0];

  const handleStageChange = (stage: "Activate" | "Retain" | "Support") => {
    setActiveStage(stage);
    setActiveEntryIndex(0);
    setIsPlaying(false);
  };

  const handleEntryClick = (index: number) => {
    setActiveEntryIndex(index);
    setIsPlaying(false);
  };

  // Floating controls proxy to the transcript player (every entry uses it).
  const handleTogglePlay = () => playerRef.current?.togglePlay();
  const handleCycleRate = () => playerRef.current?.cycleRate();
  const handleToggleMute = () => playerRef.current?.toggleMute();

  const handlePlaybackSync = (state: { isPlaying: boolean; isMuted: boolean; playbackRate: number }) => {
    setIsPlaying(state.isPlaying);
    setIsMuted(state.isMuted);
    setPlaybackRate(state.playbackRate);
  };

  return (
    <div className="w-full">
      {/* Two Column Layout: Left (Header + Tabs + Accordions), Right (Device Frame aligned to top) */}
      <div className="flex flex-col lg:flex-row lg:items-start lg:gap-10">
        {/* Left Column: Header, Tabs, and Vertical Sub-tabs / Accordions */}
        <div className="w-full lg:w-[460px] lg:shrink-0">
          {/* Section header with the brand diamond mark */}
          <div className="mb-4 flex items-center gap-2">
            <span
              aria-hidden="true"
              className="block size-[15px] shrink-0 bg-[#4FDAF1]"
              style={{
                clipPath:
                  "polygon(50% 4%, 55% 12.5%, 58.5% 18.5%, 61% 23%, 63% 27%, 65% 30%, 67% 33%, 68.5% 36%, 70% 38.5%, 71.5% 41%, 73% 44%, 75% 47%, 76.5% 50%, 78.5% 54%, 81.5% 58.5%, 85% 64.5%, 90% 73%, 80% 73%, 73% 73%, 68% 73%, 63% 73%, 59.5% 73%, 56% 73%, 53% 73%, 50% 73%, 47% 73%, 44% 73%, 40.5% 73%, 37% 73%, 32.5% 73%, 27% 73%, 20% 73%, 10% 73%, 15% 64.5%, 18.5% 58.5%, 21% 54%, 23.5% 50%, 25% 47%, 27% 44%, 28.5% 41%, 30% 38.5%, 31.5% 36%, 33% 33%, 35% 30%, 37% 27%, 39% 23%, 41.5% 18.5%, 45% 12.5%)",
              }}
            />
            <h2 className="font-display text-base font-medium text-foreground lg:text-2xl">
              Perfect for <span className="font-extrabold text-gradient-brand">every use case</span>
            </h2>
          </div>

          {/* 3 Main Tabs: Activate, Retain, Support */}
          <div className="mb-6 flex items-center">
            <div className="inline-flex items-center rounded-full bg-secondary/80 p-1 border border-border/50">
              {(["Activate", "Retain", "Support"] as const).map((stage) => {
                const isSelected = activeStage === stage;
                return (
                  <button
                    key={stage}
                    type="button"
                    onClick={() => handleStageChange(stage)}
                    aria-pressed={isSelected}
                    className={cn(
                      "relative h-8 rounded-full px-4 text-sm font-semibold transition-all",
                      isSelected
                        ? "bg-gradient-brand text-white font-bold shadow-xs glow-brand"
                        : "text-muted-foreground hover:text-foreground",
                    )}
                  >
                    {stage}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Accordion Sub-tabs */}
          <div className="divide-y divide-border/60">
            {stageData.entries.map((entry, idx) => {
              const isExpanded = activeEntryIndex === idx;
              const kindColor =
                entry.kind === "call"
                  ? "text-[#E26B0B]"
                  : entry.kind === "browser"
                    ? "text-[#4FDAF1]"
                    : "text-[#67B7E7]";

              return (
                <div key={idx} className="group transition-all">
                  {/* Accordion trigger — use-case title + category badge */}
                  <button
                    type="button"
                    onClick={() => handleEntryClick(idx)}
                    aria-expanded={isExpanded}
                    className={cn(
                      "flex w-full items-center justify-between gap-2.5 px-0 py-4 text-left text-base font-medium tracking-tight transition-colors duration-200 sm:text-xl md:py-5.5",
                      isExpanded
                        ? "text-foreground font-semibold"
                        : "text-muted-foreground hover:text-foreground",
                    )}
                  >
                    <div className="flex min-w-0 items-center gap-3">
                      {entry.kind === "call" ? (
                        <Phone className={cn("size-5 shrink-0 transition-colors", isExpanded ? kindColor : "text-muted-foreground group-hover:text-foreground")} />
                      ) : entry.kind === "browser" ? (
                        <Globe className={cn("size-5 shrink-0 transition-colors", isExpanded ? kindColor : "text-muted-foreground group-hover:text-foreground")} />
                      ) : (
                        <MessageCircle className={cn("size-5 shrink-0 transition-colors", isExpanded ? kindColor : "text-muted-foreground group-hover:text-foreground")} />
                      )}
                      <span className="min-w-0 break-words">{entry.title}</span>
                    </div>

                    {/* Category badge */}
                    <span
                      className={cn(
                        "shrink-0 rounded-full px-3 py-1 text-sm whitespace-nowrap transition-colors",
                        entry.industry === "Quto"
                          ? "border border-[#4FDAF1]/50 bg-[#4FDAF1]/15 text-[#020202] dark:text-[#4FDAF1] font-bold"
                          : isExpanded
                            ? "border border-[#F79C09]/40 bg-[#F79C09]/10 font-semibold text-foreground"
                            : "bg-secondary font-normal text-muted-foreground",
                      )}
                    >
                      {entry.industry}
                    </span>
                  </button>

                  {/* Accordion Expanded Content (Description & Brand Logos) */}
                  {isExpanded && (
                    <div className="flex flex-col gap-4 pt-0 pr-0 pb-6 pl-8 animate-in fade-in-50 duration-200">
                      {/* Description: text-base leading-relaxed text-muted */}
                      <p className="text-base leading-relaxed text-muted-foreground">
                        {entry.description}
                      </p>

                      {/* Action link — the relevant industry page, or the Quto product section */}
                      {entry.href && (
                        <Link
                          href={entry.href}
                          className="group/link mt-1 inline-flex items-center gap-1.5 self-start text-sm font-semibold text-[#E26B0B] underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background rounded-sm"
                        >
                          {entry.linkLabel || "Learn more"}
                          <ArrowRight className="size-4 transition-transform group-hover/link:translate-x-0.5 motion-reduce:transition-none motion-reduce:group-hover/link:translate-x-0" />
                        </Link>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* Right Column: Device Canvas Frame with Dotted Grid Background */}
        <div className="relative mt-8 flex min-h-[480px] w-full flex-1 items-center justify-center overflow-hidden rounded-3xl border border-border/80 bg-secondary/15 p-3 sm:min-h-[540px] sm:p-5 lg:mt-0 lg:flex lg:min-h-[580px] lg:p-6">
            {/* Subtle dotted-grid backdrop for the device canvas */}
            <div
              className="pointer-events-none absolute inset-0 z-0 opacity-40 dark:opacity-25"
              style={{
                backgroundImage:
                  "radial-gradient(circle, currentColor 1px, transparent 1px)",
                backgroundSize: "18px 18px",
              }}
            />

            {/* Device Mockup Centered — every entry is a voice call or a website
                chat, both shown in the phone frame with the synced transcript. */}
            <div className="relative z-10 flex w-full items-center justify-center">
              <div className="w-[min(260px,100%)] sm:w-[270px] lg:w-[275px] xl:w-[280px]" style={{ aspectRatio: "433 / 882" }}>
                <PhoneDeviceFrame className="size-full shadow-2xl">
                  <SyncedCallPlayer
                    ref={playerRef}
                    entry={activeEntry}
                    onPlaybackChange={handlePlaybackSync}
                    className="size-full"
                  />
                </PhoneDeviceFrame>
              </div>
            </div>

            {/* Floating playback controls (play / speed / mute) */}
            <div className="absolute right-4 bottom-4 z-30 flex flex-col gap-2 sm:right-5 sm:bottom-5">
              {/* Play / Pause Toggle Button */}
              <button
                type="button"
                onClick={handleTogglePlay}
                aria-label={isPlaying ? "Pause audio" : "Play audio"}
                className="flex size-10 cursor-pointer items-center justify-center rounded-full border border-border/80 bg-background/90 text-foreground backdrop-blur-md shadow-xs transition hover:scale-105 active:scale-95 sm:size-11"
              >
                {isPlaying ? (
                  <Pause className="size-4 fill-current sm:size-4.5" />
                ) : (
                  <Play className="size-4 ml-0.5 fill-current sm:size-4.5" />
                )}
              </button>

              {/* Speed Selector (1x, 1.25x, 1.5x, 2x) */}
              <button
                type="button"
                onClick={handleCycleRate}
                aria-label={`Playback speed ${playbackRate}x`}
                className="flex size-10 cursor-pointer items-center justify-center rounded-full border border-border/80 bg-background/90 text-foreground backdrop-blur-md shadow-xs transition hover:scale-105 active:scale-95 text-xs font-semibold font-mono sm:size-11"
              >
                {playbackRate}x
              </button>

              {/* Mute / Unmute Toggle Button */}
              <button
                type="button"
                onClick={handleToggleMute}
                aria-label={isMuted ? "Unmute" : "Mute"}
                className="flex size-10 cursor-pointer items-center justify-center rounded-full border border-border/80 bg-background/90 text-foreground backdrop-blur-md shadow-xs transition hover:scale-105 active:scale-95 sm:size-11"
              >
                {isMuted ? (
                  <VolumeX className="size-4 text-muted-foreground sm:size-4.5" />
                ) : (
                  <Volume2 className="size-4 sm:size-4.5" />
                )}
              </button>
            </div>
          </div>
        </div>

        {/* View all industries CTA */}
        <div className="mt-10 flex justify-center lg:mt-12">
          <Button variant="outline" size="pill" asChild>
            <Link href="/industries">View all industries</Link>
          </Button>
        </div>
      </div>
    );
  }
