'use client';

import React from 'react';
import { useRouter } from 'next/navigation';
import { FiAlertTriangle, FiExternalLink } from 'react-icons/fi';
import type { PanelProps } from './panelTypes';

const typeColor = (t: string) =>
  /major/i.test(t)
    ? { bg: '#fee2e2', color: '#991b1b' }
    : /minor/i.test(t)
      ? { bg: '#ffedd5', color: '#9a3412' }
      : { bg: '#fef3c7', color: '#92400e' };

export default function NcsPanel({ model }: PanelProps) {
  const router = useRouter();
  return (
    <div>
      <div className="rb-banner rb-banner-info">
        <FiAlertTriangle size={16} style={{ flexShrink: 0, marginTop: 2 }} />
        <span>
          All NC / observation entries recorded against this audit. They print in the report&apos;s NC tables.
          To add one, mark a clause as NC / OFI in the Clauses tab and use <strong>Raise</strong>, or use the NC module.
        </span>
      </div>
      <div className="rb-table-wrap">
        <table className="rb-table">
          <thead>
            <tr>
              <th style={{ width: 90 }}>Type</th>
              <th style={{ width: 110 }}>Clause</th>
              <th>Statement</th>
              <th>Corrective action</th>
              <th style={{ width: 100 }}>Status</th>
              <th style={{ width: 60 }} />
            </tr>
          </thead>
          <tbody>
            {model.ncs.length === 0 && (
              <tr>
                <td colSpan={6}>
                  <div className="rb-empty">No NCs recorded for this audit.</div>
                </td>
              </tr>
            )}
            {model.ncs.map((n) => {
              const c = typeColor(n.nc_type);
              return (
                <tr key={n.entry_id}>
                  <td>
                    <span className="rb-pill" style={{ background: c.bg, color: c.color }}>{n.nc_type}</span>
                  </td>
                  <td>{n.criteria_clause || '—'}</td>
                  <td>{n.ncr_statement || '—'}</td>
                  <td>{n.corrective_action || '—'}</td>
                  <td>{n.status || '—'}</td>
                  <td>
                    <button className="rb-btn rb-btn-sm" title="Open in NC module" onClick={() => router.push(`/modules/previous-nc?nc_id=${n.nc_id}`)}>
                      <FiExternalLink size={12} />
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
