// frontend/src/pages/manufacturing/DeviceInventory.jsx

import { useState, useEffect, useCallback, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import PageHeader from '@/components/ui/PageHeader'
import DataTable from '@/components/ui/DataTable'
import StatusBadge from '@/components/ui/StatusBadge'
import Pagination from '@/components/ui/Pagination'
import SearchBar from '@/components/ui/SearchBar'
import Select from '@/components/ui/Select'
import RowActions from '@/components/ui/RowActions'
import Icon from '@/components/ui/Icon'
import NewBatchModal from '@/modals/engineering/manufacturing/NewBatchModal'
import { fmtDateMedium } from '@/lib/formatters'
import DeleteDeviceModal from '@/modals/engineering/manufacturing/DeleteDeviceModal'
import DeleteUnprovisionedModal from '@/modals/engineering/manufacturing/DeleteUnprovisionedModal'

// ─── Constants ────────────────────────────────────────────────────────────────

const BOARD_TYPE_LABELS = {
  vesper: 'Vesper', vesper_plus: 'Vesper+', vesper_pro: 'Vesper Pro',
  agnus: 'Agnus', agnus_mini: 'Agnus Mini',
  chronos: 'Chronos', chronos_pro: 'Chronos Pro',
}

const BOARD_TYPE_OPTIONS = [
  { value: '', label: 'All Types' },
  { value: 'vesper_pro', label: 'Vesper Pro' },
  { value: 'vesper_plus', label: 'Vesper+' },
  { value: 'vesper', label: 'Vesper' },
  { value: 'agnus', label: 'Agnus' },
  { value: 'agnus_mini', label: 'Agnus Mini' },
  { value: 'chronos_pro', label: 'Chronos Pro' },
  { value: 'chronos', label: 'Chronos' },
]

const STATUS_OPTIONS = [
  { value: '', label: 'All Statuses' },
  { value: 'manufactured', label: 'Manufactured' },
  { value: 'flashed', label: 'Flashed' },
  { value: 'provisioned', label: 'Provisioned' },
  { value: 'sold', label: 'Sold' },
  { value: 'claimed', label: 'Claimed' },
  { value: 'decommissioned', label: 'Decommissioned' },
]

// Maps mfg_status → StatusBadge variant
const STATUS_VARIANT = {
  manufactured:   'neutral',
  flashed:        'info',
  provisioned:    'warning',
  sold:           'success',
  claimed:        'success',
  decommissioned: 'danger',
}

const DEFAULT_PAGE_SIZE = 25
const PAGE_SIZE_OPTIONS = [25, 50, 100]

const COLUMNS = [
  { key: 'serial',   label: 'Serial Number',  defaultOn: true,  alwaysOn: true },
  { key: 'type',     label: 'Type',           defaultOn: true,  sortable: true },
  { key: 'version',  label: 'Revision',       defaultOn: true,  sortable: true },
  { key: 'status',   label: 'Status',         defaultOn: true  },
  { key: 'batch',    label: 'Batch',          defaultOn: true  },
  { key: 'created',  label: 'Created',        defaultOn: true,  sortable: true },
  { key: 'customer', label: 'Customer',       defaultOn: true,  sortable: true },
  { key: 'name',     label: 'Device Name',    defaultOn: false, sortable: true },
]

const COL_PREF_KEY = 'mfg_inventory_cols_v2'

function loadColPrefs() {
  try {
    const raw = localStorage.getItem(COL_PREF_KEY)
    if (raw) return JSON.parse(raw)
  } catch { /* ignore */ }
  return COLUMNS.filter((c) => c.defaultOn).map((c) => c.key)
}

function saveColPrefs(keys) {
  try { localStorage.setItem(COL_PREF_KEY, JSON.stringify(keys)) } catch { /* ignore */ }
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

function formatHwVersion(v) {
  if (!v) return '—'
  if (/^\d+\.\d+/.test(v)) return `Rev ${v}`
  const n = parseInt(v, 10)
  return isNaN(n) ? `Rev ${v}` : `Rev ${n}.0`
}

function formatDate(iso) { return fmtDateMedium(iso) }

// ─── Stat Card ────────────────────────────────────────────────────────────────

function StatCard({ label, value, accent }) {
  return (
    <div style={{
      backgroundColor: 'rgba(28, 32, 38, 0.30)',
      backdropFilter: 'var(--blur-modal)',
      WebkitBackdropFilter: 'var(--blur-modal)',
      border: '1px solid var(--color-border)',
      borderRadius: 'var(--radius-lg)',
      padding: 'var(--space-4) var(--space-5)',
      boxShadow: 'var(--shadow-card)',
      display: 'flex',
      flexDirection: 'column',
      gap: 'var(--space-1)',
    }}>
      <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', fontWeight: 'var(--font-weight-semibold)' }}>{label}</p>
      <p style={{ fontSize: 'var(--font-size-2xl)', fontFamily: 'var(--font-family-display)', fontWeight: 'var(--font-weight-bold)', color: accent || 'var(--color-text-primary)', letterSpacing: 'var(--tracking-display)', lineHeight: 1 }}>{value}</p>
    </div>
  )
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function DeviceInventory() {
  const navigate   = useNavigate()
  const { hasPermission } = useAuth()
  const canDelete  = hasPermission('manufacturing', 'delete')

  const [devices, setDevices]           = useState([])
  const [loading, setLoading]           = useState(true)
  const [error, setError]               = useState('')
  const [search, setSearch]             = useState('')
  const [statusFilter, setStatusFilter] = useState('')
  const [typeFilter, setTypeFilter]     = useState('')
  const [page, setPage]                 = useState(1)
  const [pageSize, setPageSize]         = useState(DEFAULT_PAGE_SIZE)
  const [customerMap, setCustomerMap]   = useState({})

  // Sorting
  const [sortKey, setSortKey] = useState('')
  const [sortDir, setSortDir] = useState('asc')

  // Column visibility + order
  const [visibleCols, setVisibleCols] = useState(loadColPrefs)

  // Modals
  const [showBatch, setShowBatch]               = useState(false)
  const [deleteTarget, setDeleteTarget]         = useState(null)
  const [showDeleteUnprovisioned, setShowDeleteUnprovisioned] = useState(false)

  // ─── Fetch ────────────────────────────────────────────────────────────────

  const fetchDevices = useCallback(async () => {
    setLoading(true); setError('')
    try {
      const params = new URLSearchParams()
      if (search)       params.set('search', search)
      if (statusFilter) params.set('status', statusFilter)
      if (typeFilter)   params.set('hw_type', typeFilter)
      params.set('limit', '500')
      const data = await api.get(`/manufacturing/devices${params.toString() ? `?${params}` : ''}`)
      const devs = data.devices || []
      setDevices(devs)
      setPage(1)

      // Fetch customer names for assigned devices
      const customerIds = [...new Set(devs.map((d) => d.customer_id).filter(Boolean))]
      if (customerIds.length) {
        const entries = await Promise.all(
          customerIds.map((id) =>
            api.get(`/manufacturing/customers/${id}`)
              .then((c) => [id, c])
              .catch(() => [id, null])
          )
        )
        setCustomerMap(Object.fromEntries(entries))
      } else {
        setCustomerMap({})
      }
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }, [search, statusFilter, typeFilter])

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

  // ─── Sort ─────────────────────────────────────────────────────────────────

  const handleSort = (key, dir) => {
    setSortKey(key)
    setSortDir(dir)
    setPage(1)
  }

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

  const sorted = useMemo(() => {
    if (!sortKey) return devices
    return [...devices].sort((a, b) => {
      let av, bv
      if (sortKey === 'type')     { av = BOARD_TYPE_LABELS[a.hw_type] || a.hw_type || ''; bv = BOARD_TYPE_LABELS[b.hw_type] || b.hw_type || '' }
      else if (sortKey === 'version') { av = a.hw_version || ''; bv = b.hw_version || '' }
      else if (sortKey === 'created') { av = a.created_at || ''; bv = b.created_at || '' }
      else if (sortKey === 'customer') {
        const ca = customerMap[a.customer_id]; const cb = customerMap[b.customer_id]
        av = ca ? ([ca.name, ca.surname].filter(Boolean).join(' ') || ca.email || '') : ''
        bv = cb ? ([cb.name, cb.surname].filter(Boolean).join(' ') || cb.email || '') : ''
      }
      else if (sortKey === 'name') { av = a.name || ''; bv = b.name || '' }
      else { av = ''; bv = '' }
      const cmp = av < bv ? -1 : av > bv ? 1 : 0
      return sortDir === 'asc' ? cmp : -cmp
    })
  }, [devices, sortKey, sortDir, customerMap])

  const paged = sorted.slice((page - 1) * pageSize, page * pageSize)

  // Stats
  const stats = {
    total:        devices.length,
    manufactured: devices.filter((d) => d.mfg_status === 'manufactured').length,
    provisioned:  devices.filter((d) => d.mfg_status === 'provisioned').length,
    sold:         devices.filter((d) => ['sold','claimed'].includes(d.mfg_status)).length,
  }

  // ─── Column management ────────────────────────────────────────────────────
  // onColumnChange receives either a full ordered array (from drag-reorder)
  // or a single key string (from checkbox toggle via DataTable's internal toggle).
  // We normalise both cases here.

  const handleColumnChange = (payload) => {
    if (Array.isArray(payload)) {
      // Drag reorder — payload is the new ordered array of visible keys
      saveColPrefs(payload)
      setVisibleCols(payload)
    } else {
      // Single key toggle
      const col = COLUMNS.find((c) => c.key === payload)
      if (col?.alwaysOn) return
      setVisibleCols((prev) => {
        const next = prev.includes(payload)
          ? prev.filter((k) => k !== payload)
          : [...prev, payload]
        saveColPrefs(next)
        return next
      })
    }
  }

  // ─── Table columns definition ─────────────────────────────────────────────

  const allCols = COLUMNS.map((c) => ({ ...c, pickerLabel: c.label }))

  // Define all possible column renderers keyed by column key
  const COL_DEFS = {
    serial: {
      key: 'serial',
      label: 'Serial Number',
      render: (d) => (
        <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>
          {d.serial_number}
        </span>
      ),
    },
    type: {
      key: 'type',
      label: 'Type',
      sortable: true,
      render: (d) => (
        <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
          {BOARD_TYPE_LABELS[d.hw_type] || d.hw_type}
        </span>
      ),
    },
    version: {
      key: 'version',
      label: 'Revision',
      sortable: true,
      render: (d) => (
        <span style={{ fontSize: 'var(--font-size-sm)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)' }}>
          {formatHwVersion(d.hw_version)}
        </span>
      ),
    },
    status: {
      key: 'status',
      label: 'Status',
      render: (d) => (
        <StatusBadge variant={STATUS_VARIANT[d.mfg_status] || 'neutral'}>
          {d.mfg_status}
        </StatusBadge>
      ),
    },
    batch: {
      key: 'batch',
      label: 'Batch',
      render: (d) => (
        <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
          {d.batch_id || '—'}
        </span>
      ),
    },
    created: {
      key: 'created',
      label: 'Created',
      sortable: true,
      render: (d) => (
        <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
          {formatDate(d.created_at)}
        </span>
      ),
    },
    customer: {
      key: 'customer',
      label: 'Customer',
      sortable: true,
      render: (d) => {
        const c = customerMap[d.customer_id]
        if (!d.customer_id) return <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>—</span>
        if (!c) return <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{d.customer_id}</span>
        return (
          <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
            {[c.name, c.surname].filter(Boolean).join(' ') || c.email || d.customer_id}
          </span>
        )
      },
    },
    name: {
      key: 'name',
      label: 'Device Name',
      sortable: true,
      render: (d) => (
        <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
          {d.name || '—'}
        </span>
      ),
    },
  }

  const ACTIONS_COL = {
    key: '_actions',
    label: '',
    width: '52px',
    render: (d) => (
      <RowActions
        actions={[
          { label: 'View Detail', icon: <Icon name="eye" size={14} />, onClick: () => navigate(`/manufacturing/devices/${d.serial_number}`) },
          ...(canDelete ? [{ label: 'Delete', icon: <Icon name="delete" size={14} />, color: 'var(--color-danger)', onClick: () => setDeleteTarget(d) }] : []),
        ]}
      />
    ),
  }

  // Build cols in visibleCols order so drag-reorder is reflected immediately
  const cols = [
    ...visibleCols.map((key) => COL_DEFS[key]).filter(Boolean),
    ACTIONS_COL,
  ]

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

  return (
    <div className="page-wrapper">
      <PageHeader title="Device Inventory" subtitle="All manufactured Bell Systems units">
        <RowActions
          variant="secondary"
          size="md"
          actions={[
            { label: 'New Batch',              icon: <Icon name="plus" size={14} />,   onClick: () => setShowBatch(true) },
            { label: 'Provision New',          icon: <Icon name="plus" size={14} />,   divider: true, onClick: () => navigate('/manufacturing/provision') },
            { label: 'Delete Not Provisioned', icon: <Icon name="delete" size={14} />, color: 'var(--color-danger)', divider: true, onClick: () => setShowDeleteUnprovisioned(true) },
          ]}
        />
      </PageHeader>

      {/* Stats strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 'var(--space-4)' }}>
        <StatCard label="Total Devices" value={loading ? '…' : stats.total} />
        <StatCard label="Manufactured" value={loading ? '…' : stats.manufactured} accent="var(--color-text-muted)" />
        <StatCard label="Provisioned" value={loading ? '…' : stats.provisioned} accent="var(--color-warning)" />
        <StatCard label="Sold / Claimed" value={loading ? '…' : stats.sold} accent="var(--color-success)" />
      </div>

      {/* Toolbar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', flexWrap: 'wrap' }}>
        <div style={{ flex: '1 1 220px', minWidth: 0 }}>
          <SearchBar
            value={search}
            onChange={setSearch}
            placeholder="Search serial, batch, name…"
          />
        </div>
        <div style={{ width: 160 }}>
          <Select
            value={statusFilter}
            onChange={setStatusFilter}
            options={STATUS_OPTIONS}
            placeholder="All Statuses"
          />
        </div>
        <div style={{ width: 150 }}>
          <Select
            value={typeFilter}
            onChange={setTypeFilter}
            options={BOARD_TYPE_OPTIONS}
            placeholder="All Types"
          />
        </div>
      </div>

      {/* Error */}
      {error && (
        <div style={{ padding: 'var(--space-3)', borderRadius: 'var(--radius-md)', backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)', color: 'var(--color-danger)', fontSize: 'var(--font-size-sm)' }}>
          {error}
        </div>
      )}

      {/* Table */}
      <DataTable
        columns={cols}
        allColumns={allCols}
        visibleKeys={visibleCols}
        onColumnChange={handleColumnChange}
        data={paged}
        keyField="serial_number"
        loading={loading}
        sortKey={sortKey}
        sortDir={sortDir}
        onSort={handleSort}
        onRowClick={(d) => navigate(`/manufacturing/devices/${d.serial_number}`)}
        emptyMessage="No devices found"
        emptyDescription={search || statusFilter || typeFilter ? 'Try clearing your filters.' : 'Create your first batch to get started.'}
      />

      {/* Pagination */}
      <Pagination
        page={page}
        pageSize={pageSize}
        total={sorted.length}
        onPageChange={(p) => setPage(p)}
        onSizeChange={(s) => { setPageSize(s); setPage(1) }}
        pageSizes={PAGE_SIZE_OPTIONS}
      />

      {/* Modals */}
      <NewBatchModal
        open={showBatch}
        onClose={() => setShowBatch(false)}
        onCreated={() => fetchDevices()}
      />
      <DeleteDeviceModal
        open={!!deleteTarget}
        device={deleteTarget}
        onClose={() => setDeleteTarget(null)}
        onDeleted={() => { setDeleteTarget(null); fetchDevices() }}
      />
      <DeleteUnprovisionedModal
        open={showDeleteUnprovisioned}
        devices={devices}
        onClose={() => setShowDeleteUnprovisioned(false)}
        onDeleted={() => fetchDevices()}
      />
    </div>
  )
}
