'use client';

import React from 'react';
import {
  FiEdit2,
  FiTrash2,
  FiChevronDown,
  FiChevronRight,
  FiFileText,
  FiSlash,
} from 'react-icons/fi';
import EvidenceZone from './EvidenceZone';
import type { EditableEntry, FindingViewProps } from './findings.types';

// ═══════════════════════════════════════════════════════════════════════
// FindingRow — v3 row-based layout (table-like)
// ═══════════════════════════════════════════════════════════════════════

const GRID = '32px 1fr 200px 100px 100px 95px 76px';

export default function FindingRow({
  entry,
  index,
  expanded,
  source,
  ncId,
  onToggleExpand,
  onChange,
  onFileChanged,
  onDelete,
}: FindingViewProps) {
  const borderLeftColor =
    entry.status === 'closed'
      ? '#16a34a'
      : entry.status === 'pending'
        ? '#d97706'
        : '#dc2626';

  return (
    <div
      style={{
        borderBottom: '1px solid #f1f5f9',
        borderLeft: `3px solid ${borderLeftColor}`,
        background: expanded ? '#fafbfc' : '#fff',
        transition: 'background 0.15s',
      }}
    >
      {/* ── Compact summary row ── */}
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: GRID,
          gap: 12,
          padding: '12px 14px',
          alignItems: 'center',
        }}
      >
        <span
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            width: 24,
            height: 24,
            background: '#f1f5f9',
            borderRadius: 6,
            fontSize: 11,
            fontWeight: 600,
            fontFamily: "'JetBrains Mono', monospace",
            color: '#475569',
          }}
        >
          {String(index).padStart(2, '0')}
        </span>

        <div style={{ minWidth: 0 }}>
          <div
            style={{
              fontSize: 12,
              color: '#0b1220',
              lineHeight: 1.5,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              display: '-webkit-box',
              WebkitLineClamp: 2,
              WebkitBoxOrient: 'vertical',
            }}
          >
            {entry.ncr_statement || (
              <span style={{ color: '#94a3b8', fontStyle: 'italic' }}>
                No statement yet — click expand to add
              </span>
            )}
          </div>
          <button
            onClick={onToggleExpand}
            style={{
              marginTop: 4,
              padding: 0,
              background: 'none',
              border: 'none',
              color: '#0f766e',
              fontSize: 10,
              fontWeight: 600,
              cursor: 'pointer',
              display: 'inline-flex',
              alignItems: 'center',
              gap: 3,
            }}
          >
            {expanded ? (
              <>
                <FiChevronDown size={11} /> Collapse
              </>
            ) : (
              <>
                <FiChevronRight size={11} /> Expand to edit
              </>
            )}
          </button>
        </div>

        <div
          style={{
            fontSize: 12,
            color: '#1f2937',
            fontFamily: "'JetBrains Mono', monospace",
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}
          title={entry.criteria_clause}
        >
          {entry.criteria_clause || (
            <span style={{ color: '#94a3b8' }}>—</span>
          )}
        </div>

        <NcTypePill type={entry.nc_type} />
        <StatusPill status={entry.status} />

        <EvidencePill hasFile={!!entry.document_path} />

        <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
          {entry._dirty && (
            <span
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                padding: '0 6px',
                background: '#fef3c7',
                color: '#92400e',
                borderRadius: 99,
                fontSize: 9,
                fontWeight: 700,
                letterSpacing: '0.04em',
              }}
              title="Unsaved changes"
            >
              ●
            </span>
          )}
          <button
            onClick={onDelete}
            style={iconBtnStyle('#dc2626')}
            title="Delete this finding"
            aria-label="Delete finding"
          >
            <FiTrash2 size={13} />
          </button>
        </div>
      </div>

      {/* ── Expanded inline edit panel ── */}
      {expanded && (
        <EditPanel
          entry={entry}
          source={source}
          ncId={ncId}
          onChange={onChange}
          onFileChanged={onFileChanged}
        />
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// Edit panel (shown when row is expanded)
// ═══════════════════════════════════════════════════════════════════════

function EditPanel({
  entry,
  source,
  ncId,
  onChange,
  onFileChanged,
}: {
  entry: EditableEntry;
   source: 'QRS' | 'TQS' | 'NEW';

  ncId: number;
  onChange: (patch: Partial<EditableEntry>) => void;
  onFileChanged: (newPath: string | null) => void;
}) {
  return (
    <div
      style={{
        padding: '4px 14px 18px 14px',
        background: '#fafbfc',
      }}
    >
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: '2fr 1fr 1fr 110px 110px',
          gap: 10,
          marginBottom: 14,
        }}
      >
        <Field label="NCR statement">
          <textarea
            value={entry.ncr_statement}
            onChange={(e) => onChange({ ncr_statement: e.target.value })}
            placeholder="Describe the non-conformity finding…"
            style={{ ...inputStyle(), minHeight: 88, resize: 'vertical' }}
          />
        </Field>
        <Field label="Criteria clause">
          <input
            value={entry.criteria_clause}
            onChange={(e) => onChange({ criteria_clause: e.target.value })}
            placeholder="e.g. Clause 7.1.5"
            style={inputStyle()}
          />
        </Field>
        <Field label="Corrective action">
          <textarea
            value={entry.corrective_action}
            onChange={(e) => onChange({ corrective_action: e.target.value })}
            placeholder="Proposed corrective action…"
            style={{ ...inputStyle(), minHeight: 88, resize: 'vertical' }}
          />
        </Field>
        <Field label="NC type">
          <select
            value={entry.nc_type}
            onChange={(e) => onChange({ nc_type: e.target.value })}
            style={inputStyle()}
          >
            <option value="">— select —</option>
            <option value="Major">Major</option>
            <option value="Minor">Minor</option>
            <option value="Observation">Observation</option>
          </select>
        </Field>
        <Field label="Status">
          <select
            value={entry.status}
            onChange={(e) =>
              onChange({
                status: e.target.value as 'open' | 'closed' | 'pending',
              })
            }
            style={inputStyle()}
          >
            <option value="open">Open</option>
            <option value="pending">Pending</option>
            <option value="closed">Closed</option>
          </select>
        </Field>
      </div>

      <div style={{ borderTop: '1px solid #e2e8f0', paddingTop: 12 }}>
        <div
          style={{
            fontSize: 9,
            fontWeight: 700,
            color: '#94a3b8',
            textTransform: 'uppercase',
            letterSpacing: '0.08em',
            marginBottom: 6,
          }}
        >
          Evidence file
        </div>
        <div style={{ marginLeft: -16, marginRight: -16 }}>
          <EvidenceZone
            source={source}
            ncId={ncId}
            entryId={entry.id}
            documentPath={entry.document_path}
            onChange={onFileChanged}
          />
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// Sub-components
// ═══════════════════════════════════════════════════════════════════════

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <div
        style={{
          fontSize: 9,
          fontWeight: 700,
          color: '#94a3b8',
          textTransform: 'uppercase',
          letterSpacing: '0.08em',
          marginBottom: 4,
        }}
      >
        {label}
      </div>
      {children}
    </div>
  );
}

