// frontend/src/pages/bellcloud/devices/tabs/BellsTab.jsx
// Bell Mechanisms tab — displays Bell Commander/Guard status, connected bell count,
// master switch, and per-bell glass cards with output, timing, size, and strike stats.

import { useState, useCallback } from 'react'
import api from '@/lib/api'
import { useToast } from '@/components/ui/Toast'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import Icon from '@/components/ui/Icon'
import ConfirmDialog from '@/components/ui/ConfirmDialog'

import certificationImg from '@/assets/striker-mechanisms/certification.png'
import strikerSize1 from '@/assets/striker-mechanisms/size-1.jpg'
import strikerSize2 from '@/assets/striker-mechanisms/size-2.jpg'
import strikerSize3 from '@/assets/striker-mechanisms/size-3.jpg'
import strikerSize4 from '@/assets/striker-mechanisms/size-4.jpg'
import strikerSize5 from '@/assets/striker-mechanisms/size-5.jpg'
import strikerSize6 from '@/assets/striker-mechanisms/size-6.jpg'

const STRIKER_IMAGES = { 1: strikerSize1, 2: strikerSize2, 3: strikerSize3, 4: strikerSize4, 5: strikerSize5, 6: strikerSize6 }

// ─── Timing → Size mapping (from archive) ────────────────────────────────────

function getStrikerSize(ms) {
  if (!Number.isFinite(ms)) return null
  if (ms <= 89)  return 1
  if (ms <= 94)  return 2
  if (ms <= 99)  return 3
  if (ms <= 109) return 4
  if (ms <= 119) return 5
  return 6
}

const ORDINAL_NAMES = [
  'First', 'Second', 'Third', 'Fourth', 'Fifth',
  'Sixth', 'Seventh', 'Eighth', 'Ninth', 'Tenth',
]

// ─── Indicator pill ───────────────────────────────────────────────────────────

function Indicator({ label, value, yesLabel = 'Operational', noLabel = 'Disabled' }) {
  const isUnknown = typeof value !== 'boolean'
  const variant   = isUnknown ? 'neutral' : value ? 'success' : 'danger'
  const text      = isUnknown ? 'Unknown' : value ? yesLabel : noLabel
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)', alignItems: 'flex-start' }}>
      <span style={{
        fontSize: 'var(--font-size-xs)',
        fontWeight: 'var(--font-weight-semibold)',
        color: 'var(--color-text-muted)',
        textTransform: 'uppercase',
        letterSpacing: 'var(--tracking-wide)',
      }}>
        {label}
      </span>
      <StatusBadge variant={variant}>{text}</StatusBadge>
    </div>
  )
}

// ─── Bell card (glass) ────────────────────────────────────────────────────────

const BELL_GLASS_CARD = {
  background: 'rgba(28, 32, 38, 0.30)',
  backdropFilter: 'var(--blur-modal)',
  WebkitBackdropFilter: 'var(--blur-modal)',
  border: '1px solid var(--color-border)',
  borderRadius: 'var(--radius-xl)',
  boxShadow: 'var(--shadow-card), var(--shadow-md)',
  display: 'flex',
  flexDirection: 'column',
  breakInside: 'avoid',
}

const SPEC_TILE = {
  background: 'rgba(28, 32, 38, 0.40)',
  backdropFilter: 'var(--blur-modal)',
  WebkitBackdropFilter: 'var(--blur-modal)',
  borderRadius: 'var(--radius-md)',
  padding: 'var(--space-3)',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center',
  gap: 'var(--space-1)',
  textAlign: 'center',
  flex: 1,
}

