// frontend/src/pages/crm/products/ProductList.jsx

import { useState, useEffect, useCallback } 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 Button       from '@/components/ui/Button'
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 DeleteProductModal from '@/modals/crm/products/DeleteProductModal'

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

const CATEGORY_LABELS = {
  controller:     'Controller',
  striker:        'Striker',
  clock:          'Clock',
  part:           'Part',
  repair_service: 'Repair / Service',
}

const CATEGORY_BADGE_VARIANT = {
  controller:     'primary',
  striker:        'info',
  clock:          'warning',
  part:           'neutral',
  repair_service: 'neutral',
}

const STATUS_VARIANT = {
  active:       'success',
  discontinued: 'danger',
  planned:      'warning',
}

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

function Muted({ children }) {
  return (
    <span style={{ color: 'var(--color-text-muted)' }}>{children}</span>
  )
}

function MonoCell({ children }) {
  return (
    <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
      {children}
    </span>
  )
}

function ProductThumb({ src, name }) {
  if (src) {
    return (
      <img
        src={src}
        alt={name}
        style={{
          width: 36,
          height: 36,
          borderRadius: 'var(--radius-md)',
          objectFit: 'contain',
          border: '1px solid var(--color-border)',
          backgroundColor: 'var(--color-bg-abyss)',
          display: 'block',
          flexShrink: 0,
        }}
      />
    )
  }
  return (
    <div
      style={{
        width: 36,
        height: 36,
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border)',
        backgroundColor: 'var(--color-bg-abyss)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexShrink: 0,
      }}
      aria-hidden="true"
    >
      <Icon name="devices" size={14} color="var(--color-text-muted)" />
    </div>
  )
}

// ─── Sorting ──────────────────────────────────────────────────────────────────

function getSortValue(p, key) {
  switch (key) {
    case 'name':     return (p.name || '').toLowerCase()
    case 'sku':      return (p.sku  || '').toLowerCase()
    case 'price':    return p.price != null ? Number(p.price) : -1
    case 'margin': {
      const price   = p.price != null ? Number(p.price) : null
      const cost    = p.costs?.total != null ? Number(p.costs.total) : null
      return price != null && cost != null ? price - cost : -Infinity
    }
    case 'stock':    return p.stock?.available ?? -1
    default:         return 0
  }
}

function sortProducts(products, key, dir) {
  if (!key) return products
  return [...products].sort((a, b) => {
    const va = getSortValue(a, key)
    const vb = getSortValue(b, key)
    if (va < vb) return dir === 'asc' ? -1 : 1
    if (va > vb) return dir === 'asc' ?  1 : -1
    return 0
  })
}

// ─── ProductList ──────────────────────────────────────────────────────────────

