// frontend/src/pages/crm/customers/tabs/SupportTab.jsx
// Issues and Notes linked to this customer — sourced from the Postgres /notes system.

import { useState, useEffect, useCallback } from 'react'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import { useToast } from '@/components/ui/Toast'
import Card from '@/components/ui/Card'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import Spinner from '@/components/ui/Spinner'
import ConfirmDialog from '@/components/ui/ConfirmDialog'
import Icon from '@/components/ui/Icon'
import { fmtDateMedium, fmtRelative } from '@/lib/formatters'
import EntryFormModal from '@/modals/crm/helpdesk/EntryFormModal'

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

const STATUS_META = {
  open:        { label: 'Open',        color: 'var(--color-danger)',  bg: 'var(--color-danger-bg)'  },
  researching: { label: 'Researching', color: 'var(--color-warning)', bg: 'var(--color-warning-bg)' },
  resolved:    { label: 'Resolved',    color: 'var(--color-success)', bg: 'var(--color-success-bg)' },
}

const SEVERITY_META = {
  low:      { label: 'Low',      color: 'var(--color-info)'    },
  medium:   { label: 'Medium',   color: 'var(--color-warning)' },
  high:     { label: 'High',     color: 'var(--color-danger)'  },
  critical: { label: 'Critical', color: 'var(--color-danger)', breathe: true },
}

const CATEGORY_META = {
  technical:       { label: 'Technical',       color: 'var(--color-info)',    bg: 'var(--color-info-bg)'    },
  install_support: { label: 'Install Support', color: 'var(--color-warning)', bg: 'var(--color-warning-bg)' },
  general:         { label: 'General',         color: 'var(--color-text-muted)', bg: 'var(--color-bg-elevated)' },
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function StatusPill({ status }) {
  const m = STATUS_META[status] || { label: status, color: 'var(--color-text-muted)', bg: 'var(--color-bg-elevated)' }
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '2px 8px',
      borderRadius: 'var(--radius-full)',
      backgroundColor: m.bg,
      border: `1px solid ${m.color}33`,
      fontSize: 'var(--font-size-xs)',
      fontWeight: 'var(--font-weight-semibold)',
      color: m.color,
      whiteSpace: 'nowrap',
      flexShrink: 0,
    }}>
      <span style={{ width: 5, height: 5, borderRadius: '50%', backgroundColor: m.color, flexShrink: 0 }} />
      {m.label}
    </span>
  )
}

function SeverityBars({ severity }) {
  if (!severity) return null
  const m = SEVERITY_META[severity] || { label: severity, color: 'var(--color-text-muted)' }
  const bars = { low: 1, medium: 2, high: 3, critical: 4 }[severity] || 1
  return (
    <span
      className={m.breathe ? 'support-severity-critical' : undefined}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 4, flexShrink: 0 }}
    >
      <span style={{ display: 'flex', alignItems: 'flex-end', gap: 2, height: 12 }}>
        {[1, 2, 3, 4].map(b => (
          <span key={b} style={{
            width: 3,
            height: 2 + b * 2,
            borderRadius: 1,
            backgroundColor: b <= bars ? m.color : 'var(--color-bg-island)',
            display: 'block',
          }} />
        ))}
      </span>
      <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: m.color }}>
        {m.label}
      </span>
    </span>
  )
}

function CategoryPill({ category }) {
  if (!category) return null
  const m = CATEGORY_META[category] || { label: category, color: 'var(--color-text-muted)', bg: 'var(--color-bg-elevated)' }
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      padding: '2px 8px',
      borderRadius: 'var(--radius-full)',
      backgroundColor: m.bg,
      border: `1px solid ${m.color}33`,
      fontSize: 'var(--font-size-xs)',
      fontWeight: 'var(--font-weight-medium)',
      color: m.color,
      whiteSpace: 'nowrap',
      flexShrink: 0,
    }}>
      {m.label}
    </span>
  )
}

// ─── IssuesCard ───────────────────────────────────────────────────────────────

