"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

const TIMER_OPTIONS = [
  { label: "30 min", value: 30 * 60 },
  { label: "1 hour", value: 60 * 60 },
  { label: "2 hours", value: 2 * 60 * 60 },
  { label: "4 hours", value: 4 * 60 * 60 },
];

export default function SafetyCheckinPage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [timerDuration, setTimerDuration] = useState<number | null>(null);
  const [secondsLeft, setSecondsLeft] = useState(0);
  const [expired, setExpired] = useState(false);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const audioRef = useRef<HTMLAudioElement | null>(null);

  useEffect(() => {
    if (status === "unauthenticated") router.push("/login");
  }, [status, router]);

  const clearTimer = useCallback(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
  }, []);

  function startTimer(seconds: number) {
    clearTimer();
    setTimerDuration(seconds);
    setSecondsLeft(seconds);
    setExpired(false);

    intervalRef.current = setInterval(() => {
      setSecondsLeft((prev) => {
        if (prev <= 1) {
          clearTimer();
          setExpired(true);
          // Play alert sound
          try {
            audioRef.current = new Audio(
              "data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQ=="
            );
            audioRef.current.play().catch(() => {});
          } catch {}
          // Try notification
          if (typeof Notification !== "undefined" && Notification.permission === "granted") {
            new Notification("Safety Check-in Alert", {
              body: "Your check-in timer has expired! Are you safe?",
            });
          }
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  }

  function handleSafe() {
    clearTimer();
    setTimerDuration(null);
    setSecondsLeft(0);
    setExpired(false);
  }

  useEffect(() => {
    // Request notification permission on mount
    if (typeof Notification !== "undefined" && Notification.permission === "default") {
      Notification.requestPermission();
    }
    return () => clearTimer();
  }, [clearTimer]);

  function formatTime(secs: number) {
    const h = Math.floor(secs / 3600);
    const m = Math.floor((secs % 3600) / 60);
    const s = secs % 60;
    if (h > 0) {
      return `${h}:${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
    }
    return `${m}:${s.toString().padStart(2, "0")}`;
  }

  if (status === "loading") {
    return <div className="text-text-muted p-8 text-center">Loading...</div>;
  }

  if (!session) return null;

  return (
    <div className="max-w-md mx-auto space-y-8 py-8">
      <div className="text-center">
        <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gold/10 mb-4">
          <svg className="w-8 h-8 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
        </div>
        <h1 className="text-2xl font-bold text-text">Safety Check-in</h1>
        <p className="text-text-muted text-sm mt-2">
          Set a timer for your meeting. If you don&apos;t check in, an alert will sound.
        </p>
      </div>

      {!timerDuration && !expired && (
        <div className="bg-surface rounded-xl border border-surface-light p-6 space-y-4">
          <p className="text-sm text-text-muted font-medium">Select a duration:</p>
          <div className="grid grid-cols-2 gap-3">
            {TIMER_OPTIONS.map((opt) => (
              <button
                key={opt.value}
                onClick={() => startTimer(opt.value)}
                className="bg-gold/10 hover:bg-gold/20 text-gold border border-gold/20 rounded-lg py-3 font-semibold transition-all duration-200"
              >
                {opt.label}
              </button>
            ))}
          </div>
        </div>
      )}

      {timerDuration && !expired && (
        <div className="bg-surface rounded-xl border border-surface-light p-6 text-center space-y-6">
          <p className="text-text-muted text-sm">Timer running</p>
          <p className="text-5xl font-mono font-bold text-text">
            {formatTime(secondsLeft)}
          </p>
          <button
            onClick={handleSafe}
            className="w-full bg-green-600 hover:bg-green-700 text-white font-semibold py-3 rounded-lg transition-colors text-lg"
          >
            I&apos;m Safe
          </button>
        </div>
      )}

      {expired && (
        <div className="bg-red-900/30 border border-red-500/30 rounded-xl p-6 text-center space-y-4 animate-pulse">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-red-600/20 mx-auto">
            <svg className="w-8 h-8 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
          </div>
          <h2 className="text-xl font-bold text-red-400">Timer Expired!</h2>
          <p className="text-red-300 text-sm">Are you safe? Please check in.</p>
          <div className="flex gap-3">
            <button
              onClick={handleSafe}
              className="flex-1 bg-green-600 hover:bg-green-700 text-white font-semibold py-3 rounded-lg transition-colors"
            >
              I&apos;m Safe
            </button>
            <a
              href="tel:911"
              className="flex-1 bg-red-600 hover:bg-red-700 text-white font-semibold py-3 rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
              </svg>
              Emergency
            </a>
          </div>
        </div>
      )}

      <div className="bg-surface rounded-xl border border-surface-light p-4">
        <h3 className="text-sm font-semibold text-text mb-2">Safety Tips</h3>
        <ul className="text-xs text-text-muted space-y-1.5">
          <li>- Always tell a trusted friend where you are going</li>
          <li>- Meet in a public place first</li>
          <li>- Trust your instincts — if something feels wrong, leave</li>
          <li>- Keep your phone charged and accessible</li>
        </ul>
      </div>
    </div>
  );
}
