// frontend/src/pages/bellcloud/devices/DeviceDetail.jsx
// Parent shell — data fetching, tab routing, modals. Tab content lives in tabs/

import { useState, useEffect, useCallback } from 'react'
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import { useToast } from '@/components/ui/Toast'
import PageHeader from '@/components/ui/PageHeader'
import Button from '@/components/ui/Button'
import Tabs from '@/components/ui/Tabs'
import Spinner from '@/components/ui/Spinner'
import ConfirmDialog from '@/components/ui/ConfirmDialog'

import EditLocationModal from '@/modals/bellcloud/devices/EditLocationModal'
import EditAttributesModal from '@/modals/bellcloud/devices/EditAttributesModal'
import EditLoggingModal from '@/modals/bellcloud/devices/EditLoggingModal'
import EditMiscModal from '@/modals/bellcloud/devices/EditMiscModal'
import EditBellOutputsModal from '@/modals/bellcloud/devices/EditBellOutputsModal'
import EditClockSettingsModal from '@/modals/bellcloud/devices/EditClockSettingsModal'
import EditAlertsModal from '@/modals/bellcloud/devices/EditAlertsModal'
import EditBacklightModal from '@/modals/bellcloud/devices/EditBacklightModal'
import EditSubscriptionModal from '@/modals/bellcloud/devices/EditSubscriptionModal'
import EditWarrantyModal from '@/modals/bellcloud/devices/EditWarrantyModal'
import AssignCustomerModal from '@/modals/bellcloud/devices/AssignCustomerModal'

import OverviewTab  from '@/pages/bellcloud/devices/tabs/OverviewTab'
import GeneralTab   from '@/pages/bellcloud/devices/tabs/GeneralTab'
import BellsTab     from '@/pages/bellcloud/devices/tabs/BellsTab'
import ClockTab     from '@/pages/bellcloud/devices/tabs/ClockTab'
import WarrantyTab  from '@/pages/bellcloud/devices/tabs/WarrantyTab'
import ManageTab    from '@/pages/bellcloud/devices/tabs/ManageTab'
import ControlTab   from '@/pages/bellcloud/devices/tabs/ControlTab'

// ─── Tab config ───────────────────────────────────────────────────────────────

const TABS = [
  { key: 'overview', label: 'Overview'            },
  { key: 'general',  label: 'General'             },
  { key: 'bells',    label: 'Bell Mechanisms'     },
  { key: 'clock',    label: 'Clock & Alerts'      },
  { key: 'warranty', label: 'Warranty & Subscription' },
  { key: 'manage',   label: 'Manage'              },
  { key: 'control',  label: 'Control'             },
]

function resolveInitialTab(searchParams) {
  const raw = searchParams.get('tab')
  if (!raw) return 'overview'
  const match = TABS.find(t => t.key === raw.toLowerCase())
  return match ? match.key : 'overview'
}

// ─── DeviceDetail ─────────────────────────────────────────────────────────────

