import { useState } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { Plug, Power, PowerOff, Loader2, Wifi, WifiOff, Zap, Play } from 'lucide-react'; import { api } from '../api/client'; import type { SmartPlug } from '../api/client'; import { ConfirmModal } from './ConfirmModal'; interface SwitchbarPopoverProps { onClose: () => void; } function SwitchItem({ plug }: { plug: SmartPlug }) { const queryClient = useQueryClient(); const [confirmAction, setConfirmAction] = useState<'on' | 'off' | null>(null); // Fetch current status const { data: status, isLoading: statusLoading } = useQuery({ queryKey: ['smart-plug-status', plug.id], queryFn: () => api.getSmartPlugStatus(plug.id), refetchInterval: 10000, // Refresh every 10 seconds when popover is open }); // Control mutation const controlMutation = useMutation({ mutationFn: (action: 'on' | 'off') => api.controlSmartPlug(plug.id, action), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['smart-plug-status', plug.id] }); }, }); const isOn = status?.state === 'ON'; const isReachable = status?.reachable ?? false; const isPending = controlMutation.isPending; // Check if this is a HA script entity const isScript = plug.plug_type === 'homeassistant' && plug.ha_entity_id?.startsWith('script.'); const handleConfirm = () => { if (confirmAction) { controlMutation.mutate(confirmAction); setConfirmAction(null); } }; return ( <>
{isScript ? ( ) : ( )}

{plug.name}

{isScript && ( Script )}
{statusLoading ? ( ) : isScript ? ( {isReachable ? 'Ready' : 'Offline'} ) : isReachable ? ( <> {status?.state || 'Unknown'} {status?.energy?.power !== null && status?.energy?.power !== undefined && ( <> | {Math.round(status.energy.power)}W )} ) : ( <> Offline )}
{isScript ? ( /* Script: single Run button */ ) : ( /* Regular: On/Off buttons */ <> )}
{confirmAction && ( setConfirmAction(null)} /> )} ); } export function SwitchbarPopover({ onClose }: SwitchbarPopoverProps) { // Fetch all smart plugs const { data: plugs, isLoading } = useQuery({ queryKey: ['smart-plugs'], queryFn: api.getSmartPlugs, }); // Filter to only show plugs with show_in_switchbar enabled const switchbarPlugs = plugs?.filter(p => p.show_in_switchbar) || []; return (
{/* Header */}

Smart Switches

{/* Content */}
{isLoading ? (
) : switchbarPlugs.length === 0 ? (

No switches in switchbar

Enable "Show in Switchbar" in Settings > Smart Plugs

) : (
{switchbarPlugs.map(plug => ( ))}
)}
); }