'use client';

import React, { useRef, useState } from 'react';
import {
  FiFileText,
  FiPaperclip,
  FiEye,
  FiTrash2,
  FiMoreVertical,
} from 'react-icons/fi';
import {
  getNcTypeMeta,
  avatarGradient,
  firstInitial,
  formatUserName,
} from '@/lib/api/mappers/previous-nc.mappers';
import type { FinalClosureRow as Row } from '@/lib/api/final-closure.api';

interface Props {
  row: Row;
  index: number;
  reportBusy: string | null;
  isSuperAdmin: boolean;
  onView: (row: Row) => void;
  onReport: (row: Row) => void;
  onEvidence: (row: Row, file: Row['evidence_files'][number]) => void;
  onDelete: (row: Row) => void;
}

function fmtDate(d?: string | null): string {
  if (!d) return 'N/A';
  const dt = new Date(d);
  if (isNaN(dt.getTime())) return 'N/A';
  return dt.toLocaleDateString('en-GB', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  });
}

const td: React.CSSProperties = {
  padding: '12px 10px',
  fontSize: 12,
  color: '#374151',
  verticalAlign: 'top',
};

function NA() {
  return <span style={{ color: '#dc2626', fontWeight: 600 }}>N/A</span>;
}

function PersonCell({ name }: { name: string | null }) {
  if (!name)
    return (
      <span style={{ color: '#9ca3af', fontStyle: 'italic', fontSize: 11 }}>
        Unknown
      </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>
  );
}

