// frontend/src/pages/crm/customers/CustomerDetail.jsx
// Main Customer Detail page — profile header, action menu, tab selector, tab content

import { useState, useEffect, useCallback, useRef } from 'react'
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import { ProfilePageHeaderActions } from '@/components/ui/ProfilePageHeader'
import Button from '@/components/ui/Button'
import Tabs from '@/components/ui/Tabs'
import Spinner from '@/components/ui/Spinner'
import {
  InitNegotiationsModal,
  SendMessageModal,
  RecordIssueModal,
  RecordPaymentModal,
  AddFilesModal,
} from '@/modals/crm/QuickEntryModals'
import OverviewTab from '@/pages/crm/customers/tabs/OverviewTab'
import OrdersTab from '@/pages/crm/customers/tabs/OrdersTab'
import FinancialsTab from '@/pages/crm/customers/tabs/FinancialsTab'
import SupportTab from '@/pages/crm/customers/tabs/SupportTab'
import CommunicationTab from '@/pages/crm/customers/tabs/CommunicationTab'
import QuotationsTab from '@/pages/crm/customers/tabs/QuotationsTab'
import FilesTab from '@/pages/crm/customers/tabs/FilesTab'

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

const TAB_DEFINITIONS = [
  { key: 'overview',      label: 'Overview'       },
  { key: 'communication', label: 'Communication'  },
  { key: 'quotations',    label: 'Quotations'     },
  { key: 'orders',        label: 'Orders'         },
  { key: 'finance',       label: 'Finance'        },
  { key: 'files',         label: 'Files & Media'  },
  { key: 'devices',       label: 'Devices'        },
  { key: 'support',       label: 'Support'        },
]

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

// ─── Coming-soon stub ─────────────────────────────────────────────────────────

function TabComingSoon({ label }) {
  return (
    <div style={{
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      padding: 'var(--space-16)',
      gap: 'var(--space-3)',
    }}>
      <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--color-text-muted)' }}>
        <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83" />
      </svg>
      <p style={{ fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-secondary)', margin: 0 }}>{label}</p>
      <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', margin: 0 }}>This tab is being built.</p>
    </div>
  )
}

// ─── New Action dropdown menu ─────────────────────────────────────────────────

const ACTION_ITEMS = [
  {
    key: 'init-neg',
    label: 'Init Negotiations',
    description: 'Start a new order at negotiating stage',
    icon: (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/>
      </svg>
    ),
  },
  {
    key: 'send-message',
    label: 'Send Message',
    description: 'Compose and send an email',
    icon: (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
      </svg>
    ),
  },
  {
    key: 'record-issue',
    label: 'Record Issue',
    description: 'Log a tech issue or support request',
    icon: (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
      </svg>
    ),
  },
  {
    key: 'record-payment',
    label: 'Record Payment',
    description: 'Log a payment or invoice transaction',
    icon: (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/>
      </svg>
    ),
  },
  {
    key: 'add-files',
    label: 'Add Files',
    description: 'Upload files for this customer',
    icon: (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
      </svg>
    ),
  },
]