function IssuesCard({ customerId, customerName, canEdit }) {
  const { toast }                             = useToast()
  const [issues,      setIssues]              = useState([])
  const [loading,     setLoading]             = useState(true)
  const [showResolved, setShowResolved]       = useState(false)
  const [modal,       setModal]               = useState({ open: false, entry: null })
  const [deleteId,    setDeleteId]            = useState(null)
  const [deleting,    setDeleting]            = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const data = await api.get(`/notes/by-entity/customer/${customerId}`)
      const all  = Array.isArray(data) ? data : []
      setIssues(all.filter(e => e.type === 'issue').reverse())
    } catch { setIssues([]) }
    finally { setLoading(false) }
  }, [customerId])

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

  const handleDelete = async () => {
    setDeleting(true)
    try {
      await api.delete(`/notes/${deleteId}`)
      toast.success('Deleted', 'Issue removed.')
      setDeleteId(null)
      load()
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to delete.')
    } finally { setDeleting(false) }
  }

  const openCreate  = ()      => setModal({ open: true, entry: null })
  const openEdit    = (entry) => setModal({ open: true, entry })

  const open     = issues.filter(i => i.status !== 'resolved')
  const resolved = issues.filter(i => i.status === 'resolved')
  const displayed = showResolved ? issues : open

  return (
    <>
      <style>{`
        @keyframes support-severity-critical-glow {
          0%, 100% { filter: drop-shadow(0 0 0px var(--color-danger)); }
          50%       { filter: drop-shadow(0 0 5px var(--color-danger)); }
        }
        .support-severity-critical { animation: support-severity-critical-glow 0.9s ease-in-out infinite; }
        .support-issue-row { transition: background 0.12s; cursor: pointer; }
        .support-issue-row:hover { background-color: var(--color-bg-elevated) !important; }
      `}</style>

      <Card
        title="Issues"
        action={
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
            {open.length > 0 && <StatusBadge variant="danger">{open.length} open</StatusBadge>}
            {resolved.length > 0 && <StatusBadge variant="neutral">{resolved.length} resolved</StatusBadge>}
            {resolved.length > 0 && (
              <Button variant="ghost" size="sm" onClick={() => setShowResolved(v => !v)}>
                {showResolved ? 'Hide Resolved' : `Show Resolved (${resolved.length})`}
              </Button>
            )}
            {canEdit && (
              <Button variant="secondary" size="sm" onClick={openCreate}>
                + Report Issue
              </Button>
            )}
          </div>
        }
      >

        {/* List */}
        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-8)' }}>
            <Spinner size="sm" />
          </div>
        ) : displayed.length === 0 ? (
          <div style={{
            padding: 'var(--space-8)',
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            gap: 'var(--space-2)', color: 'var(--color-text-muted)',
          }}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M22 11.08V12a10 10 0 11-5.93-9.14" />
              <polyline points="22 4 12 14.01 9 11.01" />
            </svg>
            <span style={{ fontSize: 'var(--font-size-sm)' }}>
              {showResolved ? 'No issues.' : 'No open issues — all clear.'}
            </span>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
            {displayed.map((issue) => (
              <div
                key={issue.id}
                className="support-issue-row"
                style={{
                  display: 'grid',
                  gridTemplateColumns: 'auto 1fr auto auto auto auto',
                  alignItems: 'center',
                  gap: 'var(--space-3)',
                  padding: 'var(--space-3) var(--space-4)',
                  borderRadius: 'var(--radius-lg)',
                  backgroundColor: 'var(--color-bg-abyss)',
                  border: '1px solid var(--color-border)',
                }}
                onClick={() => canEdit && openEdit(issue)}
              >
                {/* Status */}
                <StatusPill status={issue.status} />

                {/* Content */}
                <div style={{ minWidth: 0 }}>
                  <p style={{
                    margin: 0,
                    fontSize: 'var(--font-size-sm)',
                    fontWeight: 'var(--font-weight-medium)',
                    color: 'var(--color-text-primary)',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                  }}>
                    {issue.title}
                  </p>
                  {issue.body && (
                    <p style={{
                      margin: '2px 0 0',
                      fontSize: 'var(--font-size-xs)',
                      color: 'var(--color-text-muted)',
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }}>
                      {issue.body.replace(/<[^>]*>/g, '').slice(0, 100)}
                    </p>
                  )}
                </div>

                {/* Category */}
                <CategoryPill category={issue.category} />

                {/* Severity */}
                <SeverityBars severity={issue.severity} />

                {/* Date */}
                <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', whiteSpace: 'nowrap', flexShrink: 0 }}
                  title={fmtDateMedium(issue.created_at)}>
                  {fmtRelative(issue.created_at)}
                </span>

                {/* Delete */}
                {canEdit && (
                  <button
                    onClick={e => { e.stopPropagation(); setDeleteId(issue.id) }}
                    title="Delete issue"
                    aria-label="Delete issue"
                    style={{
                      width: 26, height: 26,
                      borderRadius: 'var(--radius-sm)',
                      border: '1px solid transparent',
                      background: 'none',
                      color: 'var(--color-text-muted)',
                      cursor: 'pointer',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                      transition: 'color 0.12s, background 0.12s, border-color 0.12s',
                    }}
                    onMouseEnter={e => {
                      e.currentTarget.style.color = 'var(--color-danger)'
                      e.currentTarget.style.background = 'var(--color-danger-bg)'
                      e.currentTarget.style.borderColor = 'var(--color-danger)'
                    }}
                    onMouseLeave={e => {
                      e.currentTarget.style.color = 'var(--color-text-muted)'
                      e.currentTarget.style.background = 'none'
                      e.currentTarget.style.borderColor = 'transparent'
                    }}
                  >
                    <Icon name="delete" size={13} />
                  </button>
                )}
              </div>
            ))}
          </div>
        )}
      </Card>

      <EntryFormModal
        open={modal.open}
        entry={modal.entry}
        defaultType="issue"
        prefilledLinks={modal.entry ? undefined : [{ entity_type: 'customer', entity_id: customerId, display_name: customerName, locked: true }]}
        knownEntities={customerId ? { [customerId]: customerName } : undefined}
        onClose={() => setModal({ open: false, entry: null })}
        onSaved={() => { setModal({ open: false, entry: null }); load() }}
        onDelete={canEdit ? (id) => { setModal({ open: false, entry: null }); setDeleteId(id) } : null}
      />

      <ConfirmDialog
        open={!!deleteId}
        variant="danger"
        title="Delete Issue?"
        message="This issue and all its entity links will be permanently removed."
        confirmLabel="Delete"
        onConfirm={handleDelete}
        onClose={() => setDeleteId(null)}
        loading={deleting}
      />
    </>
  )
}

