"use client"

import { useState } from "react"
import { toggleNotificationAction } from "@/app/admin/actions"

export function NotificationToggle({ userId, enabled, canEdit }: { userId: string, enabled: boolean, canEdit: boolean }) {
  const [isOn, setIsOn] = useState(enabled)
  const [isProcessing, setIsProcessing] = useState(false)

  const handleToggle = async () => {
    if (!canEdit || isProcessing) return
    setIsProcessing(true)
    const nextState = !isOn
    
    // Optimistic trigger
    setIsOn(nextState)
    
    try {
      await toggleNotificationAction(userId, nextState)
    } catch (err) {
      alert("Nu am putut salva setarea.")
      setIsOn(!nextState)
    } finally {
      setIsProcessing(false)
    }
  }

  return (
    <button
      onClick={handleToggle}
      disabled={!canEdit || isProcessing}
      style={{
        width: "44px",
        height: "24px",
        background: isOn ? "var(--success)" : "var(--border-color)",
        borderRadius: "999px",
        position: "relative",
        border: "none",
        cursor: canEdit && !isProcessing ? "pointer" : "default",
        opacity: canEdit ? (isProcessing ? 0.7 : 1) : 0.5,
        transition: "background 0.2s"
      }}
      title={isOn ? "E-mailurile sunt pornite" : "E-mailurile sunt oprite"}
    >
      <div 
        style={{
          width: "18px",
          height: "18px",
          background: "white",
          borderRadius: "50%",
          position: "absolute",
          top: "3px",
          left: isOn ? "23px" : "3px",
          transition: "left 0.2s",
          boxShadow: "0 1px 3px rgba(0,0,0,0.1)"
        }}
      />
    </button>
  )
}
