'use client';

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

// ═══════════════════════════════════════════════════════════════════════
// FindingCard — v4 card-grid layout
// ═══════════════════════════════════════════════════════════════════════
// Behaviour:
//  - Default: 2-column compact card showing preview + pills
//  - When expanded: grows to span 2 columns, shows full editor + evidence
// ═══════════════════════════════════════════════════════════════════════

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

  if (expanded) {
    return (
      <div
        style={{
          gridColumn: 'span 2',
          background: '#fff',
          border: '1px solid #185FA5',
          borderTop: `3px solid ${topBorderColor}`,
          borderRadius: 10,
          overflow: 'hidden',
        }}
      >
        {/* Editing header */}
        <div
          style={{
            padding: '11px 14px 10px',
            borderBottom: '1px solid #f1f5f9',
            background: '#f8faff',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <NumberBadge n={index} />
            <span
              style={{ fontSize: 12, fontWeight: 600, color: '#0b1220' }}
            >
              Editing finding
            </span>
            {entry._dirty && (
              <span
                style={{
                  fontSize: 9,
                  padding: '2px 7px',
                  background: '#fef3c7',
                  color: '#92400e',
                  borderRadius: 99,
                  fontWeight: 700,
                  letterSpacing: '0.04em',
                }}
              >
                MODIFIED
              </span>
            )}
          </div>
          <div style={{ display: 'flex', gap: 4 }}>
            <button
              onClick={onToggleExpand}
              style={pillBtnStyle('#475569')}
              title="Collapse"
            >
              <FiX size={12} /> Collapse
            </button>
            <button
              onClick={onDelete}
              style={iconBtnStyle('#dc2626')}
              title="Delete finding"
              aria-label="Delete finding"
            >
              <FiTrash2 size={13} />
            </button>
          </div>
        </div>

        {/* Editing body */}
        <div style={{ padding: 14 }}>
          <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: 80, 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: 80, 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 #f1f5f9', 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>
      </div>
    );
  }

  // ── Collapsed card ──
  return (
    <div
      style={{
        background: '#fff',
        border: '1px solid #e2e8f0',
        borderTop: `3px solid ${topBorderColor}`,
        borderRadius: 10,
        overflow: 'hidden',
        cursor: 'pointer',
        transition: 'all 0.15s',
      }}
      onClick={onToggleExpand}
      onMouseEnter={(e) => {
        (e.currentTarget as HTMLDivElement).style.borderColor = '#cbd5e1';
        (e.currentTarget as HTMLDivElement).style.boxShadow =
          '0 2px 6px rgba(11, 18, 32, 0.04)';
      }}
      onMouseLeave={(e) => {
        (e.currentTarget as HTMLDivElement).style.borderColor = '#e2e8f0';
        (e.currentTarget as HTMLDivElement).style.boxShadow = 'none';
      }}
    >
      <div style={{ padding: '12px 14px 10px', borderBottom: '1px solid #f1f5f9' }}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: 8,
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <NumberBadge n={index} />
            <span
              style={{
                fontSize: 11,
                color: '#94a3b8',
                fontFamily: "'JetBrains Mono', monospace",
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                maxWidth: 180,
              }}
              title={entry.criteria_clause}
            >
              {entry.criteria_clause || 'No clause'}
            </span>
          </div>
          <div style={{ display: 'flex', gap: 4 }}>
            {entry._dirty && (
              <span
                style={{
                  fontSize: 9,
                  padding: '2px 6px',
                  background: '#fef3c7',
                  color: '#92400e',
                  borderRadius: 99,
                  fontWeight: 700,
                  letterSpacing: '0.04em',
                  display: 'inline-flex',
                  alignItems: 'center',
                }}
              >
                MOD
              </span>
            )}
            <button
              onClick={(e) => {
                e.stopPropagation();
                onToggleExpand();
              }}
              style={iconBtnStyle('#475569')}
              title="Expand to edit"
            >
              <FiEdit2 size={12} />
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                onDelete();
              }}
              style={iconBtnStyle('#dc2626')}
              title="Delete finding"
              aria-label="Delete finding"
            >
              <FiTrash2 size={12} />
            </button>
          </div>
        </div>
        <div
          style={{
            fontSize: 12,
            color: '#0b1220',
            lineHeight: 1.5,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            display: '-webkit-box',
            WebkitLineClamp: 3,
            WebkitBoxOrient: 'vertical',
            minHeight: 54,
          }}
        >
          {entry.ncr_statement || (
            <span style={{ color: '#94a3b8', fontStyle: 'italic' }}>
              No statement yet — click to edit
            </span>
          )}
        </div>
      </div>
      <div
        style={{
          padding: '8px 14px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          background: '#fafbfc',
        }}
      >
        <div style={{ display: 'flex', gap: 5 }}>
          <NcTypePill type={entry.nc_type} />
          <StatusPill status={entry.status} />
        </div>
        <EvidenceIndicator hasFile={!!entry.document_path} />
      </div>
    </div>
  );
}

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

function NumberBadge({ n }: { n: number }) {
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        width: 24,
        height: 24,
        background: '#0b1220',
        color: '#fff',
        borderRadius: 5,
        fontSize: 10,
        fontWeight: 700,
        fontFamily: "'JetBrains Mono', monospace",
        flexShrink: 0,
      }}
    >
      {String(n).padStart(2, '0')}
    </span>
  );
}

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: 9,
        padding: '3px 7px',
        background: bg,
        color,
        borderRadius: 99,
        fontWeight: 700,
        letterSpacing: '0.04em',
      }}
    >
      {label.toUpperCase()}
    </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: 9,
        padding: '3px 7px',
        background: bg,
        color,
        borderRadius: 99,
        fontWeight: 700,
        letterSpacing: '0.04em',
      }}
    >
      {label.toUpperCase()}
    </span>
  );
}

function EvidenceIndicator({ hasFile }: { hasFile: boolean }) {
  if (hasFile) {
    return (
      <span
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 4,
          fontSize: 10,
          color: '#15803d',
          fontWeight: 600,
        }}
      >
        <FiPaperclip size={11} /> 1 file
      </span>
    );
  }
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 4,
        fontSize: 10,
        color: '#94a3b8',
      }}
    >
      <FiSlash size={11} /> No file
    </span>
  );
}

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

function pillBtnStyle(color = '#475569'): React.CSSProperties {
  return {
    background: '#fff',
    border: '1px solid #e2e8f0',
    borderRadius: 4,
    padding: '4px 9px',
    cursor: 'pointer',
    color,
    fontSize: 11,
    fontWeight: 500,
    display: 'inline-flex',
    alignItems: 'center',
    gap: 3,
  };
}

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',
  };
}