export default function FinalClosureRow({
  row,
  index,
  reportBusy,
  isSuperAdmin,
  onView,
  onReport,
  onEvidence,
  onDelete,
}: Props) {
  const [open, setOpen] = useState(false);
  const [openUp, setOpenUp] = useState(false);
  const [menuPos, setMenuPos] = useState({ top: 0, bottom: 0, right: 0 });
  const btnRef = useRef<HTMLButtonElement>(null);
  const MENU_WIDTH = 180;

  const hasReport = !!row.signed_copy_path;
  const evidence = row.evidence_files || [];
  const hasEvidenceText = !!row.evidence_received?.trim();
  const evidenceWithFiles = evidence.filter((e) => !!e.document_path);
  const reportKey = `report-${row.source}-${row.nc_id}`;
  const t = getNcTypeMeta(row.nc_type ?? '');
  const hasAnyEvidence =
    hasEvidenceText || evidenceWithFiles.length > 0 || row.evidence_count > 0;

  // Action items (Delete only for super-admin)
  const actionCount = 1 + (isSuperAdmin ? 1 : 0);

  const toggleMenu = () => {
    if (!open && btnRef.current) {
      const rect = btnRef.current.getBoundingClientRect();
      setMenuPos({ top: rect.top, bottom: rect.bottom, right: rect.right });
      const spaceBelow = window.innerHeight - rect.bottom;
      const menuHeight = actionCount * 38 + 16;
      setOpenUp(spaceBelow < menuHeight);
    }
    setOpen((v) => !v);
  };

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

  return (
    <tr style={{ borderTop: '1px solid #f1f5f9' }}>
      <style>{`.fc-company:hover .fc-tip { display:block !important; }`}</style>

      {/* # */}
      <td style={{ ...td, color: '#64748b', fontWeight: 600 }}>{index}</td>

      {/* Company Name */}
      <td style={td}>
        <div className="fc-company" style={{ position: 'relative', maxWidth: 220 }}>
          <div
            style={{
              fontWeight: 600,
              fontSize: 13,
              color: '#111827',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {row.company_name ?? '—'}
          </div>
          <div
            className="fc-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',
            }}
          >
            {row.company_name ?? '—'}
          </div>
        </div>
      </td>

      {/* Auditor */}
      <td style={td}>
        <PersonCell name={row.auditor_name} />
      </td>

      {/* Uploaded By */}
      <td style={td}>
        <PersonCell name={row.uploaded_by} />
      </td>

      {/* Evidence Received */}
      <td style={td}>
        {hasAnyEvidence ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
            {hasEvidenceText && (
              <span
                style={{
                  fontSize: 12,
                  color: '#0f172a',
                  maxWidth: 220,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}
                title={row.evidence_received ?? ''}
              >
                {row.evidence_received}
              </span>
            )}
            {evidenceWithFiles.length > 0 ? (
              <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
                {evidenceWithFiles.map((f) => (
                  <button
                    key={f.entry_id}
                    onClick={() => onEvidence(row, f)}
                    title={f.submitted_docs || 'View evidence'}
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: 4,
                      padding: '2px 8px',
                      borderRadius: 99,
                      background: '#f0fdfa',
                      color: '#0f766e',
                      border: '1px solid #99f6e4',
                      fontSize: 10,
                      fontWeight: 700,
                      cursor: 'pointer',
                    }}
                  >
                    <FiPaperclip size={10} />
                    {f.submitted_docs
                      ? f.submitted_docs.length > 14
                        ? f.submitted_docs.slice(0, 14) + '…'
                        : f.submitted_docs
                      : `Evidence #${f.entry_id}`}
                  </button>
                ))}
              </div>
            ) : (
              !hasEvidenceText &&
              row.evidence_count > 0 && (
                <span
                  style={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: 4,
                    padding: '2px 8px',
                    borderRadius: 99,
                    background: '#f0fdfa',
                    color: '#0f766e',
                    border: '1px solid #99f6e4',
                    fontSize: 10,
                    fontWeight: 700,
                    width: 'fit-content',
                  }}
                >
                  <FiPaperclip size={10} />
                  {row.evidence_count} file{row.evidence_count > 1 ? 's' : ''}
                </span>
              )
            )}
          </div>
        ) : (
          <NA />
        )}
      </td>

      {/* Final Closure Report */}
      <td style={td}>
        {hasReport ? (
          <button
            onClick={() => onReport(row)}
            disabled={reportBusy === reportKey}
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 5,
              padding: '5px 10px',
              borderRadius: 7,
              background: '#0f766e',
              color: '#fff',
              border: 'none',
              fontSize: 11,
              fontWeight: 700,
              cursor: reportBusy === reportKey ? 'wait' : 'pointer',
              opacity: reportBusy === reportKey ? 0.7 : 1,
              whiteSpace: 'nowrap',
            }}
          >
            <FiFileText size={12} />
            {reportBusy === reportKey ? 'Opening…' : 'View PDF'}
          </button>
        ) : (
          <NA />
        )}
      </td>

      {/* NC Type */}
      <td style={td}>
        {row.nc_type ? (
          <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>
        ) : (
          <span style={{ color: '#9ca3af', fontSize: 11 }}>N/A</span>
        )}
      </td>

      {/* Closure Date */}
      <td style={{ ...td, color: '#111827' }}>{fmtDate(row.closure_date)}</td>

      {/* Closed At */}
      <td style={{ ...td, color: '#111827' }}>{fmtDate(row.closed_at)}</td>

      {/* Final Closure Created At */}
      <td style={{ ...td, color: '#111827' }}>{fmtDate(row.finalized_at)}</td>

      {/* Remarks */}
      <td style={td}>
        {row.remarks?.trim() ? (
          <span
            style={{
              maxWidth: 200,
              display: 'inline-block',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
            title={row.remarks}
          >
            {row.remarks}
          </span>
        ) : (
          <NA />
        )}
      </td>

      {/* Actions — dropdown menu (same pattern as DynamicPreviousNcRow) */}
      <td style={{ ...td }}>
        <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 && (
            <>
              <div
                onClick={() => setOpen(false)}
                style={{ position: 'fixed', inset: 0, zIndex: 990 }}
              />
              <div
                style={{
                  position: 'fixed',
                  ...(openUp
                    ? { bottom: window.innerHeight - menuPos.top + 6 }
                    : { top: menuPos.bottom + 6 }),
                  left: 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,
                }}
              >
                <MenuItem
                  color="#4338ca"
                  icon={<FiEye size={14} />}
                  label="View"
                  onClick={() => run(() => onView(row))}
                />
                {isSuperAdmin && (
                  <MenuItem
                    color="#dc2626"
                    icon={<FiTrash2 size={14} />}
                    label="Delete closure"
                    onClick={() => run(() => onDelete(row))}
                  />
                )}
              </div>
            </>
          )}
        </div>
      </td>
    </tr>
  );
}

function MenuItem({
  color,
  icon,
  label,
  onClick,
}: {
  color: string;
  icon: React.ReactNode;
  label: string;
  onClick: () => void;
}) {
  return (
    <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>
  );
}