function BellCard({ index, output, hammingMs, strikeCount, requestingCounters, isBellSystems }) {
  const ordinal     = ORDINAL_NAMES[index] ?? `${index + 1}th`
  const strikerSize = getStrikerSize(hammingMs)
  const isDisabled  = Number.isFinite(output) && Number(output) === 0
  const [hovered, setHovered] = useState(false)

  const strikerImg = strikerSize ? STRIKER_IMAGES[strikerSize] : null

  return (
    <article
      style={{
        ...BELL_GLASS_CARD,
        boxShadow: hovered
          ? 'var(--shadow-card), var(--shadow-lg), 0 0 0 1px rgba(192, 193, 255, 0.35), 0 0 32px rgba(192, 193, 255, 0.22)'
          : 'var(--shadow-card), var(--shadow-md)',
        transition: 'box-shadow 0.25s ease',
      }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >

      {/* Hero image — fades into card body */}
      <div style={{
        position: 'relative',
        height: '220px',
        background: 'rgba(10, 14, 20, 0.80)',
        overflow: 'hidden',
        flexShrink: 0,
        borderRadius: 'var(--radius-xl) var(--radius-xl) 0 0',
      }}>
        {strikerImg ? (
          <img
            src={strikerImg}
            alt={`Size ${strikerSize} striker mechanism`}
            style={{
              width: '100%',
              height: '100%',
              objectFit: 'cover',
              objectPosition: 'center bottom',
              opacity: 1,
              transform: hovered ? 'scale(1.15)' : 'scale(1.05)',
              transition: 'transform 0.4s ease',
            }}
          />
        ) : (
          <div style={{
            width: '100%',
            height: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            <Icon name="bell" size={48} color="var(--color-text-muted)" />
          </div>
        )}

        {/* Bottom fade — bleeds over the name below */}
        <div style={{
          position: 'absolute',
          inset: 0,
          background: 'linear-gradient(to top, rgba(28, 32, 38, 1) 0%, rgba(28, 32, 38, 0.55) 40%, transparent 70%)',
          pointerEvents: 'none',
        }} />

        {/* Name overlaid at the bottom of the image */}
        <div style={{
          position: 'absolute',
          bottom: 'var(--space-4)',
          left: 'var(--space-4)',
          right: 'var(--space-4)',
        }}>
          <h3 style={{
            fontFamily: 'var(--font-family-display)',
            letterSpacing: 'var(--tracking-tight)',
            color: 'var(--color-text-primary)',
            lineHeight: 1.2,
            margin: 0,
          }}>
            <span style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-medium)' }}>
              {strikerSize ? 'Size ' : (isBellSystems ? 'Striker' : `${ordinal} Bell`)}
            </span>
            {strikerSize && (
              <span style={{ fontSize: 'var(--font-size-xl)', fontWeight: 'var(--font-weight-bold)' }}>
                {strikerSize}
              </span>
            )}
            {strikerSize && (
              <span style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-medium)' }}>
                {' Striker'}
              </span>
            )}
          </h3>
          <p style={{
            fontSize: 'var(--font-size-sm)',
            color: 'var(--color-text-muted)',
            marginTop: '2px',
          }}>
            {ordinal} Bell
          </p>
        </div>
      </div>

      {/* Card body */}
      <div style={{ padding: 'var(--space-4)', display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', flex: 1 }}>

        {/* Spec tiles: Output · Timing · Size */}
        <div style={{ display: 'flex', gap: 'var(--space-2)' }}>
          <div style={SPEC_TILE}>
            <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>
              Output
            </span>
            <span style={{ fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-bold)', color: isDisabled ? 'var(--color-danger)' : 'var(--color-text-secondary)' }}>
              {isDisabled ? 'Disabled' : Number.isFinite(output) ? `Out ${output}` : '—'}
            </span>
          </div>
          <div style={SPEC_TILE}>
            <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>
              Timing
            </span>
            <span style={{ fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-bold)', color: 'var(--color-text-secondary)', fontFamily: 'var(--font-family-mono)' }}>
              {Number.isFinite(hammingMs) ? `${hammingMs} ms` : '—'}
            </span>
          </div>
          <div style={SPEC_TILE}>
            <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>
              Size
            </span>
            <span style={{ fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-bold)', color: 'var(--color-text-secondary)' }}>
              {strikerSize ? `Size ${strikerSize}` : '—'}
            </span>
          </div>
        </div>

        {/* Strike count footer */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
            <span style={{
              fontSize: 'var(--font-size-xs)',
              fontWeight: 'var(--font-weight-semibold)',
              color: 'var(--color-text-more-muted)',
              textTransform: 'uppercase',
              letterSpacing: 'var(--tracking-wide)',
              opacity: 0.7,
            }}>
              Lifetime Strikes
            </span>
            {requestingCounters ? (
              <span style={{ fontSize: 'var(--font-size-base)', color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)' }}>…</span>
            ) : Number.isFinite(strikeCount) ? (
              <span style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', fontFamily: 'var(--font-family-mono)' }}>
                {strikeCount.toLocaleString()}
              </span>
            ) : (
              <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
                No data available
              </span>
            )}
          </div>
          {isBellSystems && (
            <img
              src={certificationImg}
              alt="BellSystems Certified"
              style={{ width: 36, height: 36, objectFit: 'contain', opacity: 0.90 }}
            />
          )}
        </div>

      </div>
    </article>
  )
}

// ─── BellsTab ─────────────────────────────────────────────────────────────────


export default function BellsTab({
  device,
  attr,
  canEdit,
  loadDevice,
  sendMqttCommand,
  onEditBellOutputs,
}) {
  const { toast } = useToast()

  const [togglingCommander, setTogglingCommander] = useState(false)
  const [requestingCounters, setRequestingCounters] = useState(false)
  const [liveCounters] = useState(null)
  const [confirmDisable, setConfirmDisable] = useState(false)

  // Derived data
  const bellOutputs   = attr?.bellOutputs  || []
  const hammerTimings = attr?.hammerTimings || []
  const totalBells    = attr?.totalBells    || 0
  const hasBells      = attr?.hasBells      ?? false
  const bellGuardOn   = attr?.bellGuardOn   ?? false

  // Request strike counters via MQTT
  const requestStrikeCounters = useCallback(async () => {
    if (!sendMqttCommand) return
    setRequestingCounters(true)
    try {
      await sendMqttCommand('system_info', { action: 'report_status' })
    } finally {
      // Will be cleared when live data arrives, or after timeout
      setTimeout(() => setRequestingCounters(false), 8000)
    }
  }, [sendMqttCommand])

  // Toggle Bell Commander (master switch)
  const handleToggleCommander = async (newVal) => {
    setTogglingCommander(true)
    try {
      await api.put(`/devices/${device.id || device.device_id}`, {
        device_attributes: { hasBells: newVal },
      })
      await loadDevice()
      toast.success(
        newVal ? 'Bell Commander Enabled' : 'Bell Commander Disabled',
        newVal ? 'All bell mechanisms are now active.' : 'All bell mechanisms have been disabled.'
      )
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to update Bell Commander.')
    } finally {
      setTogglingCommander(false)
    }
  }

  const handleCommanderToggleRequest = () => {
    if (hasBells) {
      // Disabling — confirm first
      setConfirmDisable(true)
    } else {
      handleToggleCommander(true)
    }
  }

  const hasData = bellOutputs.length > 0

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>

      {/* ── Status overview bar ───────────────────────────────────────────── */}
      <div style={{
        background: 'rgba(28, 32, 38, 0.30)',
        backdropFilter: 'var(--blur-modal)',
        WebkitBackdropFilter: 'var(--blur-modal)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-xl)',
        boxShadow: 'var(--shadow-card)',
        padding: 'var(--space-5) var(--space-6)',
        display: 'flex',
        alignItems: 'center',
        flexWrap: 'wrap',
        gap: 'var(--space-6)',
      }}>
        {/* Indicators */}
        <div style={{ display: 'flex', gap: 'var(--space-12)', flex: 1, flexWrap: 'wrap' }}>
          <Indicator label="Bell Commander" value={hasBells}    yesLabel="Operational" noLabel="Disabled" />
          <Indicator label="Bell Guard"     value={bellGuardOn} yesLabel="Operational" noLabel="Disabled" />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)', alignItems: 'flex-start' }}>
            <span style={{
              fontSize: 'var(--font-size-xs)',
              fontWeight: 'var(--font-weight-semibold)',
              color: 'var(--color-text-muted)',
              textTransform: 'uppercase',
              letterSpacing: 'var(--tracking-wide)',
            }}>
              Connected Bells
            </span>
            <span style={{
              fontSize: 'var(--font-size-base)',
              fontWeight: 'var(--font-weight-semibold)',
              color: 'var(--color-text-primary)',
            }}>
              {Number.isFinite(totalBells) ? (totalBells === 1 ? '1 Bell' : `${totalBells} Bells`) : '—'}
            </span>
          </div>
        </div>

        {/* Actions */}
        {canEdit && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', flexShrink: 0 }}>
            {/* Master toggle */}
            <Button
              variant={hasBells ? 'danger' : 'success'}
              size="md"
              loading={togglingCommander}
              onClick={handleCommanderToggleRequest}
            >
              {hasBells ? 'Disable Commander' : 'Enable Commander'}
            </Button>

            {/* Edit Outputs */}
            <Button variant="primary" size="md" onClick={onEditBellOutputs}>
              Edit Outputs
            </Button>
          </div>
        )}
      </div>

      {/* ── Bell cards ────────────────────────────────────────────────────── */}
      {!hasData ? (
        /* Empty state */
        <div style={{
          background: 'rgba(28, 32, 38, 0.30)',
          backdropFilter: 'var(--blur-modal)',
          WebkitBackdropFilter: 'var(--blur-modal)',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-xl)',
          padding: 'var(--space-12)',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          gap: 'var(--space-4)',
          textAlign: 'center',
        }}>
          <div style={{
            width: 56,
            height: 56,
            borderRadius: 'var(--radius-full)',
            background: 'var(--color-bg-elevated)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            <Icon name="bell" size={24} color="var(--color-text-muted)" />
          </div>
          <div>
            <p style={{ fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-secondary)' }}>
              No Bell Mechanisms Configured
            </p>
            <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 'var(--space-1)' }}>
              Use Edit Outputs to assign bells and configure their output channels.
            </p>
          </div>
          {canEdit && (
            <Button variant="primary" size="sm" onClick={onEditBellOutputs}>
              Configure Bell Outputs
            </Button>
          )}
        </div>
      ) : (
        <div>
          {/* Strike counter refresh */}
          <div style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            marginBottom: 'var(--space-4)',
          }}>
            <h2 style={{
              fontFamily: 'var(--font-family-display)',
              fontSize: 'var(--font-size-xl)',
              fontWeight: 'var(--font-weight-semibold)',
              letterSpacing: 'var(--tracking-tight)',
              color: 'var(--color-text-primary)',
            }}>
              Bell Mechanisms
            </h2>
            <Button
              variant="ghost"
              size="sm"
              onClick={requestStrikeCounters}
              loading={requestingCounters}
            >
              Refresh Strike Counts
            </Button>
          </div>

          {/* Grid of bell cards */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))',
            gap: 'var(--space-5)',
          }}>
            {bellOutputs.map((output, i) => (
              <BellCard
                key={i}
                index={i}
                output={output}
                hammingMs={hammerTimings[i]}
                strikeCount={liveCounters?.[i] ?? null}
                requestingCounters={requestingCounters}
                isBellSystems={true}
              />
            ))}
          </div>
        </div>
      )}

      {/* ── Confirm disable dialog ────────────────────────────────────────── */}
      <ConfirmDialog
        open={confirmDisable}
        variant="danger"
        title="Disable Bell Commander"
        message="Are you sure you want to disable the Bell Commander? This will deactivate all bell mechanisms on this device."
        confirmLabel="Disable"
        onConfirm={() => {
          setConfirmDisable(false)
          handleToggleCommander(false)
        }}
        onCancel={() => setConfirmDisable(false)}
        loading={togglingCommander}
      />

    </div>
  )
}
