'use client';

import React, { useRef, useState } from 'react';
import { FiArrowRight, FiEye, FiEdit2, FiFileText, FiUsers, FiTrash2, FiCheckCircle, FiMoreVertical, FiPlusCircle, FiSearch, FiRefreshCw, FiClipboard, FiChevronDown, FiChevronUp } from 'react-icons/fi';
import type { PreviousNcRow } from '@/lib/api/types/previous-nc.types';
import {
  NC_STATUS_CONFIG,
  NC_SOURCE_CONFIG,
  getNcTypeMeta,
  formatDateWithHint,
  formatUserName,
  avatarGradient,
  firstInitial,
} from '@/lib/api/mappers/previous-nc.mappers';

interface ButtonConfig {
  key: string; icon: string; color: string; label: string; order: number; position: 'row' | 'toolbar';
}
interface ColumnConfig {
  key: string; type: string; label: string; order: number; sortable: boolean; default_visible: boolean;
}

interface Props {
  row: PreviousNcRow;
  visibleColumns: ColumnConfig[];
  rowButtons: ButtonConfig[];
  hasActionsColumn: boolean;
  mapColumnKeyToValue: (key: string, row: PreviousNcRow) => any;
  pdfBusy: string | null;
  onView: (row: PreviousNcRow) => void;
  onEdit: (row: PreviousNcRow) => void;
  onPdf: (row: PreviousNcRow) => void;
  onAttendance: (row: PreviousNcRow) => void;
  onDelete: (row: PreviousNcRow) => void;
  onFinalClosure: (row: PreviousNcRow) => void;
}

// label + icon + color for each known action key
const ACTION_META: Record<string, { label: string; icon: React.ReactNode; color: string }> = {
  'view': { label: 'View', icon: <FiArrowRight size={14} />, color: '#4338ca' },
  'view-all': { label: 'View', icon: <FiArrowRight size={14} />, color: '#4338ca' },
  'edit': { label: 'Edit', icon: <FiEdit2 size={14} />, color: '#c2410c' },
  'pdf': { label: 'NC PDF', icon: <FiFileText size={14} />, color: '#0f766e' },
  'attendance': { label: 'Attendance', icon: <FiUsers size={14} />, color: '#166534' },
  'final-closure': { label: 'Final closure', icon: <FiCheckCircle size={14} />, color: '#6d28d9' },
  'delete': { label: 'Delete', icon: <FiTrash2 size={14} />, color: '#dc2626' },
};

