"use client";

import React, { useRef, useState } from "react";
import {
  Play,
  Pause,
  Download,
  ShieldCheck,
  CheckCircle2,
  BarChart3,
  Bell,
  Activity,
  AlertTriangle,
  ShieldAlert,
  TrendingDown,
  type LucideIcon,
} from "lucide-react";
import { motion, AnimatePresence, useReducedMotion } from "motion/react";
import { cn } from "@/lib/utils";

type TabId = "qa" | "analytics" | "alerts";

const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
  { id: "qa", label: "QA", icon: ShieldCheck },
  { id: "analytics", label: "Analytics", icon: BarChart3 },
  { id: "alerts", label: "Alerts", icon: Bell },
];

export function QAAuditSection({ className }: { className?: string }) {
  const [tab, setTab] = useState<TabId>("qa");
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(238); // 3m 58s
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const reduce = useReducedMotion();

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

  const handleTimeUpdate = () => {
    if (audioRef.current) {
      setCurrentTime(audioRef.current.currentTime);
    }
  };

  const changeTab = (next: TabId) => {
    // Pause playback when leaving the QA inspection view so audio never
    // keeps playing from a hidden panel.
    if (next !== "qa" && isPlaying && audioRef.current) {
      audioRef.current.pause();
      setIsPlaying(false);
    }
    setTab(next);
  };

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

  const panelTransition = reduce
    ? { duration: 0 }
    : { duration: 0.24, ease: "easeOut" as const };

  return (
    <div className={cn("mx-auto w-full max-w-6xl", className)}>
      {/* Audio element kept mounted at the top level so playback state and the
          ref survive tab switches. */}
      <audio
        ref={audioRef}
        src="/audio/insurance-qa.mp3"
        preload="none"
        onTimeUpdate={handleTimeUpdate}
        onLoadedMetadata={() => {
          if (audioRef.current && audioRef.current.duration) {
            setDuration(audioRef.current.duration);
          }
        }}
        onEnded={() => {
          setIsPlaying(false);
          setCurrentTime(0);
        }}
      />

      {/* Header */}
      <div className="text-center">
        <h2 className="font-display text-3xl font-medium tracking-tight text-foreground sm:text-4xl md:text-5xl leading-tight">
          <span className="font-extrabold text-gradient-brand">QA, analytics, and alerts</span>
          <br />
          on all your conversations.
        </h2>
        <p className="mt-3 text-base text-muted-foreground max-w-xl mx-auto">
          Every conversation is scored in real time across policy adherence,
          latency, and compliance.
        </p>
      </div>

      {/* Tab bar (segmented control) */}
      <div
        role="tablist"
        aria-label="Conversation intelligence views"
        className="mx-auto mt-8 flex w-full max-w-md items-center gap-1 overflow-x-auto rounded-full border border-border bg-muted/60 p-1"
      >
        {TABS.map(({ id, label, icon: Icon }) => {
          const active = tab === id;
          return (
            <button
              key={id}
              type="button"
              role="tab"
              id={`qa-tab-${id}`}
              aria-selected={active}
              aria-controls={`qa-panel-${id}`}
              onClick={() => changeTab(id)}
              className={cn(
                "relative flex flex-1 shrink-0 items-center justify-center gap-1.5 rounded-full px-4 py-2 text-sm font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
                active ? "text-white [&_svg]:text-white font-bold" : "text-muted-foreground hover:text-foreground",
              )}
            >
              {active && (
                <motion.span
                  layoutId="qaTabIndicator"
                  className="absolute inset-0 rounded-full bg-gradient-brand shadow-sm glow-brand"
                  transition={
                    reduce
                      ? { duration: 0 }
                      : { type: "spring", stiffness: 420, damping: 34 }
                  }
                />
              )}
              <span className="relative z-10 flex items-center gap-1.5">
                <Icon className="size-4" />
                {label}
              </span>
            </button>
          );
        })}
      </div>

      {/* Panel frame — reserves height so the swap never collapses/shifts. */}
      <div className="relative mt-8 min-h-[34rem] overflow-hidden rounded-3xl border border-border/80 bg-card p-5 shadow-sm sm:min-h-[30rem] sm:p-6 lg:min-h-[27rem]">
        <AnimatePresence mode="wait" initial={false}>
          {tab === "qa" && (
            <motion.div
              key="qa"
              role="tabpanel"
              id="qa-panel-qa"
              aria-labelledby="qa-tab-qa"
              initial={{ opacity: 0, y: reduce ? 0 : 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: reduce ? 0 : -10 }}
              transition={panelTransition}
              className="space-y-6"
            >
              {/* Call metadata header */}
              <div className="flex flex-wrap items-center justify-between gap-4 border-b border-border/80 pb-4">
                <dl className="flex flex-wrap items-start gap-x-8 gap-y-2 text-xs">
                  <div className="flex flex-col">
                    <dt className="text-muted-foreground">Call Completed</dt>
                    <dd className="font-medium text-foreground">May 11, 10:19 AM</dd>
                  </div>
                  <div className="flex flex-col">
                    <dt className="text-muted-foreground">Call Duration</dt>
                    <dd className="font-medium text-foreground">3m 58s</dd>
                  </div>
                  <div className="flex flex-col">
                    <dt className="text-muted-foreground">Call Status</dt>
                    <dd className="flex items-center gap-1 font-medium text-foreground">
                      <CheckCircle2 className="size-3 text-[#4FDAF1]" /> Success
                    </dd>
                  </div>
                </dl>

                <span className="rounded-full bg-secondary px-3 py-1 font-mono text-[11px] text-muted-foreground">
                  Call ID: #82914-EV
                </span>
              </div>

              {/* Real audio player bar */}
              <div className="flex items-center gap-2 rounded-full bg-foreground/[0.04] py-2.5 pr-3 pl-2 sm:gap-3 sm:pr-4 sm:pl-2.5">
                <button
                  type="button"
                  onClick={togglePlay}
                  className="flex size-9 shrink-0 items-center justify-center rounded-full bg-gradient-brand text-white shadow-xs glow-brand transition hover:scale-105 active:scale-95 motion-reduce:transition-none motion-reduce:hover:scale-100"
                  aria-label={isPlaying ? "Pause call audio" : "Play call audio"}
                >
                  {isPlaying ? (
                    <Pause className="size-4" />
                  ) : (
                    <Play className="size-4 ml-0.5" />
                  )}
                </button>

                <span className="w-10 shrink-0 text-right font-mono text-xs text-foreground sm:w-12">
                  {formatTime(currentTime)}
                </span>

                {/* Scrubber waveform */}
                <div
                  role="slider"
                  tabIndex={0}
                  aria-label="Seek audio"
                  aria-valuemin={0}
                  aria-valuemax={Math.round(duration || 238)}
                  aria-valuenow={Math.round(currentTime)}
                  aria-valuetext={formatTime(currentTime)}
                  className="relative flex h-8 flex-1 cursor-pointer items-center gap-1 rounded-md px-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
                  onClick={(e) => {
                    const rect = e.currentTarget.getBoundingClientRect();
                    const pos = (e.clientX - rect.left) / rect.width;
                    if (audioRef.current) {
                      audioRef.current.currentTime = pos * (duration || 238);
                      if (!isPlaying) {
                        audioRef.current
                          .play()
                          .then(() => setIsPlaying(true))
                          .catch(() => {});
                      }
                    }
                  }}
                  onKeyDown={(e) => {
                    const total = duration || 238;
                    const step = Math.max(1, Math.round(total / 20));
                    let next: number | null = null;
                    if (e.key === "ArrowRight" || e.key === "ArrowUp") next = Math.min(total, currentTime + step);
                    else if (e.key === "ArrowLeft" || e.key === "ArrowDown") next = Math.max(0, currentTime - step);
                    else if (e.key === "Home") next = 0;
                    else if (e.key === "End") next = total;
                    if (next !== null) {
                      e.preventDefault();
                      if (audioRef.current) audioRef.current.currentTime = next;
                      setCurrentTime(next);
                    }
                  }}
                >
                  {Array.from({ length: 42 }).map((_, i) => {
                    const pct = i / 42;
                    const played = pct <= currentTime / (duration || 238);
                    const playedColor = pct < 0.35 ? "bg-[#4FDAF1]" : pct < 0.7 ? "bg-[#F79C09]" : "bg-[#E26B0B]";
                    const height = Math.round(
                      10 + Math.sin(i * 0.5) * 12 + ((i * 3) % 8),
                    );
                    return (
                      <span
                        key={i}
                        aria-hidden
                        style={{ height: `${height}px` }}
                        className={cn(
                          "flex-1 rounded-full transition-colors",
                          played ? playedColor : "bg-border",
                        )}
                      />
                    );
                  })}
                </div>

                <span className="w-10 shrink-0 text-left font-mono text-xs text-muted-foreground sm:w-12">
                  -{formatTime(Math.max(0, (duration || 238) - currentTime))}
                </span>

                <a
                  href="/audio/insurance-qa.mp3"
                  download
                  className="hidden size-8 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:text-foreground sm:flex"
                  title="Download call audio"
                >
                  <Download className="size-4" />
                </a>
              </div>

              {/* Pass/fail QA metrics */}
              <div className="grid grid-cols-2 gap-px overflow-hidden rounded-2xl border border-border bg-border sm:grid-cols-4">
                {[
                  { value: "1/1", label: "Criteria met", cls: "text-gradient-cool" },
                  { value: "82%", label: "Relevance", cls: "text-gradient-brand" },
                  { value: "100%", label: "Tool calls", cls: "text-gradient-cool" },
                  { value: "84%", label: "Obedience", cls: "text-gradient-warm" },
                ].map((m) => (
                  <div
                    key={m.label}
                    className="flex flex-col items-start bg-card px-5 py-3.5"
                  >
                    <span className={cn("text-2xl font-bold tracking-tight sm:text-3xl", m.cls)}>
                      {m.value}
                    </span>
                    <span className="text-xs text-muted-foreground">{m.label}</span>
                  </div>
                ))}
              </div>

              {/* Flagged issues */}
              <div className="space-y-3">
                <div className="flex items-baseline justify-between px-1">
                  <h4 className="text-sm font-semibold text-foreground">
                    Issues across this call
                  </h4>
                  <span className="rounded-full border border-[#E26B0B]/30 bg-[#E26B0B]/10 px-2.5 py-0.5 text-xs font-semibold text-[#E26B0B]">
                    2 flagged
                  </span>
                </div>

                <div className="divide-y divide-border overflow-hidden rounded-2xl border border-border bg-card">
                  {[
                    {
                      tag: "Hallucination",
                      tagColor: "border-[#E26B0B]/40 bg-[#E26B0B]/10 text-[#E26B0B]",
                      dotColor: "bg-[#E26B0B]",
                      title: "Misinformed about policy",
                      body: "Agent provided incorrect information about car pickups and dropoffs, deviating from the script.",
                    },
                    {
                      tag: "Interruptions",
                      tagColor: "border-[#F79C09]/40 bg-[#F79C09]/10 text-[#F79C09]",
                      dotColor: "bg-[#F79C09]",
                      title: "Speaking over the customer",
                      body: "Agent spoke over the customer twice, and did not wait for a response once.",
                    },
                  ].map((issue) => (
                    <div
                      key={issue.tag}
                      className="flex flex-col gap-1.5 p-4 sm:p-5"
                    >
                      <div className="flex flex-wrap items-center gap-2">
                        <span className={cn("inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[10px] font-bold uppercase tracking-wider", issue.tagColor)}>
                          <span className={cn("size-1.5 rounded-full", issue.dotColor)} />
                          {issue.tag}
                        </span>
                        <h5 className="text-sm font-semibold text-foreground">
                          {issue.title}
                        </h5>
                      </div>
                      <p className="text-xs leading-relaxed text-muted-foreground">
                        {issue.body}
                      </p>
                    </div>
                  ))}
                </div>
              </div>
            </motion.div>
          )}

          {tab === "analytics" && (
            <motion.div
              key="analytics"
              role="tabpanel"
              id="qa-panel-analytics"
              aria-labelledby="qa-tab-analytics"
              initial={{ opacity: 0, y: reduce ? 0 : 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: reduce ? 0 : -10 }}
              transition={panelTransition}
              className="space-y-6"
            >
              <AnalyticsPanel />
            </motion.div>
          )}

          {tab === "alerts" && (
            <motion.div
              key="alerts"
              role="tabpanel"
              id="qa-panel-alerts"
              aria-labelledby="qa-tab-alerts"
              initial={{ opacity: 0, y: reduce ? 0 : 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: reduce ? 0 : -10 }}
              transition={panelTransition}
              className="space-y-5"
            >
              <AlertsPanel reduce={!!reduce} />
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}

/* -------------------------------------------------------------------------- */
/* Analytics                                                                  */
/* -------------------------------------------------------------------------- */

const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const;

type Series = {
  name: string;
  values: number[];
  color: string;
  dash?: string;
  area?: boolean;
};

const SERIES: Series[] = [
  {
    name: "Relevance",
    values: [78, 80, 79, 83, 85, 84, 88],
    color: "#4FDAF1",
    area: true,
  },
  {
    name: "Obedience",
    values: [71, 74, 77, 75, 80, 82, 85],
    color: "#67B7E7",
  },
  {
    name: "Latency score",
    values: [64, 66, 63, 70, 72, 74, 78],
    color: "#E26B0B",
    dash: "5 4",
  },
];

// Chart geometry (unitless viewBox, scales to width).
const CW = 600;
const PLOT_TOP = 22;
const PLOT_BOTTOM = 176;
const PAD_X = 26;

const xFor = (i: number) => PAD_X + (i * (CW - PAD_X * 2)) / (DAYS.length - 1);
const yFor = (v: number) => PLOT_TOP + (1 - v / 100) * (PLOT_BOTTOM - PLOT_TOP);

const linePath = (values: number[]) =>
  values
    .map((v, i) => `${i === 0 ? "M" : "L"}${xFor(i).toFixed(1)},${yFor(v).toFixed(1)}`)
    .join(" ");

const areaPath = (values: number[]) =>
  `${linePath(values)} L${xFor(values.length - 1).toFixed(1)},${PLOT_BOTTOM} L${xFor(0).toFixed(1)},${PLOT_BOTTOM} Z`;

function AnalyticsPanel() {
  const kpis = [
    { value: "99.4%", label: "Pass rate", cls: "text-gradient-cool" },
    { value: "1.2s", label: "Avg latency", cls: "text-gradient-warm" },
    { value: "92%", label: "Resolution rate", cls: "text-gradient-brand" },
    { value: "3,412", label: "Calls scored", cls: "text-foreground" },
  ];

  return (
    <>
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <h3 className="font-display text-lg font-semibold text-foreground">
            Trends · last 7 days
          </h3>
          <p className="mt-0.5 text-xs text-muted-foreground">
            Per-metric performance across all scored calls
          </p>
        </div>
        <span className="rounded-full border border-border px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground">
          Sample data
        </span>
      </div>

      {/* Legend */}
      <div className="flex flex-wrap gap-4 text-xs text-muted-foreground">
        {SERIES.map((s) => (
          <span key={s.name} className="flex items-center gap-2">
            <svg width="22" height="8" viewBox="0 0 22 8">
              <line
                x1="1"
                y1="4"
                x2="21"
                y2="4"
                stroke={s.color}
                strokeWidth={s.area ? 2.5 : 2}
                strokeLinecap="round"
                strokeDasharray={s.dash}
              />
            </svg>
            <span className="font-medium text-foreground">{s.name}</span>
          </span>
        ))}
      </div>

      {/* Chart */}
      <div className="w-full text-foreground">
        <svg
          viewBox={`0 0 ${CW} 200`}
          className="h-auto w-full"
          fill="none"
          role="img"
          aria-label="Line chart of relevance, obedience, and latency scores over the last seven days"
        >
          <defs>
            <linearGradient id="qaAreaFill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#4FDAF1" stopOpacity="0.22" />
              <stop offset="100%" stopColor="#4FDAF1" stopOpacity="0" />
            </linearGradient>
          </defs>

          {/* Horizontal grid lines at 25 / 50 / 75 */}
          {[25, 50, 75].map((g) => (
            <line
              key={g}
              x1={PAD_X}
              y1={yFor(g)}
              x2={CW - PAD_X}
              y2={yFor(g)}
              stroke="currentColor"
              strokeWidth="1"
              strokeDasharray="3 4"
              className="text-border"
            />
          ))}

          {/* Area under the primary series */}
          {SERIES.filter((s) => s.area).map((s) => (
            <path key={`${s.name}-area`} d={areaPath(s.values)} fill="url(#qaAreaFill)" />
          ))}

          {/* Series lines */}
          {SERIES.map((s) => (
            <path
              key={s.name}
              d={linePath(s.values)}
              stroke={s.color}
              strokeWidth={s.area ? 2.5 : 2}
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeDasharray={s.dash}
            />
          ))}

          {/* Endpoint markers */}
          {SERIES.map((s) => {
            const last = s.values.length - 1;
            return (
              <circle
                key={`${s.name}-dot`}
                cx={xFor(last)}
                cy={yFor(s.values[last])}
                r="3.5"
                fill={s.color}
              />
            );
          })}

          {/* X-axis day labels */}
          {DAYS.map((d, i) => (
            <text
              key={d}
              x={xFor(i)}
              y="196"
              textAnchor="middle"
              className="fill-muted-foreground"
              style={{ fontSize: "11px" }}
            >
              {d}
            </text>
          ))}
        </svg>
      </div>

      {/* KPI row */}
      <div className="grid grid-cols-2 gap-px overflow-hidden rounded-2xl border border-border bg-border sm:grid-cols-4">
        {kpis.map((k) => (
          <div key={k.label} className="flex flex-col items-start bg-card px-5 py-3.5">
            <span className={cn("text-2xl font-bold tracking-tight sm:text-[1.75rem]", k.cls)}>
              {k.value}
            </span>
            <span className="text-xs text-muted-foreground">{k.label}</span>
          </div>
        ))}
      </div>
    </>
  );
}

/* -------------------------------------------------------------------------- */
/* Alerts                                                                     */
/* -------------------------------------------------------------------------- */

type Severity = "high" | "medium" | "low" | "error";

type Alert = {
  icon: LucideIcon;
  title: string;
  body: string;
  time: string;
  severity: Severity;
};

const ALERTS: Alert[] = [
  {
    icon: Activity,
    title: "Latency spike detected",
    body: "Response time exceeded 2.5s on 3 calls in the billing queue.",
    time: "2m ago",
    severity: "high",
  },
  {
    icon: AlertTriangle,
    title: "Negative sentiment flagged",
    body: "Customer frustration detected mid-call before escalation.",
    time: "14m ago",
    severity: "medium",
  },
  {
    icon: ShieldAlert,
    title: "Compliance keyword missing",
    body: "Required disclosure was not spoken on a regulated call.",
    time: "38m ago",
    severity: "error",
  },
  {
    icon: TrendingDown,
    title: "Resolution rate dip",
    body: "Auto-resolution fell below 90% over the last rolling hour.",
    time: "1h ago",
    severity: "low",
  },
];

// Reference palette severity indicators
const dotClass: Record<Severity, string> = {
  high: "bg-[#E26B0B]",
  medium: "bg-[#F79C09]",
  low: "bg-[#67B7E7]",
  error: "bg-destructive",
};

const iconStyleClass: Record<Severity, string> = {
  high: "bg-[#E26B0B]/15 text-[#E26B0B] border border-[#E26B0B]/30",
  medium: "bg-[#F79C09]/15 text-[#F79C09] border border-[#F79C09]/30",
  low: "bg-[#67B7E7]/15 text-[#67B7E7] border border-[#67B7E7]/30",
  error: "bg-destructive/15 text-destructive border border-destructive/30",
};

function AlertsPanel({ reduce }: { reduce: boolean }) {
  return (
    <>
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h3 className="font-display text-lg font-semibold text-foreground">
            Live alerts
          </h3>
          <p className="mt-0.5 text-xs text-muted-foreground">
            Triggered rules across every active conversation
          </p>
        </div>
        <span className="inline-flex items-center gap-2 rounded-full border border-[#4FDAF1]/30 bg-[#4FDAF1]/10 px-2.5 py-1 text-[11px] font-semibold text-[#4FDAF1]">
          <span className="relative flex size-2">
            {!reduce && (
              <span className="absolute inline-flex size-full animate-ping motion-reduce:animate-none rounded-full bg-[#4FDAF1]/60" />
            )}
            <span className="relative inline-flex size-2 rounded-full bg-[#4FDAF1]" />
          </span>
          Live
        </span>
      </div>

      <ul className="divide-y divide-border overflow-hidden rounded-2xl border border-border bg-card">
        {ALERTS.map((a, i) => {
          const Icon = a.icon;
          return (
            <motion.li
              key={a.title}
              initial={{ opacity: 0, y: reduce ? 0 : 6 }}
              animate={{ opacity: 1, y: 0 }}
              transition={
                reduce ? { duration: 0 } : { duration: 0.24, delay: 0.05 + i * 0.06 }
              }
              className="flex items-start gap-3 p-4 transition-colors hover:bg-foreground/[0.02] sm:gap-4 sm:p-5"
            >
              <span
                className={cn("mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full shadow-2xs", iconStyleClass[a.severity])}
                aria-hidden
              >
                <Icon className="size-4" />
              </span>

              <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-2">
                  <span
                    className={cn("size-2 shrink-0 rounded-full", dotClass[a.severity])}
                    aria-hidden
                  />
                  <h4 className="text-sm font-semibold text-foreground">{a.title}</h4>
                </div>
                <p className="mt-1 text-xs leading-relaxed text-muted-foreground">
                  {a.body}
                </p>
              </div>

              <time className="shrink-0 pt-0.5 font-mono text-[11px] text-muted-foreground">
                {a.time}
              </time>
            </motion.li>
          );
        })}
      </ul>
    </>
  );
}
