'use client'

import { useState, useEffect } from 'react'

interface DeviceCardProps {
  id: string
  name: string
  icon: string
  entityId?: string
  domain?: string
  initialState: boolean
  isMock?: boolean
  extraInfo?: string
}

export default function DeviceCard({
  id, name, icon, entityId, domain, initialState, isMock = false, extraInfo,
}: DeviceCardProps) {
  const [isOn, setIsOn] = useState(initialState)
  const [synced, setSynced] = useState(false)
  const [loading, setLoading] = useState(false)

  // Sync from HA only once — when real data first arrives (not mock default)
  useEffect(() => {
    if (!synced && !isMock) {
      setIsOn(initialState)
      setSynced(true)
    }
  }, [initialState, isMock, synced])

  const toggle = async () => {
    const next = !isOn
    setIsOn(next) // optimistic

    if (!isMock && entityId && domain) {
      setLoading(true)
      try {
        await fetch('/api/ha', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            domain,
            service: next ? 'turn_on' : 'turn_off',
            entity_id: entityId,
          }),
        })
      } catch {
        setIsOn(!next)
      } finally {
        setLoading(false)
      }
    }
  }

  const accent = '#00d4ff'

  return (
    <div style={{
      background: isOn ? 'rgba(0,212,255,0.07)' : 'rgba(255,255,255,0.04)',
      border: isOn ? '1px solid rgba(0,212,255,0.25)' : '1px solid rgba(255,255,255,0.08)',
      borderRadius: 18,
      padding: '18px 16px 16px',
      minHeight: 140,
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'space-between',
      transition: 'background 0.25s ease, border-color 0.25s ease',
      boxShadow: isOn ? '0 0 24px rgba(0,212,255,0.06)' : 'none',
    }}>
      {/* Top: icon + toggle */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div style={{
          width: 42, height: 42, borderRadius: 12,
          background: isOn ? 'rgba(0,212,255,0.15)' : 'rgba(255,255,255,0.06)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 20,
          transition: 'background 0.25s ease',
          boxShadow: isOn ? '0 0 16px rgba(0,212,255,0.25)' : 'none',
        }}>
          {icon}
        </div>

        <button
          onClick={toggle}
          disabled={loading}
          style={{
            width: 52, height: 30, borderRadius: 15,
            background: isOn ? `linear-gradient(90deg, #00b4d8, #00d4ff)` : 'rgba(255,255,255,0.1)',
            position: 'relative', border: 'none', cursor: 'pointer',
            flexShrink: 0, touchAction: 'manipulation',
            WebkitTapHighlightColor: 'transparent',
            transition: 'background 0.25s ease',
            opacity: loading ? 0.6 : 1,
            boxShadow: isOn ? '0 0 10px rgba(0,212,255,0.4)' : 'none',
          }}
        >
          <span style={{
            position: 'absolute', top: 4,
            left: isOn ? 26 : 4,
            width: 22, height: 22, borderRadius: '50%',
            background: '#fff',
            boxShadow: '0 1px 4px rgba(0,0,0,0.3)',
            transition: 'left 0.22s ease',
            display: 'block',
          }} />
        </button>
      </div>

      {/* Bottom: name + status */}
      <div>
        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-primary)', lineHeight: 1.3 }}>
          {name}
        </div>
        <div style={{ fontSize: 12, color: isOn ? accent : 'var(--text-secondary)', marginTop: 3 }}>
          {isOn ? 'Включён' : 'Выключен'}
          {extraInfo && isOn ? ` · ${extraInfo}` : ''}
        </div>
      </div>
    </div>
  )
}