function NewActionButton({ onSelect }) {
  const [open, setOpen] = useState(false)
  const ref = useRef(null)

  useEffect(() => {
    if (!open) return
    const handler = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false) }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [open])

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <Button variant="primary" size="md" onClick={() => setOpen(v => !v)}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' }}>
          + New Action
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="6 9 12 15 18 9" />
          </svg>
        </span>
      </Button>

      {open && (
        <div style={{
          position: 'absolute',
          top: 'calc(100% + var(--space-2))',
          right: 0,
          zIndex: 50,
          backgroundColor: 'var(--color-bg-elevated)',
          border: '1px solid var(--color-border-strong)',
          borderRadius: 'var(--radius-lg)',
          boxShadow: 'var(--shadow-lg)',
          overflow: 'hidden',
          minWidth: 240,
          animation: 'slide-up 0.12s ease',
        }}>
          {ACTION_ITEMS.map((item, i) => (
            <button
              key={item.key}
              type="button"
              onClick={() => { setOpen(false); onSelect(item.key) }}
              style={{
                display: 'flex',
                alignItems: 'flex-start',
                gap: 'var(--space-3)',
                width: '100%',
                padding: 'var(--space-3) var(--space-4)',
                borderTop: i > 0 ? '1px solid var(--color-border)' : 'none',
                background: 'none',
                border: 'none',
                borderTop: i > 0 ? '1px solid var(--color-border)' : 'none',
                cursor: 'pointer',
                textAlign: 'left',
                transition: 'background-color var(--transition-fast)',
              }}
              onMouseEnter={e => e.currentTarget.style.backgroundColor = 'var(--color-bg-island)'}
              onMouseLeave={e => e.currentTarget.style.backgroundColor = 'transparent'}
            >
              <div style={{
                width: 30,
                height: 30,
                borderRadius: 'var(--radius-md)',
                backgroundColor: 'var(--color-bg-surface)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: 'var(--color-primary)',
                flexShrink: 0,
                marginTop: 1,
              }}>
                {item.icon}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                <span style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
                  {item.label}
                </span>
                <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
                  {item.description}
                </span>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  )
}

// ─── Main component ───────────────────────────────────────────────────────────

export default function CustomerDetail() {
  const { id }   = useParams()
  const navigate = useNavigate()
  const [searchParams, setSearchParams] = useSearchParams()
  const { hasPermission } = useAuth()
  const canEdit = hasPermission('crm_customers', 'full_access')

  // ── State ──────────────────────────────────────────────────────────────────
  const [customer, setCustomer]   = useState(null)
  const [loading, setLoading]     = useState(true)
  const [error, setError]         = useState('')
  const [activeTab, setActiveTab] = useState(() => resolveInitialTab(searchParams))

  // Modal visibility
  const [modal, setModal] = useState(null) // 'init-neg' | 'send-message' | 'record-issue' | 'record-payment' | 'add-files' | null

  // Orders for RecordPaymentModal order-ref selector
  const [orders, setOrders] = useState([])

  // ── Data fetching ──────────────────────────────────────────────────────────
  const loadCustomer = useCallback((silent = false) => {
    if (!silent) { setLoading(true); setError('') }
    api.get(`/crm/customers/${id}`)
      .then(data => setCustomer(data))
      .catch(err  => { if (!silent) setError(err.message || 'Failed to load customer') })
      .finally(() => { if (!silent) setLoading(false) })
  }, [id])

  const loadOrders = useCallback(() => {
    api.get(`/crm/customers/${id}/orders`)
      .then(d => setOrders(d.orders || []))
      .catch(() => {})
  }, [id])

  useEffect(() => { loadCustomer() }, [loadCustomer])
  useEffect(() => { loadOrders() }, [loadOrders])

  const reloadFinancials = useCallback(() => {
    loadCustomer(true)
    loadOrders()
  }, [loadCustomer, loadOrders])

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

  // ── Modal dispatch ─────────────────────────────────────────────────────────
  const openModal  = key => setModal(key)
  const closeModal = ()  => setModal(null)

  const handleActionSuccess = () => {
    loadCustomer() // refresh customer stats after any quick action
  }

  // ── Render states ──────────────────────────────────────────────────────────
  if (loading) {
    return (
      <div className="page-wrapper" style={{ alignItems: 'center', justifyContent: 'center', minHeight: '60vh' }}>
        <Spinner size="lg" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="page-wrapper">
        <div style={{
          backgroundColor: 'var(--color-danger-bg)',
          border: '1px solid var(--color-danger)',
          borderRadius: 'var(--radius-lg)',
          padding: 'var(--space-6)',
          color: 'var(--color-danger)',
          fontSize: 'var(--font-size-base)',
        }}>
          {error}
        </div>
      </div>
    )
  }

  if (!customer) return null

  // ── Derived display values ─────────────────────────────────────────────────
  const displayName = [customer.name, customer.surname].filter(Boolean).join(' ')
    || customer.organization
    || 'Unknown Customer'

  const subtitleParts = [
    customer.organization,
    customer.location?.city,
    customer.location?.country,
  ].filter(Boolean)
  const subtitle = subtitleParts.join(' · ') || undefined

  // ── Tab content ────────────────────────────────────────────────────────────
  function renderTabContent() {
    switch (activeTab) {
      case 'overview':
        return <OverviewTab customer={customer} canEdit={canEdit} onCustomerUpdated={setCustomer} onTabChange={handleTabChange} />
      case 'communication': return <CommunicationTab customer={customer} canEdit={canEdit} />
      case 'quotations':    return <QuotationsTab customer={customer} canEdit={canEdit} />
      case 'orders':        return <OrdersTab customer={customer} orders={orders} canEdit={canEdit} onReloadOrders={loadOrders} />
      case 'finance':       return <FinancialsTab customer={customer} orders={orders} canEdit={canEdit} onCustomerUpdated={setCustomer} onReloadOrders={reloadFinancials} />
      case 'files':         return <FilesTab customer={customer} canEdit={canEdit} />
      case 'devices':       return <TabComingSoon label="Devices" />
      case 'support':       return <SupportTab customer={customer} canEdit={canEdit} onCustomerUpdated={setCustomer} />
      default:              return <TabComingSoon label="Overview" />
    }
  }

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

        {/* ── Profile Page Header ────────────────────────────────────────── */}
        <ProfilePageHeaderActions
          name={displayName}
          subtitle={subtitle}
        >
          <Button variant="ghost" size="md" onClick={() => navigate('/crm/customers')}>
            ← Customers
          </Button>
          {canEdit && (
            <Button variant="secondary" size="md" onClick={() => navigate(`/crm/customers/${id}/edit`)}>
              Edit Profile
            </Button>
          )}
          <NewActionButton onSelect={openModal} />
        </ProfilePageHeaderActions>

        {/* ── Tab Bar ───────────────────────────────────────────────────── */}
        <Tabs
          tabs={TAB_DEFINITIONS}
          active={activeTab}
          onChange={handleTabChange}
          variant="line"
        />

        {/* ── Tab Content ───────────────────────────────────────────────── */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {renderTabContent()}
        </div>

      </div>

      {/* ── Quick-entry modals (portaled) ──────────────────────────────── */}
      <InitNegotiationsModal
        open={modal === 'init-neg'}
        customerId={id}
        onClose={closeModal}
        onSuccess={handleActionSuccess}
      />
      <SendMessageModal
        open={modal === 'send-message'}
        customer={customer}
        onClose={closeModal}
        onSent={handleActionSuccess}
      />
      <RecordIssueModal
        open={modal === 'record-issue'}
        customerId={id}
        onClose={closeModal}
        onSuccess={handleActionSuccess}
      />
      <RecordPaymentModal
        open={modal === 'record-payment'}
        customerId={id}
        orders={orders}
        onClose={closeModal}
        onSuccess={handleActionSuccess}
      />
      <AddFilesModal
        open={modal === 'add-files'}
        customerId={id}
        onClose={closeModal}
        onSuccess={() => { closeModal(); handleTabChange('files') }}
      />
    </>
  )
}
