// frontend/src/pages/settings/staff/StaffDetail.jsx

import { useState, useEffect } from 'react'
import { useParams, useNavigate } 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 Card from '@/components/ui/Card'
import StatusBadge from '@/components/ui/StatusBadge'
import Spinner from '@/components/ui/Spinner'
import Modal from '@/components/ui/Modal'
import FormField from '@/components/ui/FormField'
import ConfirmDialog from '@/components/ui/ConfirmDialog'
import Icon from '@/components/ui/Icon'

// ─── Role meta ─────────────────────────────────────────────────────────────

const ROLE_VARIANT = {
  sysadmin: 'danger',
  admin:    'warning',
  editor:   'info',
  user:     'neutral',
}

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

function InfoRow({ label, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
      <dt style={{
        fontSize: 'var(--font-size-xs)',
        fontWeight: 'var(--font-weight-semibold)',
        textTransform: 'uppercase',
        letterSpacing: 'var(--tracking-wide)',
        color: 'var(--color-text-muted)',
      }}>
        {label}
      </dt>
      <dd style={{ fontSize: 'var(--font-size-base)', color: 'var(--color-text-primary)', margin: 0 }}>
        {children || <span style={{ color: 'var(--color-text-muted)' }}>—</span>}
      </dd>
    </div>
  )
}

// ─── Permission display pill ────────────────────────────────────────────────

function PermPill({ value }) {
  if (value) {
    return (
      <span style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: '4px',
        padding: '2px 8px',
        borderRadius: 'var(--radius-full)',
        backgroundColor: 'var(--color-success-bg)',
        color: 'var(--color-success)',
        fontSize: 'var(--font-size-xs)',
        fontWeight: 'var(--font-weight-semibold)',
      }}>
        <svg width="9" height="9" viewBox="0 0 10 10" fill="none" aria-hidden="true">
          <path d="M2 5l2.5 2.5L8 3" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
        Yes
      </span>
    )
  }
  return (
    <span style={{
      display: 'inline-flex',
      alignItems: 'center',
      padding: '2px 8px',
      borderRadius: 'var(--radius-full)',
      backgroundColor: 'var(--color-bg-island)',
      color: 'var(--color-text-muted)',
      fontSize: 'var(--font-size-xs)',
      fontWeight: 'var(--font-weight-normal)',
    }}>
      No
    </span>
  )
}

function AccessPill({ viewVal, editVal }) {
  if (editVal) return (
    <span style={{
      display: 'inline-flex',
      alignItems: 'center',
      padding: '2px 8px',
      borderRadius: 'var(--radius-full)',
      backgroundColor: 'var(--color-info-bg)',
      color: 'var(--color-info)',
      fontSize: 'var(--font-size-xs)',
      fontWeight: 'var(--font-weight-semibold)',
    }}>Edit</span>
  )
  if (viewVal) return (
    <span style={{
      display: 'inline-flex',
      alignItems: 'center',
      padding: '2px 8px',
      borderRadius: 'var(--radius-full)',
      backgroundColor: 'var(--color-success-bg)',
      color: 'var(--color-success)',
      fontSize: 'var(--font-size-xs)',
      fontWeight: 'var(--font-weight-semibold)',
    }}>View</span>
  )
  return (
    <span style={{
      display: 'inline-flex',
      alignItems: 'center',
      padding: '2px 8px',
      borderRadius: 'var(--radius-full)',
      backgroundColor: 'var(--color-bg-island)',
      color: 'var(--color-text-muted)',
      fontSize: 'var(--font-size-xs)',
    }}>None</span>
  )
}

function PermRow({ label, value }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      padding: 'var(--space-2) 0',
      borderBottom: '1px solid var(--color-border)',
    }}>
      <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>{label}</span>
      <PermPill value={value} />
    </div>
  )
}

function SegRow({ label, viewVal, editVal }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      padding: 'var(--space-2) 0',
      borderBottom: '1px solid var(--color-border)',
    }}>
      <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>{label}</span>
      <AccessPill viewVal={viewVal} editVal={editVal} />
    </div>
  )
}

function PermCard({ title, children }) {
  return (
    <Card title={title} variant="flat">
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {children}
      </div>
    </Card>
  )
}

// ─── Reset Password Modal ──────────────────────────────────────────────────

