'use client';

import React, { useMemo } from 'react';
import type { EditableEntry } from './findings.types';
import { isDraft } from './findings.types';

// ═══════════════════════════════════════════════════════════════════════
// 🆕 PHASE 2A — Closure Finding Picker
// ═══════════════════════════════════════════════════════════════════════
// Simple list: checkbox + number + type pill + finding statement.
// Auditor picks which findings to include in this closure batch.
// Findings that are already closed don't appear here.
//
// FIX: replaced <label> + hidden <input type="checkbox"> pattern with
// a plain <div> + onClick. Avoids browser-specific label-input
// click-delegation issues when pointer-events: none is involved.
// ═══════════════════════════════════════════════════════════════════════

interface Props {
  entries: EditableEntry[];
  selectedIds: Set<number>;
  onToggle: (id: number) => void;
  onSelectAll: () => void;
}

export default function ClosureFindingPicker({
  entries,
  selectedIds,
  onToggle,
  onSelectAll,
}: Props) {
  // Only show real (non-draft) findings that are NOT already closed
  const openEntries = useMemo(
    () =>
      entries.filter(
        (e) => !isDraft(e) && e.status !== 'closed',
      ),
    [entries],
  );

  const allSelected =
    openEntries.length > 0 &&
    openEntries.every((e) => selectedIds.has(e.id));

  if (openEntries.length === 0) {
    return (
      <div
        style={{
          padding: '24px 18px',
          textAlign: 'center',
          background: '#fafbfc',
          border: '1px dashed #e2e8f0',
          borderRadius: 8,
          fontSize: 12,
          color: '#94a3b8',
        }}
      >
        No open findings on this NC. All findings have already been closed.
      </div>
    );
  }

  return (
    <div>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 12,
        }}
      >
        <div>
          <div
            style={{
              fontSize: 12,
              fontWeight: 700,
              color: '#0b1220',
              marginBottom: 3,
            }}
          >
            Which findings are you closing?
          </div>
          <div style={{ fontSize: 11, color: '#64748b' }}>
            Pick the findings this closure covers. Unticked ones stay open for later.
          </div>
        </div>
        <button
          type="button"
          onClick={onSelectAll}
          style={{
            fontSize: 10,
            padding: '5px 11px',
            background: '#fff',
            border: '1px solid #185FA5',
            color: '#185FA5',
            borderRadius: 5,
            fontWeight: 600,
            cursor: 'pointer',
          }}
        >
          {allSelected ? 'Deselect all' : 'Select all'}
        </button>
      </div>

      <div
        style={{
          border: '1px solid #e2e8f0',
          borderRadius: 8,
          overflow: 'hidden',
        }}
      >
        {openEntries.map((e, idx) => {
          const checked = selectedIds.has(e.id);
          const isLast = idx === openEntries.length - 1;
          // Find the original index in the full list (1-based, only counting real entries)
          const realIndex =
            entries.filter((x) => !isDraft(x)).indexOf(e) + 1;

          return (
            <div
              key={e.id}
              role="checkbox"
              aria-checked={checked}
              tabIndex={0}
              onClick={() => onToggle(e.id)}
              onKeyDown={(ev) => {
                if (ev.key === ' ' || ev.key === 'Enter') {
                  ev.preventDefault();
                  onToggle(e.id);
                }
              }}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 10,
                padding: '10px 12px',
                borderBottom: isLast ? 'none' : '1px solid #f1f5f9',
                cursor: 'pointer',
                background: checked ? '#f8faff' : 'transparent',
                transition: 'background 0.12s',
                userSelect: 'none',
                outline: 'none',
              }}
            >
              <span
                style={{
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  width: 16,
                  height: 16,
                  background: checked ? '#185FA5' : '#fff',
                  border: `1.5px solid ${checked ? '#185FA5' : '#cbd5e1'}`,
                  borderRadius: 4,
                  flexShrink: 0,
                  transition: 'all 0.12s',
                }}
              >
                {checked && (
                  <svg
                    width="10"
                    height="10"
                    viewBox="0 0 12 12"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M2 6L5 9L10 3"
                      stroke="white"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                )}
              </span>
              <span
                style={{
                  fontFamily: "'JetBrains Mono', monospace",
                  fontSize: 11,
                  color: checked ? '#185FA5' : '#475569',
                  fontWeight: 700,
                  minWidth: 22,
                }}
              >
                {String(realIndex).padStart(2, '0')}
              </span>
              <NcTypePill type={e.nc_type} />
              <span
                style={{
                  fontSize: 11,
                  color: checked ? '#0b1220' : '#1f2937',
                  fontWeight: checked ? 600 : 500,
                  flex: 1,
                  minWidth: 0,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}
                title={e.ncr_statement}
              >
                {e.ncr_statement || '(no statement)'}
              </span>
            </div>
          );
        })}
      </div>

      {selectedIds.size > 0 && (
        <div
          style={{
            marginTop: 10,
            padding: '8px 11px',
            background: '#f0fdf4',
            border: '1px solid #bbf7d0',
            borderRadius: 6,
            fontSize: 11,
            color: '#15803d',
            display: 'flex',
            alignItems: 'center',
            gap: 6,
          }}
        >
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none">
            <path
              d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
              stroke="#15803d"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          <span>
            <strong>{selectedIds.size}</strong>{' '}
            finding{selectedIds.size > 1 ? 's' : ''} selected. Verification details
            for these rows appear below.
          </span>
        </div>
      )}
    </div>
  );
}

function NcTypePill({ type }: { type?: string }) {
  const t = (type || '').toLowerCase();
  let label = 'NA';
  let color = '#94a3b8';
  let bg = '#f1f5f9';
  if (t.includes('major')) {
    label = 'MAJOR';
    color = '#A32D2D';
    bg = '#FCEBEB';
  } else if (t.includes('minor')) {
    label = 'MINOR';
    color = '#854F0B';
    bg = '#FAEEDA';
  } else if (t.includes('observ')) {
    label = 'OBSERV';
    color = '#0C447C';
    bg = '#E6F1FB';
  }
  return (
    <span
      style={{
        fontSize: 9,
        padding: '2px 6px',
        background: bg,
        color,
        borderRadius: 4,
        fontWeight: 700,
        letterSpacing: '0.04em',
        flexShrink: 0,
      }}
    >
      {label}
    </span>
  );
}