function renderCell(col: ColumnConfig, row: PreviousNcRow, value: any) {
  if (col.key === 'status') {
    const status = NC_STATUS_CONFIG[row.status] ?? NC_STATUS_CONFIG.unknown;
    return (
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '4px 10px', borderRadius: 99, background: status.bg, color: status.text, fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap' }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: status.dot }} />
        {status.label}
      </span>
    );
  }
  if (col.key === 'company_name') {
    const name = row.company_name ?? '—';
    return (
      <div className="pn-company" style={{ position: 'relative', maxWidth: 220 }}>
        <div
          style={{
            fontWeight: 600, fontSize: 13, color: '#111827',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}
        >
          {name}
        </div>
        <div className="pn-tip" style={{
          position: 'absolute', top: '100%', left: 0, zIndex: 200,
          marginTop: 4, padding: '6px 10px',
          background: '#0f172a', color: '#fff',
          fontSize: 12, fontWeight: 500, borderRadius: 6,
          whiteSpace: 'normal', maxWidth: 320, width: 'max-content',
          boxShadow: '0 6px 18px rgba(15,23,42,0.25)',
          display: 'none',
        }}>
          {name}
        </div>
      </div>
    );
  }
  if (col.key === 'audit_type') {
    const raw = (row.audit_type || '').toLowerCase();
    let cfg: { bg: string; color: string; border: string; Icon: React.ComponentType<{ size?: number }> } =
      { bg: '#f1f5f9', color: '#475569', border: '#cbd5e1', Icon: FiClipboard };
    if (raw.includes('initial')) {
      cfg = { bg: '#eef2ff', color: '#4338ca', border: '#c7d2fe', Icon: FiPlusCircle };
    } else if (raw.includes('surveillance')) {
      cfg = { bg: '#fffbeb', color: '#b45309', border: '#fde68a', Icon: FiSearch };
    } else if (raw.includes('re-assessment') || raw.includes('reassessment') || raw.includes('re-certification') || raw.includes('recert')) {
      cfg = { bg: '#f0fdf4', color: '#15803d', border: '#bbf7d0', Icon: FiRefreshCw };
    }
    const Icon = cfg.Icon;
    return row.audit_type ? (
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        padding: '4px 10px', borderRadius: 8,
        background: cfg.bg, color: cfg.color,
        border: `1px solid ${cfg.border}`,
        fontSize: 11, fontWeight: 700, whiteSpace: 'nowrap',
        letterSpacing: '0.02em',
      }}>
        <Icon size={12} /> {row.audit_type}
      </span>
    ) : (
      <span style={{ color: '#9ca3af', fontSize: 11 }}>—</span>
    );
  }
  if (col.key === 'nc_type') {
    const t = getNcTypeMeta(row.nc_type);
    return (
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '3px 9px', borderRadius: 99, background: t.bg, color: t.color, fontSize: 11, fontWeight: 700, border: `1px solid ${t.color}33`, whiteSpace: 'nowrap' }}>
        {t.icon} {t.label}
      </span>
    );
  }
  if (col.key === 'nc_code') {
    const src = NC_SOURCE_CONFIG[row.source];
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
        <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#0f766e', fontWeight: 600 }}>{value}</span>
        <span style={{ padding: '2px 8px', borderRadius: 99, background: src.bg, color: src.color, fontSize: 10, fontWeight: 600, width: 'fit-content' }}>📁 {src.label}</span>
      </div>
    );
  }
  if (col.key === 'created_at') {
    const d = formatDateWithHint(row.created_at);
    const recent = !!d.hint && (d.hint.includes('m ago') || d.hint.includes('h ago') || d.hint === 'just now');
    return (
      <div>
        <div style={{ fontSize: 13, color: '#111827', display: 'flex', alignItems: 'center', gap: 6 }}>
          {d.display}
          {d.hint && (
            <span style={{
              fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 99,
              background: recent ? '#0f766e' : '#f3f4f6',
              color: recent ? '#fff' : d.hintColor || '#6b7280',
            }}>
              {d.hint}
            </span>
          )}
        </div>
        <div style={{ fontSize: 11, color: '#6b7280', marginTop: 2 }}>
          {row.audit_type || '—'}
        </div>
      </div>
    );
  }
  if (col.key === 'created_by' || col.key === 'assigned_to') {
    const name = value;
    if (!name) return <span style={{ color: '#9ca3af', fontStyle: 'italic', fontSize: 11 }}>N/A</span>;
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <span style={{ width: 22, height: 22, borderRadius: '50%', background: avatarGradient(name), color: '#fff', fontSize: 10, fontWeight: 700, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          {firstInitial(name)}
        </span>
        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={formatUserName(name)}>{formatUserName(name)}</span>
      </div>
    );
  }
  if (value === null || value === undefined) return '—';
  return String(value);
}