export default function ProductList() {
  const navigate       = useNavigate()
  const { hasPermission } = useAuth()
  const canEdit        = hasPermission('crm_products', 'edit')
  const canAdd         = hasPermission('crm_products', 'add')

  // Data
  const [products, setProducts] = useState([])
  const [loading,  setLoading]  = useState(true)
  const [error,    setError]    = useState('')

  // Filters
  const [search,          setSearch]          = useState('')
  const [categoryFilter,  setCategoryFilter]  = useState('')
  const [statusFilter,    setStatusFilter]    = useState('')

  // Sort + pagination
  const [sortKey,  setSortKey]  = useState('')
  const [sortDir,  setSortDir]  = useState('asc')
  const [page,     setPage]     = useState(1)
  const [pageSize, setPageSize] = useState(20)

  // Delete modal
  const [deleteTarget,  setDeleteTarget]  = useState(null)
  const [deleteLoading, setDeleteLoading] = useState(false)
  const [, setDeleteError] = useState('')

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

  const fetchProducts = useCallback(async () => {
    setLoading(true)
    setError('')
    try {
      const params = new URLSearchParams()
      if (categoryFilter) params.set('category', categoryFilter)
      const qs   = params.toString()
      const data = await api.get(`/crm/products${qs ? `?${qs}` : ''}`)
      setProducts(data.products ?? [])
    } catch (err) {
      setError(err.message || 'Failed to load products.')
    } finally {
      setLoading(false)
    }
  }, [categoryFilter])

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

  // Reset to page 1 on filter/sort change
  useEffect(() => { setPage(1) }, [search, categoryFilter, statusFilter])

  // ── Delete ───────────────────────────────────────────────────────────────

  const handleDelete = async () => {
    if (!deleteTarget) return
    setDeleteLoading(true)
    setDeleteError('')
    try {
      await api.delete(`/crm/products/${deleteTarget.id}`)
      setDeleteTarget(null)
      fetchProducts()
    } catch (err) {
      setDeleteError(err.message || 'Failed to delete product.')
    } finally {
      setDeleteLoading(false)
    }
  }

  // ── Client-side filter + sort + paginate ──────────────────────────────────

  const filtered = products.filter((p) => {
    if (statusFilter && p.status !== statusFilter &&
        !(statusFilter === 'active' && p.active === true && !p.status)) return false
    if (search) {
      const q = search.toLowerCase()
      if (!(p.name || '').toLowerCase().includes(q) &&
          !(p.sku  || '').toLowerCase().includes(q)) return false
    }
    return true
  })

  const sorted     = sortProducts(filtered, sortKey, sortDir)
  const total      = sorted.length
  const paged      = sorted.slice((page - 1) * pageSize, page * pageSize)

  // ── Column definitions ────────────────────────────────────────────────────

  const columns = [
    {
      key: 'photo',
      label: '',
      width: '52px',
      render: (p) => (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <ProductThumb
            src={p.photo_url ? `/api${p.photo_url}` : null}
            name={p.name}
          />
        </div>
      ),
    },
    {
      key: 'name',
      label: 'Name',
      sortable: true,
      render: (p) => (
        <span style={{ fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)' }}>
          {p.name || <Muted>Unnamed</Muted>}
        </span>
      ),
    },
    {
      key: 'sku',
      label: 'SKU',
      sortable: true,
      render: (p) => p.sku ? <MonoCell>{p.sku}</MonoCell> : <Muted>—</Muted>,
    },
    {
      key: 'category',
      label: 'Category',
      render: (p) => (
        <StatusBadge
          variant={CATEGORY_BADGE_VARIANT[p.category] ?? 'neutral'}
          dot={false}
          size="sm"
        >
          {CATEGORY_LABELS[p.category] ?? p.category ?? '—'}
        </StatusBadge>
      ),
    },
    {
      key: 'price',
      label: 'Price',
      align: 'right',
      sortable: true,
      render: (p) => {
        const v = p.price != null ? Number(p.price) : null
        return v != null
          ? <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)' }}>€{v.toFixed(2)}</span>
          : <Muted>—</Muted>
      },
    },
    {
      key: 'mfgCost',
      label: 'Mfg. Cost',
      align: 'right',
      render: (p) => {
        const v = p.costs?.total != null ? Number(p.costs.total) : null
        return v != null
          ? <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>€{v.toFixed(2)}</span>
          : <Muted>—</Muted>
      },
    },
    {
      key: 'margin',
      label: 'Margin',
      align: 'right',
      sortable: true,
      render: (p) => {
        const price = p.price != null ? Number(p.price) : null
        const cost  = p.costs?.total != null ? Number(p.costs.total) : null
        if (price == null || cost == null) return <Muted>—</Muted>
        const margin = price - cost
        return (
          <span style={{
            fontFamily: 'var(--font-family-mono)',
            fontSize:   'var(--font-size-sm)',
            color:      margin >= 0 ? 'var(--color-success)' : 'var(--color-danger)',
            fontWeight: 'var(--font-weight-medium)',
          }}>
            €{margin.toFixed(2)}
          </span>
        )
      },
    },
    {
      key: 'stock',
      label: 'Stock',
      align: 'right',
      sortable: true,
      render: (p) => {
        const available = p.stock?.available ?? null
        if (available == null) return <Muted>—</Muted>
        const low = available <= 5
        return (
          <span style={{
            fontFamily: 'var(--font-family-mono)',
            fontSize:   'var(--font-size-sm)',
            color:      low ? 'var(--color-warning)' : 'var(--color-text-primary)',
            fontWeight: low ? 'var(--font-weight-medium)' : undefined,
          }}>
            {available}
          </span>
        )
      },
    },
    {
      key: 'status',
      label: 'Status',
      render: (p) => {
        const status = p.status ?? (p.active !== false ? 'active' : 'discontinued')
        const label  = status.charAt(0).toUpperCase() + status.slice(1)
        return (
          <StatusBadge variant={STATUS_VARIANT[status] ?? 'neutral'} size="sm">
            {label}
          </StatusBadge>
        )
      },
    },
    {
      key: '__actions',
      label: '',
      width: '110px',
      align: 'right',
      render: (p) => (
        <div onClick={(e) => e.stopPropagation()} style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <RowActions
            actions={[
              {
                label: 'View / Edit',
                icon: <Icon name="edit" size={14} />,
                onClick: () => navigate(`/crm/products/${p.id}`),
              },
              ...(canEdit ? [
                {
                  label: 'Delete',
                  icon: <Icon name="delete" size={14} />,
                  color: 'var(--color-danger)',
                  divider: true,
                  onClick: () => { setDeleteError(''); setDeleteTarget(p) },
                },
              ] : []),
            ]}
          />
        </div>
      ),
    },
  ]

  // ─────────────────────────────────────────────────────────────────────────

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

      <PageHeader
        title="Product Catalog"
        subtitle={!loading ? `${filtered.length} ${filtered.length === 1 ? 'product' : 'products'}` : undefined}
      >
        {canAdd && (
          <Button variant="primary" size="md" onClick={() => navigate('/crm/products/new')}>
            New Product
          </Button>
        )}
      </PageHeader>

      {/* Filter toolbar */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-3)', alignItems: 'center', minWidth: 0 }}>
        <div style={{ flex: '1 1 0', minWidth: '200px' }}>
          <SearchBar
            value={search}
            onChange={setSearch}
            placeholder="Search by name or SKU…"
          />
        </div>

        <Select
          value={categoryFilter}
          onChange={(e) => setCategoryFilter(e.target.value)}
          style={{ width: '160px', flexShrink: 0 }}
        >
          <option value="">All Categories</option>
          {Object.entries(CATEGORY_LABELS).map(([val, label]) => (
            <option key={val} value={val}>{label}</option>
          ))}
        </Select>

        <Select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          style={{ width: '140px', flexShrink: 0 }}
        >
          <option value="">All Statuses</option>
          <option value="active">Active</option>
          <option value="discontinued">Discontinued</option>
          <option value="planned">Planned</option>
        </Select>
      </div>

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

      {/* Table */}
      <DataTable
        columns={columns}
        data={paged}
        loading={loading}
        keyField="id"
        emptyMessage="No products found"
        emptyDescription="Try adjusting your search or filters, or add a new product."
        onRowClick={(p) => navigate(`/crm/products/${p.id}`)}
        skeletonRows={8}
        sortKey={sortKey}
        sortDir={sortDir}
        onSort={(key, dir) => { setSortKey(key); setSortDir(dir); setPage(1) }}
        footer={
          total > pageSize && (
            <Pagination
              page={page}
              pageSize={pageSize}
              total={total}
              onPageChange={setPage}
              onSizeChange={(s) => { setPageSize(s); setPage(1) }}
              pageSizes={[10, 20, 50, 100]}
            />
          )
        }
      />

      {/* Delete confirmation */}
      <DeleteProductModal
        product={deleteTarget}
        onConfirm={handleDelete}
        onCancel={() => { setDeleteTarget(null); setDeleteError('') }}
        loading={deleteLoading}
      />

    </div>
  )
}