function NcTypePill({ type }: { type?: string }) {
  const t = (type || '').toLowerCase();
  let label = type || '—';
  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 = 'Observation';
    color = '#0C447C';
    bg = '#E6F1FB';
  }
  return (
    <span
      style={{
        fontSize: 10,
        padding: '3px 8px',
        background: bg,
        color,
        borderRadius: 99,
        fontWeight: 700,
        letterSpacing: '0.04em',
        width: 'fit-content',
        whiteSpace: 'nowrap',
      }}
    >
      {label}
    </span>
  );
}

function StatusPill({ status }: { status: string }) {
  const s = (status || '').toLowerCase();
  let label = status || '—';
  let color = '#94a3b8';
  let bg = '#f1f5f9';
  if (s === 'open') {
    label = 'Open';
    color = '#A32D2D';
    bg = '#FCEBEB';
  } else if (s === 'closed') {
    label = 'Closed';
    color = '#0F6E56';
    bg = '#E1F5EE';
  } else if (s === 'pending') {
    label = 'Pending';
    color = '#854F0B';
    bg = '#FAEEDA';
  }
  return (
    <span
      style={{
        fontSize: 10,
        padding: '3px 8px',
        background: bg,
        color,
        borderRadius: 99,
        fontWeight: 700,
        letterSpacing: '0.04em',
        width: 'fit-content',
      }}
    >
      {label}
    </span>
  );
}

function EvidencePill({ hasFile }: { hasFile: boolean }) {
  if (hasFile) {
    return (
      <span
        style={{
          fontSize: 10,
          padding: '3px 7px',
          background: '#dcfce7',
          color: '#15803d',
          borderRadius: 5,
          fontWeight: 600,
          display: 'inline-flex',
          alignItems: 'center',
          gap: 4,
          width: 'fit-content',
        }}
      >
        <FiFileText size={11} /> 1 file
      </span>
    );
  }
  return (
    <span
      style={{
        fontSize: 10,
        color: '#94a3b8',
        display: 'inline-flex',
        alignItems: 'center',
        gap: 4,
      }}
    >
      <FiSlash size={11} /> No file
    </span>
  );
}

function iconBtnStyle(color = '#475569'): React.CSSProperties {
  return {
    background: 'none',
    border: '1px solid #e2e8f0',
    borderRadius: 5,
    padding: '5px 7px',
    cursor: 'pointer',
    color,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    transition: 'all 0.12s',
  };
}

function inputStyle(): React.CSSProperties {
  return {
    width: '100%',
    background: '#fff',
    border: '1px solid #e2e8f0',
    borderRadius: 5,
    padding: '7px 10px',
    fontSize: 12,
    fontWeight: 500,
    color: '#0b1220',
    outline: 'none',
    fontFamily: 'inherit',
    lineHeight: 1.5,
    boxSizing: 'border-box',
  };
}
