import { useState, useEffect } from "react";
import { apiFetch } from "../hooks/useApi.js";

export default function CurfewClock({ curfew, timers, onCancelTimer, refetchCurfew }) {
  const [now, setNow] = useState(Date.now());
  const [showInput, setShowInput] = useState(false);
  const [customTime, setCustomTime] = useState("");

  useEffect(() => {
    const interval = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(interval);
  }, []);

  if (!curfew) return null;

  const getNextEvent = () => {
    const today = new Date();
    const [blockH, blockM] = curfew.blockTime.split(":").map(Number);
    const [unblockH, unblockM] = curfew.unblockTime.split(":").map(Number);

    const blockToday = new Date(today);
    blockToday.setHours(blockH, blockM, 0, 0);

    const unblockTomorrow = new Date(today);
    unblockTomorrow.setDate(unblockTomorrow.getDate() + 1);
    unblockTomorrow.setHours(unblockH, unblockM, 0, 0);

    const unblockToday = new Date(today);
    unblockToday.setHours(unblockH, unblockM, 0, 0);

    if (now < unblockToday.getTime()) {
      return { label: "RESTRICTED UNTIL", target: unblockToday.getTime(), active: true };
    } else if (now < blockToday.getTime()) {
      return { label: "CURFEW BEGINS IN", target: blockToday.getTime(), active: false };
    } else {
      return { label: "RESTRICTED UNTIL", target: unblockTomorrow.getTime(), active: true };
    }
  };

  const formatCountdown = (ms) => {
    const totalSec = Math.max(0, Math.floor(ms / 1000));
    const h = Math.floor(totalSec / 3600);
    const m = Math.floor((totalSec % 3600) / 60);
    const s = totalSec % 60;
    return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
  };

  const handleOverride = async (minutes) => {
    await apiFetch("/curfew/override", {
      method: "POST",
      body: JSON.stringify({ minutes }),
    });
    refetchCurfew();
    setShowInput(false);
    setCustomTime("");
  };

  const event = curfew.enabled ? getNextEvent() : null;
  const activeTimers = (timers || []).filter((t) => t.remainingMs > 0);

  return (
    <div className="glass-card p-6 flex flex-col h-full relative overflow-hidden">
      <div className="absolute -right-10 -top-10 w-40 h-40 bg-gold/5 rounded-full blur-3xl pointer-events-none" />
      
      <div className="flex items-center justify-between mb-6 z-10">
        <div className="flex items-center gap-2">
          <div className={`w-2 h-2 rounded-full ${curfew.enabled ? "bg-gold shadow-[0_0_8px_rgba(212,175,55,0.8)]" : "bg-cream-dark/30"}`} />
          <span className="text-cream-dark text-[0.7rem] tracking-[0.2em] uppercase font-bold">
            Estate Curfew
          </span>
        </div>
        <span className={`text-[0.6rem] px-2 py-0.5 rounded border border-gold/20 font-bold tracking-widest ${
          curfew.enabled ? "text-gold" : "text-cream-dark opacity-40"
        }`}>
          {curfew.enabled ? "ARMED" : "STANDBY"}
        </span>
      </div>

      {event ? (
        <div className="flex-1 flex flex-col justify-center items-center py-4 z-10">
          <span className={`text-[0.65rem] uppercase tracking-[0.3em] mb-4 ${event.active ? "text-blockRed font-bold" : "text-cream-dark"}`}>
            {event.label}
          </span>
          <span className="font-serif text-5xl md:text-6xl font-bold text-cream tracking-[0.1em] tabular-nums drop-shadow-lg">
            {formatCountdown(event.target - now)}
          </span>
          
          <div className="mt-6 w-full">
            {showInput ? (
              <div className="flex gap-2">
                <input 
                  type="number" 
                  autoFocus
                  placeholder="MIN" 
                  className="manor-input w-full text-center font-mono"
                  value={customTime}
                  onChange={(e) => setCustomTime(e.target.value)}
                  onKeyDown={(e) => e.key === "Enter" && handleOverride(Number(customTime))}
                />
                <button 
                  onClick={() => handleOverride(Number(customTime))} 
                  className="btn-manor btn-manor-green px-4"
                  disabled={!customTime}
                >
                  SET
                </button>
                <button 
                  onClick={() => setShowInput(false)} 
                  className="btn-manor btn-manor-ghost px-3 text-blockRed"
                >
                  ✕
                </button>
              </div>
            ) : (
              <div className="flex gap-2 w-full">
                 <button onClick={() => handleOverride(30)} className="btn-manor btn-manor-ghost flex-1 text-[0.65rem] py-2">+30m</button>
                 <button onClick={() => handleOverride(60)} className="btn-manor btn-manor-ghost flex-1 text-[0.65rem] py-2">+1h</button>
                 <button onClick={() => setShowInput(true)} className="btn-manor btn-manor-ghost flex-1 text-[0.65rem] py-2">Custom</button>
              </div>
            )}
          </div>
        </div>
      ) : (
        <div className="flex-1 flex items-center justify-center py-10 opacity-30 z-10">
          <span className="text-sm italic tracking-widest uppercase">Curfew Disabled</span>
        </div>
      )}

      {activeTimers.length > 0 && (
        <div className="mt-6 pt-6 border-t border-cream/10 z-10">
          <span className="block text-[0.6rem] text-gold/60 uppercase tracking-[0.2em] mb-4 font-bold">
            Active Overrides
          </span>
          <div className="space-y-3">
            {activeTimers.map((t) => (
              <div key={t.id} className="flex items-center justify-between bg-viridian-dark/30 p-2 rounded-lg border border-cream/5">
                <div className="flex flex-col">
                  <span className="text-cream text-xs font-serif italic">{t.category}</span>
                  <span className="text-manor-green text-[0.65rem] font-mono font-bold tracking-wider">
                    {formatCountdown(t.remainingMs)}
                  </span>
                </div>
                <button
                  className="text-blockRed hover:text-white transition-colors p-1"
                  onClick={() => onCancelTimer(t.id)}
                >
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <line x1="18" y1="6" x2="6" y2="18" />
                    <line x1="6" y1="6" x2="18" y2="18" />
                  </svg>
                </button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
