'use client';

import React from 'react';
import { FiCheck, FiX } from 'react-icons/fi';
import type { EditableEntry } from './findings.types';
import { isDraft } from './findings.types';
import type { ClosureRow } from '@/lib/api/types/previous-nc.types';

// ═══════════════════════════════════════════════════════════════════════
// 🆕 PHASE 2A — Closure Verification Table
// ═══════════════════════════════════════════════════════════════════════
// Shows ONLY the findings ticked in the picker. Auditor fills in
// Evidence Received, Submitted Documents, and sets Result per row.
// ═══════════════════════════════════════════════════════════════════════

interface Props {
  entries: EditableEntry[];
  selectedIds: Set<number>;
  rows: ClosureRow[];
  onRowChange: (entryId: number, patch: Partial<ClosureRow>) => void;
  disabled?: boolean;
}

export default function ClosureVerificationTable({
  entries,
  selectedIds,
  rows,
  onRowChange,
  disabled,
}: Props) {
  // Build display list — entries that are ticked, in original order
  const tickedEntries = entries.filter(
    (e) => !isDraft(e) && selectedIds.has(e.id),
  );

  const rowMap = new Map(rows.map((r) => [r.entry_id, r]));

  if (tickedEntries.length === 0) {
    return (
      <div
        style={{
          padding: '20px 18px',
          textAlign: 'center',
          background: '#fafbfc',
          border: '1px dashed #cbd5e1',
          borderRadius: 8,
          fontSize: 12,
          color: '#94a3b8',
        }}
      >
        Select findings above to start filling verification details.
      </div>
    );
  }

  return (
    <div>
      <div
        style={{
          fontSize: 12,
          fontWeight: 700,
          color: '#0b1220',
          marginBottom: 3,
        }}
      >
        Verification comments — one row per selected finding
      </div>
      <div
        style={{
          fontSize: 11,
          color: '#64748b',
          marginBottom: 10,
        }}
      >
        Fill in details and set the result for each finding. Only Accepted
        findings will be marked Closed.
      </div>

      <div
        style={{
          border: '1px solid #e2e8f0',
          borderRadius: 8,
          overflow: 'hidden',
          overflowX: 'auto',
        }}
      >
        <div style={{ minWidth: 880 }}>
          {/* Header */}
          <div
            style={{
              display: 'grid',
              gridTemplateColumns:
                '44px 1.2fr 1.3fr 80px 90px 1.4fr 110px',
              gap: 0,
              background: '#fafbfc',
              borderBottom: '1px solid #e2e8f0',
              fontSize: 9,
              fontWeight: 700,
              color: '#64748b',
              textTransform: 'uppercase',
              letterSpacing: '0.07em',
            }}
          >
            <div style={{ padding: '10px 10px' }}>#</div>
            <div style={{ padding: '10px 10px' }}>NCR statement</div>
            <div style={{ padding: '10px 10px' }}>Evidence received</div>
            <div style={{ padding: '10px 10px' }}>NC type</div>
            <div style={{ padding: '10px 10px' }}>Clause</div>
            <div style={{ padding: '10px 10px' }}>Submitted documents</div>
            <div style={{ padding: '10px 10px' }}>Result</div>
          </div>

          {/* Rows */}
          {tickedEntries.map((e) => {
            const realIndex =
              entries.filter((x) => !isDraft(x)).indexOf(e) + 1;
            const row = rowMap.get(e.id) || emptyRow(e.id);
            const stripe = row.result_accepted
              ? '#15803d'
              : isAcceptanceSet(row, rows)
                ? '#d97706'
                : '#e2e8f0';
            const bg = row.result_accepted
              ? '#f0fdf4'
              : isAcceptanceSet(row, rows) && !row.result_accepted
                ? '#fef9f3'
                : '#fff';

            return (
              <div
                key={e.id}
                style={{
                  display: 'grid',
                  gridTemplateColumns:
                    '44px 1.2fr 1.3fr 80px 90px 1.4fr 110px',
                  gap: 0,
                  borderBottom: '1px solid #f1f5f9',
                  alignItems: 'stretch',
                  background: bg,
                }}
              >
                <div
                  style={{
                    padding: '12px 10px',
                    fontFamily: "'JetBrains Mono', monospace",
                    fontSize: 12,
                    fontWeight: 700,
                    color: '#185FA5',
                    borderLeft: `3px solid ${stripe}`,
                    background: `${stripe}10`,
                  }}
                >
                  {String(realIndex).padStart(2, '0')}
                </div>
                <div
                  style={{
                    padding: '11px 10px',
                    fontSize: 11,
                    color: '#1f2937',
                    lineHeight: 1.45,
                  }}
                >
                  {e.ncr_statement || '(no statement)'}
                </div>
                <div style={{ padding: '7px 10px' }}>
                  <input
                    value={row.evidence_received}
                    onChange={(ev) =>
                      onRowChange(e.id, { evidence_received: ev.target.value })
                    }
                    placeholder="Evidence received…"
                    disabled={disabled}
                    style={inputStyle(row.result_accepted)}
                  />
                </div>
                <div style={{ padding: '11px 10px' }}>
                  <span
                    style={{
                      fontSize: 9,
                      padding: '2px 7px',
                      background: '#FAEEDA',
                      color: '#854F0B',
                      borderRadius: 99,
                      fontWeight: 700,
                      letterSpacing: '0.04em',
                    }}
                  >
                    {(e.nc_type || 'NA').toUpperCase()}
                  </span>
                </div>
                <div
                  style={{
                    padding: '9px 10px',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: 5,
                  }}
                >
                  <button
                    type="button"
                    onClick={() =>
                      onRowChange(e.id, { result_accepted: true, status: 'closed' })
                    }
                    disabled={disabled}
                    style={resultBtn(row.result_accepted, 'accept')}
                  >
                    <FiCheck size={11} />
                    Accepted
                  </button>
                  <button
                    type="button"
                    onClick={() =>
                      onRowChange(e.id, { result_accepted: false, status: 'open' })
                    }
                    disabled={disabled}
                    style={resultBtn(!row.result_accepted, 'reject')}
                  >
                    <FiX size={11} />
                    Not Acc.
                  </button>

                  {/* 🆕 status — auto-fills from result, still editable */}
                  <select
                    value={row.status ?? (row.result_accepted ? 'closed' : 'open')}
                    onChange={(ev) =>
                      onRowChange(e.id, { status: ev.target.value as 'open' | 'closed' })
                    }
                    disabled={disabled}
                    style={{
                      width: '100%',
                      padding: '5px 6px',
                      fontSize: 10,
                      fontWeight: 700,
                      border: '1px solid #e2e8f0',
                      borderRadius: 4,
                      background: '#fff',
                      color:
                        (row.status ?? (row.result_accepted ? 'closed' : 'open')) === 'closed'
                          ? '#0F6E56'
                          : '#A32D2D',
                      cursor: 'pointer',
                      outline: 'none',
                    }}
                  >
                    <option value="open">Open</option>
                    <option value="closed">Closed</option>
                  </select>
                </div>
                <div style={{ padding: '7px 10px' }}>
                  <textarea
                    value={row.submitted_docs}
                    onChange={(ev) =>
                      onRowChange(e.id, { submitted_docs: ev.target.value })
                    }
                    placeholder="1) Document — Code: ... — Date: ..."
                    disabled={disabled}
                    style={{
                      ...inputStyle(row.result_accepted),
                      minHeight: 42,
                      resize: 'vertical',
                      lineHeight: 1.4,
                      fontFamily: 'inherit',
                      padding: '6px 9px',
                    }}
                  />
                </div>
                <div
                  style={{
                    padding: '9px 10px',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: 4,
                  }}
                >
                  <button
                    type="button"
                    onClick={() =>
                      onRowChange(e.id, { result_accepted: true })
                    }
                    disabled={disabled}
                    style={resultBtn(row.result_accepted, 'accept')}
                  >
                    <FiCheck size={11} />
                    Accepted
                  </button>
                  <button
                    type="button"
                    onClick={() =>
                      onRowChange(e.id, { result_accepted: false })
                    }
                    disabled={disabled}
                    style={resultBtn(!row.result_accepted, 'reject')}
                  >
                    <FiX size={11} />
                    Not Acc.
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div
        style={{
          marginTop: 10,
          padding: '8px 12px',
          background: '#fafbfc',
          border: '1px solid #f1f5f9',
          borderRadius: 6,
          fontSize: 10,
          color: '#64748b',
          display: 'flex',
          gap: 14,
          flexWrap: 'wrap',
          alignItems: 'center',
        }}
      >
        <strong style={{ color: '#0b1220' }}>Result legend:</strong>
        <span
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: 5,
          }}
        >
          <span
            style={{
              width: 10,
              height: 10,
              borderLeft: '3px solid #15803d',
              background: '#15803d10',
              borderRadius: 1,
            }}
          />
          Accepted → finding will be marked Closed
        </span>
        <span
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: 5,
          }}
        >
          <span
            style={{
              width: 10,
              height: 10,
              borderLeft: '3px solid #d97706',
              background: '#d9770610',
              borderRadius: 1,
            }}
          />
          Not Accepted → stays Open, verification recorded
        </span>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════════════════════════════

function emptyRow(entryId: number): ClosureRow {
  return {
    entry_id: entryId,
    evidence_received: '',
    submitted_docs: '',
    result_accepted: false,
    remarks: '',
    status: 'open',
  };
}

// Detect if the row has been explicitly set (has any content)
function isAcceptanceSet(row: ClosureRow, allRows: ClosureRow[]): boolean {
  return !!row.evidence_received || !!row.submitted_docs || !!row.remarks;
}

function inputStyle(accepted: boolean): React.CSSProperties {
  return {
    width: '100%',
    padding: '7px 9px',
    fontSize: 11,
    border: `1px solid ${accepted ? '#bbf7d0' : '#e2e8f0'}`,
    borderRadius: 5,
    background: '#fff',
    color: '#0b1220',
    boxSizing: 'border-box',
    fontFamily: 'inherit',
    outline: 'none',
  };
}

function resultBtn(
  active: boolean,
  kind: 'accept' | 'reject',
): React.CSSProperties {
  const color = kind === 'accept' ? '#15803d' : '#A32D2D';
  return {
    padding: '5px 8px',
    background: active ? color : '#fff',
    color: active ? '#fff' : '#475569',
    border: active ? 'none' : '1px solid #e2e8f0',
    borderRadius: 4,
    fontSize: 10,
    fontWeight: active ? 700 : 500,
    cursor: 'pointer',
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 4,
  };
}