"use client";

import { useState } from "react";
import { type PowerData } from "../lib/getPower";
import PowerCard from "./PowerCard";

interface PowerGridProps {
	power: PowerData | null;
	onRefresh: () => void;
}

export default function PowerGrid({ power, onRefresh }: PowerGridProps) {
	const [toggling, setToggling] = useState<string | null>(null);

	const server = power?.devices.find((d) => d.name === "server") ?? null;
	const desktop = power?.devices.find((d) => d.name === "desktop") ?? null;

	const handleToggle = async (deviceName: string, on: boolean) => {
		setToggling(deviceName);
		try {
			const action = on ? "on" : "off";
			const res = await fetch(`/api/power/${deviceName}/${action}`, { method: "POST" });
			if (!res.ok) console.error(`Toggle ${deviceName} failed:`, res.status);
			else onRefresh();
		} finally {
			setToggling(null);
		}
	};

	return (
		<div className="grid grid-cols-1 md:grid-cols-2 gap-3.5 mb-11">
			<PowerCard
				device={server}
				label="Server"
				delay={0}
				toggling={toggling === "server"}
				onToggle={(on) => handleToggle("server", on)}
			/>
			<PowerCard
				device={desktop}
				label="Desktop"
				delay={60}
				toggling={toggling === "desktop"}
				onToggle={(on) => handleToggle("desktop", on)}
			/>
		</div>
	);
}