// ─── NotesCard ────────────────────────────────────────────────────────────────

function NotesCard({ customerId, customerName, canEdit }) {
  const { toast }                             = useToast()
  const [notes,    setNotes]                  = useState([])
  const [loading,  setLoading]                = useState(true)
  const [modal,    setModal]                  = useState({ open: false, entry: null })
  const [deleteId, setDeleteId]               = useState(null)
  const [deleting, setDeleting]               = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const data = await api.get(`/notes/by-entity/customer/${customerId}`)
      const all  = Array.isArray(data) ? data : []
      setNotes(all.filter(e => e.type === 'note').reverse())
    } catch { setNotes([]) }
    finally { setLoading(false) }
  }, [customerId])

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

  const handleDelete = async () => {
    setDeleting(true)
    try {
      await api.delete(`/notes/${deleteId}`)
      toast.success('Deleted', 'Note removed.')
      setDeleteId(null)
      load()
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to delete.')
    } finally { setDeleting(false) }
  }

  const openCreate  = ()      => setModal({ open: true, entry: null })
  const openEdit    = (entry) => setModal({ open: true, entry })

  return (
    <>
      <Card
        title="Notes"
        action={
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
            {notes.length > 0 && <StatusBadge variant="neutral">{notes.length}</StatusBadge>}
            {canEdit && (
              <Button variant="secondary" size="sm" onClick={openCreate}>
                + Add Note
              </Button>
            )}
          </div>
        }
      >

        {/* List */}
        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-8)' }}>
            <Spinner size="sm" />
          </div>
        ) : notes.length === 0 ? (
          <div style={{
            padding: 'var(--space-8)',
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            gap: 'var(--space-2)', color: 'var(--color-text-muted)',
          }}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
              <polyline points="14 2 14 8 20 8"/>
              <line x1="16" y1="13" x2="8" y2="13"/>
              <line x1="16" y1="17" x2="8" y2="17"/>
              <polyline points="10 9 9 9 8 9"/>
            </svg>
            <span style={{ fontSize: 'var(--font-size-sm)' }}>No notes yet.</span>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
            {notes.map((note) => (
              <div
                key={note.id}
                onClick={() => canEdit && openEdit(note)}
                style={{
                  display: 'flex',
                  alignItems: 'flex-start',
                  gap: 'var(--space-3)',
                  padding: 'var(--space-3) var(--space-4)',
                  borderRadius: 'var(--radius-lg)',
                  backgroundColor: 'var(--color-bg-abyss)',
                  border: '1px solid var(--color-border)',
                  cursor: canEdit ? 'pointer' : 'default',
                  transition: 'background-color 0.15s',
                }}
                onMouseEnter={e => { if (canEdit) e.currentTarget.style.backgroundColor = 'var(--color-bg-elevated)' }}
                onMouseLeave={e => { e.currentTarget.style.backgroundColor = 'var(--color-bg-abyss)' }}
              >
                <div style={{ flex: 1, minWidth: 0 }}>
                  <p style={{
                    margin: 0,
                    fontSize: 'var(--font-size-sm)',
                    fontWeight: 'var(--font-weight-medium)',
                    color: 'var(--color-text-primary)',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    marginBottom: 'var(--space-1)',
                  }}>
                    {note.title}
                  </p>
                  {note.body && (
                    <p style={{
                      margin: '0 0 var(--space-1)',
                      fontSize: 'var(--font-size-sm)',
                      color: 'var(--color-text-secondary)',
                      overflow: 'hidden',
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical',
                      lineHeight: 1.5,
                    }}>
                      {note.body.replace(/<[^>]*>/g, '')}
                    </p>
                  )}
                  <p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', margin: 0 }}>
                    {[note.author_name, note.created_at ? fmtDateMedium(note.created_at) : null].filter(Boolean).join(' · ')}
                  </p>
                </div>

                {canEdit && (
                  <button
                    onClick={e => { e.stopPropagation(); setDeleteId(note.id) }}
                    title="Delete note"
                    aria-label="Delete note"
                    style={{
                      background: 'none', border: 'none', cursor: 'pointer',
                      color: 'var(--color-text-muted)', padding: 'var(--space-1)',
                      display: 'flex', alignItems: 'center', flexShrink: 0,
                      transition: 'color 0.15s',
                    }}
                    onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-danger)' }}
                    onMouseLeave={e => { e.currentTarget.style.color = 'var(--color-text-muted)' }}
                  >
                    <Icon name="delete" size={14} color="currentColor" />
                  </button>
                )}
              </div>
            ))}
          </div>
        )}
      </Card>

      <EntryFormModal
        open={modal.open}
        entry={modal.entry}
        defaultType="note"
        prefilledLinks={modal.entry ? undefined : [{ entity_type: 'customer', entity_id: customerId, display_name: customerName, locked: true }]}
        knownEntities={customerId ? { [customerId]: customerName } : undefined}
        onClose={() => setModal({ open: false, entry: null })}
        onSaved={() => { setModal({ open: false, entry: null }); load() }}
        onDelete={canEdit ? (id) => { setModal({ open: false, entry: null }); setDeleteId(id) } : null}
      />

      <ConfirmDialog
        open={!!deleteId}
        variant="danger"
        title="Delete Note?"
        message="This note will be permanently removed."
        confirmLabel="Delete"
        onConfirm={handleDelete}
        onClose={() => setDeleteId(null)}
        loading={deleting}
      />
    </>
  )
}

// ─── SupportTab ───────────────────────────────────────────────────────────────

export default function SupportTab({ customer, canEdit }) {
  const customerName = [customer.surname, customer.name].filter(Boolean).join(' ') || customer.organization || ''
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>
      <IssuesCard customerId={customer.id} customerName={customerName} canEdit={canEdit} />
      <NotesCard  customerId={customer.id} customerName={customerName} canEdit={canEdit} />
    </div>
  )
}