export default function DeviceDetail() {
  const { id } = useParams()
  const navigate = useNavigate()
  const [searchParams, setSearchParams] = useSearchParams()
  const { hasPermission } = useAuth()
  const { toast } = useToast()
  const canEdit = hasPermission('devices', 'edit')

  // ── State ──────────────────────────────────────────────────────────────────
  const [device, setDevice]         = useState(null)
  const [loading, setLoading]       = useState(true)
  const [error, setError]           = useState('')
  const [mqttStatus, setMqttStatus] = useState(null)
  const [activeTab, setActiveTab]   = useState(() => resolveInitialTab(searchParams))

  const [deviceUsers, setDeviceUsers]       = useState([])
  const [usersLoading, setUsersLoading]     = useState(false)
  const [ownerCustomer, setOwnerCustomer]   = useState(null)
  const [assigningCustomer, setAssigningCustomer] = useState(false)

  const [tags, setTags]           = useState([])
  const [staffNotes, setStaffNotes] = useState('')

  const [showDelete, setShowDelete] = useState(false)
  const [deleting, setDeleting]     = useState(false)

  const [cmdHistory, setCmdHistory]           = useState([])
  const [cmdHistoryLoading, setCmdHistoryLoading] = useState(false)
  const [sendingCmd, setSendingCmd]           = useState('')

  // Modal open flags
  const [editingLocation,      setEditingLocation]      = useState(false)
  const [editingAttributes,    setEditingAttributes]    = useState(false)
  const [editingLogging,       setEditingLogging]       = useState(false)
  const [editingMisc,          setEditingMisc]          = useState(false)
  const [editingBellOutputs,   setEditingBellOutputs]   = useState(false)
  const [editingClockSettings, setEditingClockSettings] = useState(false)
  const [editingAlerts,        setEditingAlerts]        = useState(false)
  const [editingBacklight,     setEditingBacklight]     = useState(false)
  const [editingSubscription,  setEditingSubscription]  = useState(false)
  const [editingWarranty,      setEditingWarranty]      = useState(false)
  const [showAssignCustomer,   setShowAssignCustomer]   = useState(false)

  // ── Data fetching ──────────────────────────────────────────────────────────

  const loadDevice = useCallback(async () => {
    setLoading(true)
    setError('')
    try {
      const d = await api.get(`/devices/${id}`)
      setDevice(d)
      if (d.staffNotes) setStaffNotes(d.staffNotes)
      if (Array.isArray(d.tags)) setTags(d.tags)
      setLoading(false)

      const sn = d.serial_number || d.device_id
      if (sn) {
        api.get('/mqtt/status').then(mqttData => {
          if (mqttData?.devices) {
            const match = mqttData.devices.find(s => s.device_serial === sn)
            setMqttStatus(match || null)
          }
        }).catch(() => {})
      }

      if (d.customer_id) {
        api.get(`/devices/${id}/customer`).then(res => {
          setOwnerCustomer(res.customer || null)
        }).catch(() => setOwnerCustomer(null))
      } else {
        setOwnerCustomer(null)
      }

      setUsersLoading(true)
      api.get(`/devices/${id}/users`).then(data => {
        setDeviceUsers(data.users || [])
      }).catch(() => setDeviceUsers([])).finally(() => setUsersLoading(false))

    } catch (err) {
      setError(err.message || 'Failed to load device.')
      setLoading(false)
    }
  }, [id])

  useEffect(() => { loadDevice() }, [loadDevice])

  const loadCmdHistory = useCallback(async () => {
    const sn = device?.serial_number || device?.device_id
    if (!sn) return
    setCmdHistoryLoading(true)
    try {
      const data = await api.get(`/mqtt/commands/${sn}?limit=50`)
      setCmdHistory(data.commands || [])
    } catch {
      setCmdHistory([])
    } finally {
      setCmdHistoryLoading(false)
    }
  }, [device])

  useEffect(() => {
    if (activeTab === 'control' && device) loadCmdHistory()
  }, [activeTab, device, loadCmdHistory])

  // ── Tab sync ───────────────────────────────────────────────────────────────

  const handleTabChange = key => {
    setActiveTab(key)
    setSearchParams(prev => {
      const next = new URLSearchParams(prev)
      next.set('tab', key)
      return next
    }, { replace: true })
  }

  // ── Actions ────────────────────────────────────────────────────────────────

  const handleDelete = async () => {
    setDeleting(true)
    try {
      await api.delete(`/devices/${id}`)
      toast.success('Deleted', 'Device removed.')
      navigate('/devices')
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to delete device.')
      setDeleting(false)
      setShowDelete(false)
    }
  }

  const handleAssignCustomer = async customer => {
    setAssigningCustomer(true)
    try {
      await api.post(`/devices/${id}/assign-customer`, { customer_id: customer.id })
      setOwnerCustomer(customer)
      setDevice(prev => ({ ...prev, customer_id: customer.id }))
      setShowAssignCustomer(false)
      toast.success('Assigned', `Assigned to ${[customer.name, customer.surname].filter(Boolean).join(' ')}.`)
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to assign customer.')
    } finally {
      setAssigningCustomer(false)
    }
  }

  const handleUnassignCustomer = async () => {
    setAssigningCustomer(true)
    try {
      const cid = device?.customer_id
      await api.delete(`/devices/${id}/assign-customer${cid ? `?customer_id=${cid}` : ''}`)
      setOwnerCustomer(null)
      setDevice(prev => ({ ...prev, customer_id: '' }))
      toast.success('Removed', 'Customer unassigned.')
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to unassign.')
    } finally {
      setAssigningCustomer(false)
    }
  }

  const sendMqttCommand = async (cmd, contents = {}) => {
    const deviceId = device?.device_id || device?.serial_number
    if (!deviceId) return
    setSendingCmd(cmd)
    try {
      await api.post(`/mqtt/command/${deviceId}`, { cmd, contents })
      toast.success('Sent', `Command "${cmd}" sent.`)
      loadCmdHistory()
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to send command.')
    } finally {
      setSendingCmd('')
    }
  }

  // ── Derived ────────────────────────────────────────────────────────────────

  const attr  = device?.device_attributes  || {}
  const clock = attr.clockSettings          || {}
  const sub   = device?.device_subscription || {}
  const stats = device?.device_stats        || {}
  const sn    = device?.serial_number || device?.device_id
  const isOnline = mqttStatus ? mqttStatus.online : device?.is_Online

  // ── Render states ──────────────────────────────────────────────────────────

  if (loading) {
    return (
      <div className="page-wrapper">
        <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 'var(--space-16)' }}>
          <Spinner size="lg" />
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="page-wrapper">
        <div role="alert" style={{ backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)', borderRadius: 'var(--radius-md)', padding: 'var(--space-4)', color: 'var(--color-danger)' }}>
          {error}
        </div>
      </div>
    )
  }

  if (!device) return null

  // Props bundle passed to every tab
  const tabProps = {
    device,
    canEdit,
    onDeviceUpdated: setDevice,
    attr,
    clock,
    sub,
    stats,
    sn,
    isOnline,
    tags,
    setTags,
    staffNotes,
    setStaffNotes,
    deviceUsers,
    usersLoading,
    ownerCustomer,
    assigningCustomer,
    cmdHistory,
    cmdHistoryLoading,
    sendingCmd,
    loadDevice,
    loadCmdHistory,
    sendMqttCommand,
    onShowDelete:          () => setShowDelete(true),
    onAssignCustomer:      () => setShowAssignCustomer(true),
    onUnassignCustomer:    handleUnassignCustomer,
    onEditLocation:        () => setEditingLocation(true),
    onEditAttributes:      () => setEditingAttributes(true),
    onEditLogging:         () => setEditingLogging(true),
    onEditMisc:            () => setEditingMisc(true),
    onEditBellOutputs:     () => setEditingBellOutputs(true),
    onEditClockSettings:   () => setEditingClockSettings(true),
    onEditAlerts:          () => setEditingAlerts(true),
    onEditBacklight:       () => setEditingBacklight(true),
    onEditSubscription:    () => setEditingSubscription(true),
    onEditWarranty:        () => setEditingWarranty(true),
    onNavigateToManage:    () => handleTabChange('manage'),
  }

  // ── Render ─────────────────────────────────────────────────────────────────

  return (
    <div className="page-wrapper">

      <PageHeader
        title={device.device_name || 'Unnamed Device'}
        subtitle={sn}
      >
        {canEdit && (
          <Button variant="secondary" onClick={() => navigate(`/devices/${id}/edit`)}>
            Edit Device
          </Button>
        )}
      </PageHeader>

      <Tabs
        tabs={TABS}
        active={activeTab}
        onChange={handleTabChange}
      />

      <div style={{ flex: 1, minWidth: 0 }}>
        {activeTab === 'overview' && <OverviewTab  {...tabProps} />}
        {activeTab === 'general'  && <GeneralTab   {...tabProps} />}
        {activeTab === 'bells'    && <BellsTab     {...tabProps} />}
        {activeTab === 'clock'    && <ClockTab     {...tabProps} />}
        {activeTab === 'warranty' && <WarrantyTab  {...tabProps} />}
        {activeTab === 'manage'   && <ManageTab    {...tabProps} />}
        {activeTab === 'control'  && <ControlTab   {...tabProps} />}
      </div>

      {/* ── Modals ────────────────────────────────────────────────────────── */}

      <EditLocationModal
        open={editingLocation}
        onClose={() => setEditingLocation(false)}
        onSaved={loadDevice}
        device={device}
        id={id}
      />
      <EditAttributesModal
        open={editingAttributes}
        onClose={() => setEditingAttributes(false)}
        onSaved={loadDevice}
        attr={attr}
        id={id}
      />
      <EditLoggingModal
        open={editingLogging}
        onClose={() => setEditingLogging(false)}
        onSaved={loadDevice}
        attr={attr}
        id={id}
      />
      <EditMiscModal
        open={editingMisc}
        onClose={() => setEditingMisc(false)}
        onSaved={loadDevice}
        device={device}
        attr={attr}
        id={id}
      />
      <EditBellOutputsModal
        open={editingBellOutputs}
        onClose={() => setEditingBellOutputs(false)}
        onSaved={loadDevice}
        attr={attr}
        sub={sub}
        id={id}
      />
      <EditClockSettingsModal
        open={editingClockSettings}
        onClose={() => setEditingClockSettings(false)}
        onSaved={loadDevice}
        attr={attr}
        sub={sub}
        id={id}
      />
      <EditAlertsModal
        open={editingAlerts}
        onClose={() => setEditingAlerts(false)}
        onSaved={loadDevice}
        clock={clock}
        attr={attr}
        id={id}
      />
      <EditBacklightModal
        open={editingBacklight}
        onClose={() => setEditingBacklight(false)}
        onSaved={loadDevice}
        attr={attr}
        clock={clock}
        sub={sub}
        id={id}
      />
      <EditSubscriptionModal
        open={editingSubscription}
        onClose={() => setEditingSubscription(false)}
        onSaved={loadDevice}
        sub={sub}
        id={id}
      />
      <EditWarrantyModal
        open={editingWarranty}
        onClose={() => setEditingWarranty(false)}
        onSaved={loadDevice}
        stats={stats}
        id={id}
      />
      <AssignCustomerModal
        open={showAssignCustomer}
        onClose={() => setShowAssignCustomer(false)}
        onSelect={handleAssignCustomer}
        deviceId={id}
      />
      <ConfirmDialog
        open={showDelete}
        variant="danger"
        title="Delete Device"
        message={`Are you sure you want to delete "${device.device_name || sn}"? This action cannot be undone.`}
        confirmLabel="Delete"
        onConfirm={handleDelete}
        onCancel={() => setShowDelete(false)}
        loading={deleting}
      />

    </div>
  )
}
