"use client";

import { useState, useEffect, useRef, type KeyboardEvent } from "react";
import { Play, Pause } from "lucide-react";
import { cn } from "@/lib/utils";

interface IndustryVoiceShowcaseProps {
  callTitle: string;
  callSubtitle: string;
  durationSeconds?: number;
  audioUrl?: string;
}

const WAVEFORM_HEIGHTS = [
  35, 60, 45, 80, 55, 90, 70, 40, 85, 95, 65, 50,
  75, 40, 85, 60, 45, 90, 75, 55, 65, 80, 50, 70,
  85, 60, 40, 75, 95, 55, 45, 65, 80, 50, 70, 40,
];

const clamp = (n: number, min: number, max: number) => Math.min(max, Math.max(min, n));

export function IndustryVoiceShowcase({
  durationSeconds = 28,
  audioUrl,
}: IndustryVoiceShowcaseProps) {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const trackRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (isPlaying) {
      interval = setInterval(() => {
        setCurrentTime((prev) => {
          if (prev >= durationSeconds) {
            setIsPlaying(false);
            return 0;
          }
          return prev + 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [isPlaying, durationSeconds]);

  const handleTogglePlay = () => {
    if (!isPlaying) {
      setIsPlaying(true);
      audioRef.current?.play().catch(() => {});
    } else {
      setIsPlaying(false);
      audioRef.current?.pause();
    }
  };

  const seekToTime = (secs: number, autoplay = true) => {
    const t = Math.round(clamp(secs, 0, durationSeconds));
    setCurrentTime(t);
    if (autoplay && !isPlaying) setIsPlaying(true);
  };

  const seekFromClientX = (clientX: number) => {
    const el = trackRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const frac = clamp((clientX - rect.left) / rect.width, 0, 1);
    seekToTime(frac * durationSeconds);
  };

  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    const step = Math.max(1, Math.round(durationSeconds / 20));
    if (e.key === "ArrowRight" || e.key === "ArrowUp") {
      e.preventDefault();
      seekToTime(currentTime + step, false);
    } else if (e.key === "ArrowLeft" || e.key === "ArrowDown") {
      e.preventDefault();
      seekToTime(currentTime - step, false);
    } else if (e.key === "Home") {
      e.preventDefault();
      seekToTime(0, false);
    } else if (e.key === "End") {
      e.preventDefault();
      seekToTime(durationSeconds, false);
    } else if (e.key === " " || e.key === "Enter") {
      e.preventDefault();
      handleTogglePlay();
    }
  };

  const activeBarsCount = Math.floor((currentTime / durationSeconds) * WAVEFORM_HEIGHTS.length);

  const formatTime = (secs: number) => {
    const m = Math.floor(secs / 60);
    const s = Math.floor(secs % 60);
    return `${m}:${s < 10 ? `0${s}` : s}`;
  };

  return (
    <div className="relative flex min-h-[300px] w-full items-center justify-center overflow-hidden rounded-3xl border border-border/80 bg-secondary/15 p-6 shadow-lg sm:min-h-[380px] sm:p-10">
      {/* Subtle halftone background grid */}
      <div
        aria-hidden
        className="pointer-events-none absolute inset-0 opacity-20"
        style={{
          backgroundImage: "radial-gradient(circle, currentColor 1.2px, transparent 1.2px)",
          backgroundSize: "20px 20px",
        }}
      />

      {/* Floating Interactive Audio Capsule */}
      <div className="relative z-10 flex w-full max-w-md flex-col gap-3 rounded-3xl border border-border/80 bg-card/95 px-5 py-4 shadow-2xl backdrop-blur-md transition-all sm:flex-row sm:items-center sm:gap-4 sm:rounded-full sm:px-8 sm:py-5">
        {/* Play / Pause Circular Button */}
        <button
          type="button"
          onClick={handleTogglePlay}
          className="flex size-12 shrink-0 cursor-pointer items-center justify-center rounded-full bg-primary text-primary-foreground shadow-md transition-all hover:scale-105 hover:bg-primary/90 active:scale-95 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card"
          aria-label={isPlaying ? "Pause voice preview" : "Play voice preview"}
        >
          {isPlaying ? <Pause className="size-5 fill-current" /> : <Play className="ml-0.5 size-5 fill-current" />}
        </button>

        {/* Waveform seek slider */}
        <div className="flex flex-1 flex-col justify-center">
          <div
            ref={trackRef}
            role="slider"
            tabIndex={0}
            aria-label="Seek voice preview"
            aria-valuemin={0}
            aria-valuemax={durationSeconds}
            aria-valuenow={currentTime}
            aria-valuetext={`${formatTime(currentTime)} of ${formatTime(durationSeconds)}`}
            onKeyDown={onKeyDown}
            onClick={(e) => seekFromClientX(e.clientX)}
            className="flex h-10 cursor-pointer items-center gap-px rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card sm:gap-1"
          >
            {WAVEFORM_HEIGHTS.map((h, i) => {
              const isFilled = i <= activeBarsCount;
              return (
                <span
                  key={i}
                  aria-hidden
                  className={cn(
                    "min-w-0 flex-1 rounded-full transition-all duration-150 sm:w-1 sm:flex-none",
                    isFilled ? "bg-primary opacity-100" : "bg-muted-foreground/30 opacity-40",
                  )}
                  style={{ height: `${h}%` }}
                />
              );
            })}
          </div>

          {/* Time & Latency Footer */}
          <div className="mt-1 flex items-center justify-between text-[10px] text-muted-foreground">
            <span className="font-mono">
              {formatTime(currentTime)} / {formatTime(durationSeconds)}
            </span>
            <span className="flex items-center gap-1 font-medium text-muted-foreground">
              <span className="size-1.5 rounded-full bg-primary animate-pulse motion-reduce:animate-none" />
              Sub-350ms turnaround
            </span>
          </div>
        </div>
      </div>

      {audioUrl && <audio ref={audioRef} src={audioUrl} preload="none" />}
    </div>
  );
}