function ResetPasswordModal({ open, onClose, memberId, memberName }) {
  const { toast } = useToast()
  const [password, setPassword] = useState('')
  const [saving,   setSaving]   = useState(false)
  const [error,    setError]    = useState('')

  function handleClose() {
    setPassword('')
    setError('')
    onClose()
  }

  async function handleSubmit(e) {
    e.preventDefault()
    setError('')
    if (password.length < 6) { setError('Password must be at least 6 characters.'); return }
    setSaving(true)
    try {
      await api.put(`/staff/${memberId}/password`, { new_password: password })
      toast.success('Password updated', `Password for ${memberName} has been changed.`)
      handleClose()
    } catch (err) {
      setError(err.message || 'Failed to update password.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={handleClose}
      title="Reset Password"
      size="sm"
      footer={
        <>
          <Button variant="ghost" onClick={handleClose} disabled={saving}>Cancel</Button>
          <Button variant="primary" onClick={handleSubmit} loading={saving}>Update Password</Button>
        </>
      }
    >
      <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)', marginBottom: 'var(--space-4)' }}>
        Set a new password for <strong style={{ color: 'var(--color-text-primary)' }}>{memberName}</strong>.
      </p>
      <FormField
        label="New Password"
        name="new_password"
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Min. 6 characters"
        error={error}
        required
      />
    </Modal>
  )
}

// ─── Main ─────────────────────────────────────────────────────────────────

export default function StaffDetail() {
  const { id }     = useParams()
  const navigate   = useNavigate()
  const { user }   = useAuth()
  const toast      = useToast()

  const [member,      setMember]      = useState(null)
  const [loading,     setLoading]     = useState(true)
  const [showDelete,  setShowDelete]  = useState(false)
  const [deleting,    setDeleting]    = useState(false)
  const [showResetPw, setShowResetPw] = useState(false)

  useEffect(() => {
    setLoading(true)
    api.get(`/staff/${id}`)
      .then(setMember)
      .catch((err) => toast.danger('Failed to load staff member', err.message))
      .finally(() => setLoading(false))
  }, [id])

  const handleDelete = async () => {
    setDeleting(true)
    try {
      await api.delete(`/staff/${id}`)
      toast.success('Staff member deleted', `${member.name} has been removed.`)
      navigate('/settings/staff')
    } catch (err) {
      toast.danger('Delete failed', err.message)
      setDeleting(false)
      setShowDelete(false)
    }
  }

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

  if (!member) return null

  const canEdit   = !(user?.role === 'admin' && member.role === 'sysadmin')
  const canDelete = canEdit && member.id !== user?.sub
  const showPerms = (member.role === 'editor' || member.role === 'user') && member.permissions

  const q    = member.permissions || {}
  const mel  = q.melodies       || {}
  const dev  = q.devices         || {}
  const usr  = q.app_users       || {}
  const iss  = q.issues_notes    || {}
  const mail = q.mail            || {}
  const crm  = q.crm             || {}
  const cc   = q.crm_customers   || {}
  const cprod = q.crm_products   || {}
  const mfg  = q.mfg             || {}
  const apir = q.api_reference   || {}
  const mqtt = q.mqtt            || {}

  return (
    <div className="page-wrapper">
      <PageHeader title={member.name} subtitle={member.email}>
        <div style={{ display: 'flex', gap: 'var(--space-2)' }}>
          {canEdit && (
            <>
              <Button variant="secondary" onClick={() => setShowResetPw(true)}>
                <Icon name="edit" size={14} />
                Reset Password
              </Button>
              <Button variant="primary" onClick={() => navigate(`/settings/staff/${id}/edit`)}>
                Edit
              </Button>
            </>
          )}
          {canDelete && (
            <Button variant="danger" onClick={() => setShowDelete(true)}>
              Delete
            </Button>
          )}
        </div>
      </PageHeader>

      {/* Account info card */}
      <Card title="Account Information" variant="flat">
        <dl style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 'var(--space-5)' }}>
          <InfoRow label="Name">{member.name}</InfoRow>
          <InfoRow label="Email">{member.email}</InfoRow>
          <InfoRow label="Role">
            <StatusBadge variant={ROLE_VARIANT[member.role] || 'neutral'}>
              {member.role?.charAt(0).toUpperCase() + member.role?.slice(1)}
            </StatusBadge>
          </InfoRow>
          <InfoRow label="Status">
            <StatusBadge variant={member.is_active ? 'success' : 'neutral'}>
              {member.is_active ? 'Active' : 'Inactive'}
            </StatusBadge>
          </InfoRow>
          <InfoRow label="Document ID">
            <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
              {member.id}
            </span>
          </InfoRow>
        </dl>
      </Card>

      {/* Admin / Sysadmin — full access notice */}
      {(member.role === 'sysadmin' || member.role === 'admin') && (
        <Card title="Permissions" variant="flat">
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
            <div style={{
              width: '36px',
              height: '36px',
              borderRadius: 'var(--radius-full)',
              backgroundColor: member.role === 'sysadmin' ? 'var(--color-danger-bg)' : 'var(--color-warning-bg)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              flexShrink: 0,
            }}>
              <Icon name="check" size={16} color={member.role === 'sysadmin' ? 'var(--color-danger)' : 'var(--color-warning)'} />
            </div>
            <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
              {member.role === 'sysadmin'
                ? 'SysAdmin has full god-mode access to all features and settings.'
                : 'Admin has full access to all features, except managing SysAdmin accounts and system-level settings.'}
            </p>
          </div>
        </Card>
      )}

      {/* Granular permissions grid */}
      {showPerms && (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 'var(--space-4)' }}>

            <PermCard title="Melodies">
              <PermRow label="View"             value={mel.view} />
              <PermRow label="Add"              value={mel.add} />
              <PermRow label="Delete"           value={mel.delete} />
              <PermRow label="Safe Edit"        value={mel.safe_edit || mel.full_edit} />
              <PermRow label="Full Edit"        value={mel.full_edit} />
              <PermRow label="Archetype Access" value={mel.archetype_access} />
              <PermRow label="Settings Access"  value={mel.settings_access} />
              <PermRow label="Compose Access"   value={mel.compose_access} />
            </PermCard>

            <PermCard title="Devices">
              <PermRow label="View"               value={dev.view} />
              <PermRow label="Add"                value={dev.add} />
              <PermRow label="Delete"             value={dev.delete} />
              <PermRow label="Safe Edit (Info)"   value={dev.safe_edit || dev.full_edit} />
              <PermRow label="Edit Bells"         value={dev.edit_bells || dev.full_edit} />
              <PermRow label="Edit Clock & Alerts" value={dev.edit_clock || dev.full_edit} />
              <PermRow label="Edit Warranty/Sub"  value={dev.edit_warranty || dev.full_edit} />
              <PermRow label="Full Edit"          value={dev.full_edit} />
              <PermRow label="Control"            value={dev.control} />
            </PermCard>

            <PermCard title="App Users">
              <PermRow label="View"      value={usr.view} />
              <PermRow label="Add"       value={usr.add} />
              <PermRow label="Delete"    value={usr.delete} />
              <PermRow label="Safe Edit" value={usr.safe_edit || usr.full_edit} />
              <PermRow label="Full Edit" value={usr.full_edit} />
            </PermCard>

            <PermCard title="Issues & Notes">
              <PermRow label="View"   value={iss.view} />
              <PermRow label="Add"    value={iss.add} />
              <PermRow label="Delete" value={iss.delete} />
              <PermRow label="Edit"   value={iss.edit} />
            </PermCard>

            <PermCard title="Mail">
              <PermRow label="View Inbox" value={mail.view} />
              <PermRow label="Compose"    value={mail.compose} />
              <PermRow label="Reply"      value={mail.reply} />
            </PermCard>

            <PermCard title="CRM">
              <PermRow label="View Activity Log" value={crm.activity_log} />
            </PermCard>

            <PermCard title="CRM Products">
              <PermRow label="View"        value={cprod.view} />
              <PermRow label="Add"         value={cprod.add} />
              <PermRow label="Edit/Delete" value={cprod.edit} />
            </PermCard>

            <PermCard title="Manufacturing">
              <PermRow label="View Inventory"   value={mfg.view_inventory} />
              <PermRow label="Edit"             value={mfg.edit} />
              <PermRow label="Provision Device" value={mfg.provision} />
              <SegRow  label="Firmware"         viewVal={mfg.firmware_view} editVal={mfg.firmware_edit} />
            </PermCard>

          </div>

          {/* CRM Customers — full width */}
          <Card variant="flat">
            <div style={{ marginBottom: 'var(--space-4)', display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
              <h3 style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', margin: 0 }}>
                CRM Customers
              </h3>
              {cc.full_access && (
                <StatusBadge variant="success">Full Access</StatusBadge>
              )}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 var(--space-8)' }}>
              <div>
                <PermRow label="Overview Tab"    value={cc.full_access || cc.overview} />
                <PermRow label="Add Customer"    value={cc.full_access || cc.add} />
                <PermRow label="Delete Customer" value={cc.full_access || cc.delete} />
                <SegRow  label="Orders"          viewVal={cc.full_access || cc.orders_view}     editVal={cc.full_access || cc.orders_edit} />
                <SegRow  label="Quotations"      viewVal={cc.full_access || cc.quotations_view} editVal={cc.full_access || cc.quotations_edit} />
              </div>
              <div>
                <SegRow  label="Files & Media"         viewVal={cc.full_access || cc.files_view}   editVal={cc.full_access || cc.files_edit} />
                <SegRow  label="Devices Tab"            viewVal={cc.full_access || cc.devices_view} editVal={cc.full_access || cc.devices_edit} />
                <PermRow label="Comms: View"            value={cc.full_access || cc.comms_view} />
                <PermRow label="Comms: Log Entry"       value={cc.full_access || cc.comms_log} />
                <PermRow label="Comms: Edit Entries"    value={cc.full_access || cc.comms_edit} />
                <PermRow label="Comms: Compose & Send"  value={cc.full_access || cc.comms_compose} />
              </div>
            </div>
          </Card>

          {/* API + MQTT */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 'var(--space-4)' }}>
            <PermCard title="API Reference">
              <PermRow label="Access API Reference" value={apir.access} />
            </PermCard>
            <PermCard title="MQTT">
              <PermRow label="MQTT Access" value={mqtt.access} />
            </PermCard>
          </div>
        </>
      )}

      <ResetPasswordModal
        open={showResetPw}
        onClose={() => setShowResetPw(false)}
        memberId={id}
        memberName={member.name}
      />

      <ConfirmDialog
        open={showDelete}
        variant="danger"
        title="Delete Staff Member"
        message={`Are you sure you want to delete "${member.name}" (${member.email})? This cannot be undone.`}
        confirmLabel="Delete"
        loading={deleting}
        onConfirm={handleDelete}
        onCancel={() => setShowDelete(false)}
      />
    </div>
  )
}
