"use client";

import { useEffect } from "react";
import { cn } from "@/lib/utils";
import { useVoiceCall, type VoiceCallTarget } from "@/hooks/useVoiceCall";
import {
  CarIcon,
  CloseIcon,
  PhoneIcon,
  MicIcon,
  MicOffIcon,
  AlertIcon,
  ShieldCheckIcon,
} from "@/app/components/icons";

// mm:ss for the live call timer.
function formatDuration(totalSeconds: number): string {
  const m = Math.floor(totalSeconds / 60)
    .toString()
    .padStart(2, "0");
  const s = (totalSeconds % 60).toString().padStart(2, "0");
  return `${m}:${s}`;
}

// Outgoing voice call to a vehicle owner. Mounted (keyed per target) by the app
// layout once the scan modal's "Request call" fires. Auto-starts the call via
// useVoiceCall and renders its phase: connecting -> ringing -> connected, plus
// the ended/failed terminal states with retry. Your number stays private — the
// connection is anonymised through Agora, never a direct phone dial.
export function VoiceCallModal({
  target,
  onClose,
}: {
  target: VoiceCallTarget;
  onClose: () => void;
}) {
  const {
    phase,
    note,
    muted,
    durationSeconds,
    hangUp,
    toggleMute,
    retry,
  } = useVoiceCall(target);

  const isLive =
    phase === "initiating" || phase === "ringing" || phase === "connected";
  const isRinging = phase === "initiating" || phase === "ringing";
  const isTerminal = phase === "ended" || phase === "failed";

  const statusLabel =
    phase === "initiating"
      ? "Connecting…"
      : phase === "ringing"
        ? "Ringing…"
        : phase === "connected"
          ? formatDuration(durationSeconds)
          : phase === "failed"
            ? "Call failed"
            : "Call ended";

  // While the call is live, Escape hangs up (and shows the ended state) rather
  // than silently closing; once terminal it dismisses. Lock body scroll meanwhile.
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key !== "Escape") return;
      if (isLive) hangUp();
      else onClose();
    }
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [isLive, hangUp, onClose]);

  // Backdrop click: hang up if live, otherwise close.
  function onBackdrop() {
    if (isLive) hangUp();
    else onClose();
  }

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="voice-call-title"
      className="fixed inset-0 z-50 flex items-end justify-center p-4 sm:items-center"
    >
      {/* Backdrop */}
      <button
        type="button"
        aria-label="Close"
        onClick={onBackdrop}
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
      />

      {/* Dialog */}
      <div className="glass animate-toast-in relative w-full max-w-sm overflow-hidden rounded-3xl">
        <div className="flex items-center justify-between gap-3 border-b border-white/8 px-6 py-5">
          <div className="flex items-center gap-3">
            <span className="grid h-10 w-10 place-items-center rounded-xl bg-brand/12 text-brand">
              <PhoneIcon className="h-5 w-5" />
            </span>
            <div>
              <h2
                id="voice-call-title"
                className="text-base font-bold text-white"
              >
                Voice call
              </h2>
              <p className="text-xs text-white/50">{statusLabel}</p>
            </div>
          </div>
          {/* Header close is only a shortcut once the call is over — during a live
              call use the End button so we always hang up cleanly. */}
          {isTerminal && (
            <button
              type="button"
              onClick={onClose}
              aria-label="Close"
              className="grid h-9 w-9 place-items-center rounded-lg text-white/50 transition hover:bg-white/5 hover:text-white"
            >
              <CloseIcon className="h-5 w-5" />
            </button>
          )}
        </div>

        <div className="flex flex-col items-center gap-6 px-6 py-8">
          {/* Avatar — pulses while ringing/connecting */}
          <div className="relative grid place-items-center">
            {isRinging && (
              <span className="absolute inline-flex h-24 w-24 animate-ping rounded-full bg-brand/30" />
            )}
            <span
              className={cn(
                "relative grid h-24 w-24 place-items-center rounded-full",
                phase === "failed"
                  ? "bg-danger/15 text-danger"
                  : "bg-brand/15 text-brand",
              )}
            >
              {phase === "failed" ? (
                <AlertIcon className="h-10 w-10" />
              ) : (
                <CarIcon className="h-10 w-10" />
              )}
            </span>
          </div>

          {/* Identity + status */}
          <div className="flex flex-col items-center gap-1 text-center">
            <span className="text-xl font-bold tracking-wide text-white">
              {target.vehicleNumber}
            </span>
            <span
              className={cn(
                "text-sm",
                phase === "connected"
                  ? "font-semibold text-success"
                  : phase === "failed"
                    ? "text-danger"
                    : "text-white/55",
              )}
            >
              {phase === "connected"
                ? `Connected · ${formatDuration(durationSeconds)}`
                : statusLabel}
            </span>
            {note && <p className="mt-1 text-xs text-white/50">{note}</p>}
          </div>

          {/* Privacy reassurance (hidden once the call failed) */}
          {phase !== "failed" && (
            <p className="flex items-center gap-1.5 text-center text-xs text-white/40">
              <ShieldCheckIcon className="h-4 w-4 shrink-0" />
              Your number stays private — connected anonymously via VehCall.
            </p>
          )}

          {/* Controls */}
          {isLive ? (
            <div className="flex items-center justify-center gap-6">
              <button
                type="button"
                onClick={toggleMute}
                aria-pressed={muted}
                aria-label={muted ? "Unmute" : "Mute"}
                className={cn(
                  "grid h-14 w-14 place-items-center rounded-full border transition",
                  muted
                    ? "border-transparent bg-white/90 text-black"
                    : "border-white/15 bg-white/5 text-white hover:bg-white/10",
                )}
              >
                {muted ? (
                  <MicOffIcon className="h-6 w-6" />
                ) : (
                  <MicIcon className="h-6 w-6" />
                )}
              </button>
              <button
                type="button"
                onClick={hangUp}
                aria-label="End call"
                className="grid h-16 w-16 place-items-center rounded-full bg-danger text-white shadow-lg shadow-danger/30 transition hover:bg-danger/90"
              >
                <PhoneIcon className="h-7 w-7 rotate-[135deg]" />
              </button>
            </div>
          ) : (
            <div className="flex w-full gap-3">
              <button
                type="button"
                onClick={retry}
                className="btn-primary flex-1 text-sm"
              >
                <PhoneIcon className="h-4 w-4" />
                Call again
              </button>
              <button
                type="button"
                onClick={onClose}
                className="btn-ghost flex-1 text-sm"
              >
                Close
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
