import { useState } from "react";
import { useApi, apiFetch } from "../hooks/useApi.js";
import CategoryCard from "../components/CategoryCard.jsx";
import CurfewClock from "../components/CurfewClock.jsx";
import BonusTimeDrawer from "../components/BonusTimeDrawer.jsx";
import RuleAssigner from "../components/RuleAssigner.jsx";

export default function ControlDashboard() {
  const { data: policies, loading, error, refetch } = useApi("/policies");
  const { data: curfew, refetch: refetchCurfew } = useApi("/curfew");
  const { data: timers, refetch: refetchTimers } = useApi("/timers");
  const [bonusCategory, setBonusCategory] = useState(null);
  const [assignCategory, setAssignCategory] = useState(null);

  const handleToggle = async (category, allowed) => {
    try {
      await apiFetch(`/policies/\${encodeURIComponent(category)}/toggle`, {
        method: "POST",
        body: JSON.stringify({ allowed }),
      });
      refetch();
    } catch (err) {
      console.error("Toggle failed:", err);
    }
  };

  const handleBonusTime = async (category, minutes) => {
    try {
      await apiFetch("/timers", {
        method: "POST",
        body: JSON.stringify({ category, minutes }),
      });
      refetch();
      refetchTimers();
      setBonusCategory(null);
    } catch (err) {
      console.error("Bonus time failed:", err);
    }
  };

  const handleCancelTimer = async (timerId) => {
    try {
      await apiFetch(`/timers/\${timerId}`, { method: "DELETE" });
      refetchTimers();
      refetch();
    } catch (err) {
      console.error("Cancel timer failed:", err);
    }
  };

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center py-40 gap-4">
        <div className="w-8 h-8 border-2 border-gold/30 border-t-gold rounded-full animate-spin" />
        <span className="text-gold/50 text-[0.6rem] tracking-[0.4em] uppercase font-bold">Initializing Systems...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="glass-card p-6 border-blockRed/30 bg-blockRed/5 mt-10">
        <div className="flex items-center gap-3 text-blockRed mb-2">
           <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
           <span className="font-bold tracking-widest text-xs uppercase">System Error</span>
        </div>
        <span className="text-cream/60 text-sm italic">{error}</span>
        <button onClick={refetch} className="block mt-4 text-gold text-[0.6rem] underline tracking-widest uppercase">Retry Connection</button>
      </div>
    );
  }

  const categories = policies ? Object.entries(policies) : [];

  return (
    <div className="space-y-8 pb-10">
      <header className="flex flex-col items-center pt-2">
        <div className="w-12 h-px bg-gold/30 mb-4" />
        <h1 className="font-serif text-3xl md:text-4xl font-bold text-cream tracking-tight text-center">
          Manor <span className="text-gold italic">BarkWho</span>
        </h1>
        <p className="text-[0.55rem] text-cream-dark tracking-[0.5em] uppercase mt-2 opacity-50 font-bold">Network Controller v1.0</p>
      </header>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        <div className="lg:col-span-7 space-y-6">
          <div className="flex items-center justify-between px-1">
             <h2 className="section-label m-0">Policy Overrides</h2>
             <button onClick={refetch} className="text-[0.55rem] text-gold/60 hover:text-gold tracking-[0.2em] uppercase transition-colors">Sync rules</button>
          </div>
          <div className="space-y-4">
            {categories.map(([name, config]) => (
              <CategoryCard
                key={name}
                name={name}
                config={config}
                timers={timers?.filter((t) => t.category === name) || []}
                onToggle={(allowed) => handleToggle(name, allowed)}
                onBonusTime={() => setBonusCategory(name)}
                onAssignRules={() => setAssignCategory(name)}
              />
            ))}
          </div>
        </div>

        <div className="lg:col-span-5 space-y-6">
          <h2 className="section-label px-1">Timeline & Status</h2>
          <CurfewClock
            curfew={curfew}
            timers={timers}
            onCancelTimer={handleCancelTimer}
            refetchCurfew={refetchCurfew}
          />
        </div>
      </div>

      {bonusCategory && (
        <BonusTimeDrawer
          category={bonusCategory}
          onSubmit={(minutes) => handleBonusTime(bonusCategory, minutes)}
          onClose={() => setBonusCategory(null)}
        />
      )}

      {assignCategory && (
        <RuleAssigner
          category={assignCategory}
          currentRuleIds={policies?.[assignCategory]?.ruleIds || []}
          onSave={async (ruleIds) => {
            await apiFetch(`/policies/\${encodeURIComponent(assignCategory)}/rules`, {
              method: "PUT",
              body: JSON.stringify({ ruleIds }),
            });
            refetch();
            setAssignCategory(null);
          }}
          onClose={() => setAssignCategory(null)}
        />
      )}
    </div>
  );
}