export default function DynamicPreviousNcRow({
  row, visibleColumns, rowButtons, hasActionsColumn, mapColumnKeyToValue,
  pdfBusy, onView, onEdit, onPdf, onAttendance, onDelete, onFinalClosure,
}: Props) {
  const [open, setOpen] = useState(false);
  const [openUp, setOpenUp] = useState(false);
  // Screen coordinates of the trigger button (for fixed-position menu)
  const [menuPos, setMenuPos] = useState({ top: 0, bottom: 0, left: 0, right: 0 });
  // Which side of the trigger the menu anchors to:
  // 'right' → actions ⋮ button (menu grows left)
  // 'left'  → NC-code arrow (menu grows right)
  const [anchor, setAnchor] = useState<'left' | 'right'>('right');
  const btnRef = useRef<HTMLButtonElement>(null);
  const codeBtnRef = useRef<HTMLButtonElement>(null);

  const MENU_WIDTH = 180;

  const openMenuFrom = (el: HTMLElement | null, side: 'left' | 'right') => {
    if (!open && el) {
      const rect = el.getBoundingClientRect();
      setMenuPos({ top: rect.top, bottom: rect.bottom, left: rect.left, right: rect.right });
      setAnchor(side);
      const spaceBelow = window.innerHeight - rect.bottom;
      // approx menu height: each item ~38px + padding
      const menuHeight = rowButtons.length * 38 + 16;
      setOpenUp(spaceBelow < menuHeight);
    }
    setOpen((v) => !v);
  };

  const toggleMenu = () => openMenuFrom(btnRef.current, 'right');

  const handle = (key: string) => {
    setOpen(false);
    switch (key) {
      case 'view': case 'view-all': return onView(row);
      case 'edit': return onEdit(row);
      case 'pdf': return onPdf(row);
      case 'attendance': return onAttendance(row);
      case 'delete': return onDelete(row);
      case 'final-closure': return onFinalClosure(row);
    }
  };

  return (
    <tr style={{ borderTop: '1px solid #f1f5f9' }}>
      <style>{`.pn-company:hover .pn-tip { display: block !important; }`}</style>
      {visibleColumns.filter(c => c.key !== 'actions').map((col) => (
        <td key={col.key} style={{ padding: '12px 10px', fontSize: 12, color: '#374151', verticalAlign: 'top' }}>
          {col.key === 'nc_code' ? (
            // ✅ NC code + arrow dropdown (same menu as the ⋮ actions button)
            <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#0f766e', fontWeight: 600 }}>
                  {mapColumnKeyToValue(col.key, row)}
                </span>
                {rowButtons.length > 0 && (
                  <button
                    ref={codeBtnRef}
                    onClick={() => openMenuFrom(codeBtnRef.current, 'left')}
                    title="Actions"
                    style={{
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      width: 20, height: 20, borderRadius: 5,
                      border: `1px solid ${open && anchor === 'left' ? '#0f766e' : '#e2e8f0'}`,
                      background: open && anchor === 'left' ? '#f0fdfa' : '#fff',
                      color: open && anchor === 'left' ? '#0f766e' : '#94a3b8',
                      cursor: 'pointer', padding: 0,
                      transition: 'all 0.12s',
                    }}
                    onMouseEnter={(e) => {
                      if (!(open && anchor === 'left')) {
                        e.currentTarget.style.borderColor = '#0f766e';
                        e.currentTarget.style.color = '#0f766e';
                      }
                    }}
                    onMouseLeave={(e) => {
                      if (!(open && anchor === 'left')) {
                        e.currentTarget.style.borderColor = '#e2e8f0';
                        e.currentTarget.style.color = '#94a3b8';
                      }
                    }}
                  >
                    {open && anchor === 'left'
                      ? <FiChevronUp size={12} />
                      : <FiChevronDown size={12} />}
                  </button>
                )}
              </div>
              <span style={{ padding: '2px 8px', borderRadius: 99, background: NC_SOURCE_CONFIG[row.source].bg, color: NC_SOURCE_CONFIG[row.source].color, fontSize: 10, fontWeight: 600, width: 'fit-content' }}>
                📁 {NC_SOURCE_CONFIG[row.source].label}
              </span>
            </div>
          ) : (
            renderCell(col, row, mapColumnKeyToValue(col.key, row))
          )}
        </td>
      ))}

      {hasActionsColumn && (
        <td style={{ padding: '12px 10px', verticalAlign: 'top' }}>
          <div style={{ position: 'relative', display: 'inline-block' }}>
            <button
              ref={btnRef}
              onClick={toggleMenu}
              title="Actions"
              style={{
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                width: 30, height: 30, borderRadius: 6,
                border: '1px solid #e2e8f0', background: open ? '#f1f5f9' : '#fff',
                color: '#475569', cursor: 'pointer', padding: 0,
              }}
            >
              <FiMoreVertical size={16} />
            </button>

            {open && (
              <>
                {/* backdrop closes the menu when clicking elsewhere */}
                <div
                  onClick={() => setOpen(false)}
                  style={{ position: 'fixed', inset: 0, zIndex: 990 }}
                />
                {/* Menu uses position:fixed so it is never clipped by the table.
                    It anchors its RIGHT edge to the button and flips up/down. */}
                <div
                  style={{
                    position: 'fixed',
                    ...(openUp
                      ? { bottom: window.innerHeight - menuPos.top + 6 }
                      : { top: menuPos.bottom + 6 }),
                    left: anchor === 'left'
                      ? Math.min(menuPos.left, window.innerWidth - MENU_WIDTH - 8)
                      : Math.max(8, menuPos.right - MENU_WIDTH),
                    zIndex: 1000,
                    width: MENU_WIDTH, background: '#fff',
                    border: '1px solid #e2e8f0', borderRadius: 8,
                    boxShadow: '0 8px 24px rgba(15,23,42,0.12)',
                    padding: 4, display: 'flex', flexDirection: 'column', gap: 2,
                  }}
                >
                  {rowButtons.length === 0 && (
                    <span style={{ fontSize: 11, color: '#9ca3af', padding: '8px 10px' }}>No actions</span>
                  )}
                  {rowButtons.map((btn) => {
                    const meta = ACTION_META[btn.key];
                    if (!meta) return null;
                    return (
                      <button
                        key={btn.key}
                        onClick={() => handle(btn.key)}
                        style={{
                          display: 'flex', alignItems: 'center', gap: 8,
                          width: '100%', textAlign: 'left',
                          padding: '8px 10px', borderRadius: 6,
                          border: 'none', background: 'transparent',
                          color: meta.color, fontSize: 12, fontWeight: 600, cursor: 'pointer',
                        }}
                        onMouseEnter={(e) => { e.currentTarget.style.background = '#f8fafc'; }}
                        onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
                      >
                        {meta.icon} {meta.label}
                      </button>
                    );
                  })}
                </div>
              </>
            )}
          </div>
        </td>
      )}
    </tr>
  );
}