import { useState } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { Plug, Power, PowerOff, Loader2, Wifi, WifiOff, Zap, Radio, Eye } 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'; // For MQTT plugs, consider reachable if we have power data const hasMqttData = plug.plug_type === 'mqtt' && (status?.energy?.power !== null && status?.energy?.power !== undefined); const isReachable = (status?.reachable ?? false) || hasMqttData; const isPending = controlMutation.isPending; const isMqtt = plug.plug_type === 'mqtt'; const handleConfirm = () => { if (confirmAction) { controlMutation.mutate(confirmAction); setConfirmAction(null); } }; return ( <>
{isMqtt ? ( ) : ( )}

{plug.name}

{statusLoading ? ( ) : isMqtt ? ( /* MQTT plugs show power and monitor-only indicator */ isReachable ? ( <> {Math.round(status?.energy?.power ?? 0)}W | Monitor ) : ( <> Waiting ) ) : isReachable ? ( <> {status?.state || 'Unknown'} {status?.energy?.power !== null && status?.energy?.power !== undefined && ( <> | {Math.round(status.energy.power)}W )} ) : ( <> Offline )}
{/* Hide on/off buttons for MQTT plugs (monitor-only) */} {!isMqtt && (
)}
{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 => ( ))}
)}
); }