'use client';

import React, { useState } from 'react';
import { FiArrowRight, FiEdit2, FiFileText, FiUsers, FiTrash2, FiCheckCircle, FiMoreVertical } 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 Props {
  row: PreviousNcRow;
  onView: (row: PreviousNcRow) => void;
  onEdit: (row: PreviousNcRow) => void;
  onPdf: (row: PreviousNcRow) => void;
  onAttendance: (row: PreviousNcRow) => void;
  onDelete: (row: PreviousNcRow) => void;
  onFinalClosure: (row: PreviousNcRow) => void;
  pdfBusy: string | null;
  permittedActions: Set<string>;
}

export default function PreviousNcRowComponent({
  row, onView, onEdit, onPdf, onAttendance, onDelete, onFinalClosure, pdfBusy, permittedActions,
}: Props) {
  const [open, setOpen] = useState(false);

  const status = NC_STATUS_CONFIG[row.status] ?? NC_STATUS_CONFIG.unknown;
  const typeMeta = getNcTypeMeta(row.nc_type);
  const sourceMeta = NC_SOURCE_CONFIG[row.source];

  const dateInfo = formatDateWithHint(row.created_at);
  const isRecent =
    !!dateInfo.hint &&
    (dateInfo.hint.includes('m ago') || dateInfo.hint.includes('h ago') || dateInfo.hint === 'just now');

  const ncCode = `NC-${row.source}-${String(row.id).padStart(6, '0')}`;

  const canView = permittedActions.has('view') || permittedActions.has('view-all');
  const canEdit = permittedActions.has('edit');
  const canPdf = permittedActions.has('pdf') || canView;
  const canAttendance = permittedActions.has('attendance') || canView;
  const canDelete = permittedActions.has('delete');
  const canFinalClosure = permittedActions.has('final-closure');

  const noActions = !canView && !canEdit && !canPdf && !canAttendance && !canDelete && !canFinalClosure;

  const run = (fn: () => void) => { setOpen(false); fn(); };

  const menuItem = (color: string, icon: React.ReactNode, label: string, onClick: () => void) => (
    <button
      onClick={onClick}
      style={{
        display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'left',
        padding: '8px 10px', borderRadius: 6, border: 'none', background: 'transparent',
        color, fontSize: 12, fontWeight: 600, cursor: 'pointer',
      }}
      onMouseEnter={(e) => { e.currentTarget.style.background = '#f8fafc'; }}
      onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
    >
      {icon} {label}
    </button>
  );

  return (
    <tr style={{ borderTop: '1px solid #f1f5f9', background: isRecent ? '#f0fdfa' : 'transparent' }}>
      {/* 1. NC Code */}
      <td style={{ padding: '12px 10px', width: 170, verticalAlign: 'top' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 5 }}>
          <span
            onClick={() => { if (canView) onView(row); }}
            style={{
              fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
              color: canView ? '#0f766e' : '#9ca3af', fontWeight: 600,
              whiteSpace: 'nowrap', cursor: canView ? 'pointer' : 'not-allowed',
            }}
          >
            {ncCode}
          </span>
          <span style={{ padding: '2px 8px', borderRadius: 99, background: sourceMeta.bg, color: sourceMeta.color, fontSize: 10, fontWeight: 600, whiteSpace: 'nowrap' }}>
            📁 {sourceMeta.label}
          </span>
        </div>
      </td>

      {/* 2. Company */}
      <td style={{ padding: '12px 10px', width: 220, verticalAlign: 'top' }}>
        <div style={{ fontWeight: 600, fontSize: 13, color: '#111827', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={row.company_name ?? ''}>
          {row.company_name ?? '—'}
        </div>
        {row.contact_primary && (
          <div style={{ fontSize: 11, color: '#6b7280', marginTop: 2 }}>{row.contact_primary}</div>
        )}
      </td>

      {/* 3. Date / Time */}
      <td style={{ padding: '12px 10px', width: 150, verticalAlign: 'top' }}>
        <div style={{ fontSize: 13, color: '#111827', display: 'flex', alignItems: 'center', gap: 6 }}>
          {dateInfo.display}
          {dateInfo.hint && (
            <span style={{ fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 99, background: isRecent ? '#0f766e' : '#f3f4f6', color: isRecent ? '#fff' : dateInfo.hintColor || '#6b7280' }}>
              {dateInfo.hint}
            </span>
          )}
        </div>
        <div style={{ fontSize: 11, color: '#6b7280', marginTop: 2 }}>{row.audit_type || '—'}</div>
      </td>

      {/* 4. NC Type */}
      <td style={{ padding: '12px 10px', width: 170, verticalAlign: 'top' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '3px 9px', borderRadius: 99, background: typeMeta.bg, color: typeMeta.color, fontSize: 11, fontWeight: 700, whiteSpace: 'nowrap', border: `1px solid ${typeMeta.color}33` }}>
          {typeMeta.icon} {typeMeta.label}
        </span>
        <div style={{ fontSize: 10, color: '#9ca3af', marginTop: 4 }}>
          {row.entries_count > 0 ? `${row.entries_count} finding${row.entries_count !== 1 ? 's' : ''}` : 'no findings'}
        </div>
      </td>

      {/* 5. Created By */}
      <td style={{ padding: '12px 10px', width: 120, fontSize: 12, color: '#374151', verticalAlign: 'top' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 22, height: 22, borderRadius: '50%', background: avatarGradient(row.created_by_name), color: '#fff', fontSize: 10, fontWeight: 700, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            {firstInitial(row.created_by_name)}
          </span>
          <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={formatUserName(row.created_by_name)}>
            {formatUserName(row.created_by_name)}
          </span>
        </div>
      </td>

      {/* 6. Assigned To */}
      <td style={{ padding: '12px 10px', width: 120, fontSize: 12, color: '#374151', verticalAlign: 'top' }}>
        {row.assigned_to_name ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', background: avatarGradient(row.assigned_to_name), color: '#fff', fontSize: 10, fontWeight: 700, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              {firstInitial(row.assigned_to_name)}
            </span>
            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={formatUserName(row.assigned_to_name)}>
              {formatUserName(row.assigned_to_name)}
            </span>
          </div>
        ) : (
          <span style={{ color: '#9ca3af', fontStyle: 'italic', fontSize: 11 }}>N/A</span>
        )}
      </td>

      {/* 7. Status */}
      <td style={{ padding: '12px 10px', width: 100, verticalAlign: 'top' }}>
        <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>
      </td>

      {/* 8. Actions — dropdown menu, gated by permittedActions */}
      <td style={{ padding: '12px 10px', width: 180, verticalAlign: 'top' }}>
        {noActions ? (
          <span style={{ fontSize: 11, color: '#9ca3af', fontStyle: 'italic' }}>—</span>
        ) : (
          <div style={{ position: 'relative', display: 'inline-block' }}>
            <button
              onClick={() => setOpen((v) => !v)}
              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 && (
              <>
                <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 90 }} />
                <div
                  style={{
                    position: 'absolute', top: 34, right: 0, zIndex: 100,
                    minWidth: 160, 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,
                  }}
                >
                  {canView && menuItem('#4338ca', <FiArrowRight size={14} />, 'View', () => run(() => onView(row)))}
                  {canEdit && menuItem('#c2410c', <FiEdit2 size={14} />, 'Edit', () => run(() => onEdit(row)))}
                  {canPdf && menuItem('#0f766e', <FiFileText size={14} />, 'NC PDF', () => run(() => onPdf(row)))}
                  {canAttendance && menuItem('#166534', <FiUsers size={14} />, 'Attendance', () => run(() => onAttendance(row)))}
                  {canFinalClosure && menuItem('#6d28d9', <FiCheckCircle size={14} />, 'Final closure', () => run(() => onFinalClosure(row)))}
                  {canDelete && menuItem('#dc2626', <FiTrash2 size={14} />, 'Delete', () => run(() => onDelete(row)))}
                </div>
              </>
            )}
          </div>
        )}
      </td>
    </tr>
  );
}