import React from 'react';
import type { ReportData, ComplianceItem } from '../types';

interface ReportDisplayProps {
  report: ReportData;
}

const statusClass = (status: 'OK' | 'FALHA' | 'CONFORME' | 'NÃO CONFORME') => {
  switch (status) {
    case 'OK':
    case 'CONFORME':
      return 'text-emerald-600 bg-emerald-50 dark:bg-emerald-900/30 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-800';
    case 'FALHA':
    case 'NÃO CONFORME':
      return 'text-red-600 bg-red-50 dark:bg-red-900/30 dark:text-red-400 border border-red-200 dark:border-red-800';
    default:
      return 'text-slate-600 bg-slate-50 dark:bg-slate-800/50 dark:text-slate-400 border border-slate-200 dark:border-slate-700';
  }
};

const statusIcon = (status: 'OK' | 'FALHA') => {
  return status === 'OK' ? (
    <svg className="w-3 h-3" fill="none" stroke="currentColor" strokeWidth="3" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="m4.5 12.75 6 6 9-13.5"/></svg>
  ) : (
    <svg className="w-3 h-3" fill="none" stroke="currentColor" strokeWidth="3" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
  );
};

export const ReportDisplay: React.FC<ReportDisplayProps> = ({ report }) => {
  const identification = report?.identification || {};
  const compliance = report?.compliance || { status: 'NÃO CONFORME', mechanical: [], chemical: [], otherTests: [] };
  const equivalents = report?.equivalents || [];
  const confidence = report?.confidence || 0;

  return (
    <div className="animate-fade-in w-full max-w-[210mm] mx-auto bg-white dark:bg-slate-900 shadow-xl print:shadow-none print:m-0 print:p-[10mm_15mm] p-[10mm] sm:p-[16mm_20mm] relative flex flex-col justify-between text-slate-800 dark:text-slate-200 border border-slate-200 dark:border-slate-800 rounded-lg print:rounded-none min-h-[297mm]">
      
      {/* Cabeçalho (Header) */}
      <header className="border-b border-slate-100 dark:border-slate-800 pb-5">
        <div className="flex flex-col sm:flex-row justify-between items-start gap-4 sm:gap-0">
          <div>
            {/* Logo SteelCheck com visual geométrico */}
            <div className="flex items-center gap-2">
              <span className="bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 font-extrabold px-2.5 py-1 rounded text-base tracking-tight">STEEL CHECK</span>
              <span className="text-[10px] uppercase font-bold tracking-widest text-slate-400 dark:text-slate-500 border border-slate-200 dark:border-slate-700 px-1.5 py-0.5 rounded">IA Quality Report</span>
            </div>
            <h2 className="text-sm font-semibold text-slate-500 dark:text-slate-400 mt-2.5">Relatório Técnico de Qualidade</h2>
            <p className="text-xs text-slate-400 dark:text-slate-500">Análise de conformidade normativa assistida por inteligência artificial</p>
          </div>

          <div className="flex gap-4 w-full sm:w-auto justify-between sm:justify-end">
            {/* Status Global de Conformidade */}
            <div className="text-right flex flex-col items-end">
              <span className="text-[9px] uppercase font-bold tracking-wider text-slate-400 dark:text-slate-500">Status Geral</span>
              <div className={`flex items-center gap-1.5 mt-1 px-3.5 py-1.5 rounded-full ${statusClass(compliance.status)}`}>
                <span className={`w-2 h-2 rounded-full animate-pulse ${compliance.status === 'CONFORME' ? 'bg-emerald-500' : 'bg-red-500'}`}></span>
                <span className="text-xs font-black tracking-wider">{compliance.status}</span>
              </div>
            </div>

            {/* Score de Confiança da IA */}
            <div className="text-right flex flex-col items-end">
              <span className="text-[9px] uppercase font-bold tracking-wider text-slate-400 dark:text-slate-500">Confiança da Análise</span>
              <div className="mt-1 bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-300 px-3 py-1.5 rounded-full text-xs font-bold">
                {confidence}% <span className="text-[10px] text-slate-400 dark:text-slate-500 font-normal">IA-Score</span>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* Conteúdo Principal */}
      <main className="flex-grow my-4 flex flex-col justify-start">
        
        {/* Seção 1: Dados de Identificação */}
        <section className="mb-5">
          <h3 className="text-[10px] uppercase font-bold tracking-wider text-slate-400 dark:text-slate-500 mb-2.5 flex items-center gap-1.5">
            <span className="w-1.5 h-1.5 bg-slate-400 dark:bg-slate-500 rounded-full"></span>
            1. Identificação do Produto e Lote
          </h3>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 bg-slate-50/70 dark:bg-slate-800/30 rounded-xl p-3.5 border border-slate-100 dark:border-slate-800">
            <div>
              <span className="block text-[9px] text-slate-400 dark:text-slate-500 uppercase font-medium">Produto</span>
              <span className="block text-xs font-semibold text-slate-800 dark:text-slate-200 leading-tight">{identification.product || '-'}</span>
            </div>
            <div>
              <span className="block text-[9px] text-slate-400 dark:text-slate-500 uppercase font-medium">Norma de Referência</span>
              <span className="block text-xs font-bold text-slate-900 dark:text-white leading-tight">{identification.standards || '-'}</span>
            </div>
            <div>
              <span className="block text-[9px] text-slate-400 dark:text-slate-500 uppercase font-medium">Fabricante</span>
              <span className="block text-xs font-semibold text-slate-800 dark:text-slate-200 leading-tight">{identification.manufacturer || '-'}</span>
            </div>
            <div>
              <span className="block text-[9px] text-slate-400 dark:text-slate-500 uppercase font-medium">Nº do Certificado</span>
              <span className="block text-xs font-mono font-bold text-slate-800 dark:text-slate-200 leading-tight">#{identification.certificateNumber || '-'}</span>
            </div>
            <div className="pt-2 border-t border-slate-100 dark:border-slate-800">
              <span className="block text-[9px] text-slate-400 dark:text-slate-500 uppercase font-medium">Data de Emissão</span>
              <span className="block text-xs font-semibold text-slate-800 dark:text-slate-200 leading-tight">{identification.certificateDate || '-'}</span>
            </div>
            <div className="pt-2 border-t border-slate-100 dark:border-slate-800">
              <span className="block text-[9px] text-slate-400 dark:text-slate-500 uppercase font-medium">Lote analisado</span>
              <span className="block text-xs font-mono font-semibold text-slate-800 dark:text-slate-200 leading-tight">{identification.batches || '-'}</span>
            </div>
            <div className="pt-2 border-t border-slate-100 dark:border-slate-800">
              <span className="block text-[9px] text-slate-400 dark:text-slate-500 uppercase font-medium">Corrida (Heat)</span>
              <span className="block text-xs font-mono font-semibold text-slate-800 dark:text-slate-200 leading-tight">{identification.heats || '-'}</span>
            </div>
            <div className="pt-2 border-t border-slate-100 dark:border-slate-800">
              <span className="block text-[9px] text-slate-400 dark:text-slate-500 uppercase font-medium">Massa Total</span>
              <span className="block text-xs font-semibold text-slate-800 dark:text-slate-200 leading-tight">{identification.quantity || '-'}</span>
            </div>
          </div>
        </section>

        {/* Seção 2: Verificação de Conformidade */}
        <section className="grid grid-cols-1 md:grid-cols-12 gap-5 mb-5">
          
          {/* Propriedades Mecânicas (Esquerda) */}
          <div className="col-span-1 md:col-span-6 flex flex-col">
            <h3 className="text-[10px] uppercase font-bold tracking-wider text-slate-400 dark:text-slate-500 mb-2.5 flex items-center gap-1.5">
              <span className="w-1.5 h-1.5 bg-slate-400 dark:bg-slate-500 rounded-full"></span>
              2. Propriedades Mecânicas
            </h3>
            <div className="flex-grow border border-slate-100 dark:border-slate-800 rounded-xl overflow-hidden bg-white dark:bg-slate-900 shadow-sm flex flex-col justify-between">
              <div className="overflow-hidden">
                <table className="w-full table-fixed text-left border-collapse text-xs">
                  <thead>
                    <tr className="bg-slate-50 dark:bg-slate-800/50 border-b border-slate-100 dark:border-slate-800 text-[9px] text-slate-400 dark:text-slate-500 font-bold uppercase tracking-wider">
                      <th className="py-2.5 px-2 w-[35%] truncate">Propriedade</th>
                      <th className="py-2.5 px-1 w-[25%] truncate">Certif.</th>
                      <th className="py-2.5 px-1 w-[15%] text-center truncate">% Rel.</th>
                      <th className="py-2.5 px-1 w-[25%] text-right truncate">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-50 dark:divide-slate-800/50">
                    {compliance.mechanical.map((item, i) => {
                      const isPositive = item.differencePercentage?.startsWith('+');
                      const diffColor = isPositive ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400';
                      return (
                        <tr key={i}>
                          <td className="py-2.5 px-2 truncate">
                            <span className="font-semibold block text-slate-800 dark:text-slate-200" title={item.property}>{item.property}</span>
                          </td>
                          <td className="py-2.5 px-1 font-mono font-bold text-slate-700 dark:text-slate-300 truncate" title={item.certificate}>{item.certificate}</td>
                          <td className="py-2.5 px-1 text-center truncate">
                            {item.differencePercentage ? (
                              <span className={`text-[9px] font-bold ${diffColor}`}>{item.differencePercentage}</span>
                            ) : <span className="text-slate-300 dark:text-slate-600">-</span>}
                          </td>
                          <td className="py-2.5 px-1 text-right">
                            <span className={`inline-flex items-center gap-1 text-[9px] font-bold px-1.5 py-0.5 rounded ${statusClass(item.status)}`}>
                              {statusIcon(item.status)} {item.status}
                            </span>
                          </td>
                        </tr>
                      );
                    })}
                    {compliance.mechanical.length === 0 && (
                      <tr>
                        <td colSpan={4} className="py-4 text-center text-xs text-slate-400">Nenhum dado mecânico identificado</td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
              <div className="p-3 bg-slate-50/50 dark:bg-slate-800/20 border-t border-slate-50 dark:border-slate-800 text-[10px] text-slate-400 dark:text-slate-500">
                * Limites de conformidade validados conforme parâmetros da norma <span className="font-semibold text-slate-600 dark:text-slate-400">{identification.standards || '-'}</span>.
              </div>
            </div>
          </div>

          {/* Composição Química (Direita) */}
          <div className="col-span-1 md:col-span-6 flex flex-col">
            <h3 className="text-[10px] uppercase font-bold tracking-wider text-slate-400 dark:text-slate-500 mb-2.5 flex items-center gap-1.5">
              <span className="w-1.5 h-1.5 bg-slate-400 dark:bg-slate-500 rounded-full"></span>
              3. Composição Química (%)
            </h3>
            <div className="flex-grow border border-slate-100 dark:border-slate-800 rounded-xl overflow-hidden bg-white dark:bg-slate-900 shadow-sm flex flex-col justify-start">
              <div className="overflow-hidden">
                <table className="w-full table-fixed text-left border-collapse text-xs">
                  <thead>
                    <tr className="bg-slate-50 dark:bg-slate-800/50 border-b border-slate-100 dark:border-slate-800 text-[9px] text-slate-400 dark:text-slate-500 font-bold uppercase tracking-wider">
                      <th className="py-2 px-2 w-[15%] truncate">Elem.</th>
                      <th className="py-2 px-1 w-[40%] truncate">Norma Referência</th>
                      <th className="py-2 px-1 w-[25%] truncate">Certificado</th>
                      <th className="py-2 px-1 w-[20%] text-right truncate">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-50 dark:divide-slate-800/50 font-mono">
                    {compliance.chemical.map((item, i) => (
                      <tr key={i}>
                        <td className="py-2 px-2 font-sans font-semibold text-slate-800 dark:text-slate-200 truncate" title={item.element}>{item.element}</td>
                        <td className="py-2 px-1 text-slate-400 dark:text-slate-500 text-[9px] leading-tight truncate" title={item.norm}>{item.norm}</td>
                        <td className="py-2 px-1 font-bold text-slate-700 dark:text-slate-300 truncate" title={item.certificate}>{item.certificate}</td>
                        <td className="py-2 px-1 text-right">
                          <span className={`inline-flex items-center text-[9px] font-bold px-1.5 py-0.5 rounded ${statusClass(item.status)}`}>
                            {item.status}
                          </span>
                        </td>
                      </tr>
                    ))}
                    {compliance.chemical.length === 0 && (
                      <tr>
                        <td colSpan={4} className="py-4 text-center text-xs text-slate-400">Nenhum dado químico identificado</td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </section>

        {/* Seção 3: Equivalências Internacionais */}
        <section className="mb-5">
          <h3 className="text-[10px] uppercase font-bold tracking-wider text-slate-400 dark:text-slate-500 mb-2.5 flex items-center gap-1.5">
            <span className="w-1.5 h-1.5 bg-slate-400 dark:bg-slate-500 rounded-full"></span>
            4. Matriz de Equivalências Internacionais
          </h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-center">
            {equivalents.length > 0 ? (
              equivalents.map((item, i) => (
                <div key={i} className="bg-slate-50 dark:bg-slate-800/30 border border-slate-100 dark:border-slate-800 rounded-lg p-2.5">
                  <span className="block text-[8px] font-bold tracking-wider text-slate-400 dark:text-slate-500 uppercase">{item.system}</span>
                  <span className="block text-xs font-black text-slate-700 dark:text-slate-300 mt-1">{item.norm}</span>
                </div>
              ))
            ) : (
              <div className="col-span-4 py-2 text-xs text-slate-400 text-left">Nenhuma equivalência normativa identificada no documento.</div>
            )}
          </div>
        </section>

        {/* Nota de Inteligência Artificial */}
        <section className="bg-indigo-50/40 dark:bg-indigo-900/10 border border-indigo-100/50 dark:border-indigo-800/30 rounded-xl p-3 flex gap-3 items-center">
          <div className="w-8 h-8 rounded-lg bg-indigo-50 dark:bg-indigo-900/30 flex items-center justify-center text-indigo-600 dark:text-indigo-400 shrink-0">
            <svg className="w-4.5 h-4.5" fill="none" viewBox="0 0 24 24" strokeWidth="2.5" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" d="M9.813 15.904 9 21l-.813-5.096L3 15l5.096-.813L9 9l.813 5.096L15 15l-5.096.813ZM19.071 4.929l-.707 1.9.707 1.9-1.9-.707-1.9.707.707-1.9-.707-1.9 1.9.707 1.9-.707ZM17 11l-.354.954.954.354-.954.354-.354.954-.354-.954-.954-.354.954-.354.354-.954Z" />
            </svg>
          </div>
          <div>
            <h4 className="text-[10px] font-bold text-indigo-950 dark:text-indigo-200 uppercase tracking-wide">Laudo Assistido por Inteligência Artificial</h4>
            <p className="text-[10px] text-slate-500 dark:text-slate-400 leading-normal mt-0.5">
              Os dados certificados deste lote foram analisados em tempo real contra as bibliotecas normativas globais de siderurgia. O status global é classificado como <span className="font-semibold text-slate-700 dark:text-slate-300">{compliance.status}</span>.
            </p>
          </div>
        </section>

      </main>

      {/* Rodapé (Footer) */}
      <footer className="border-t border-slate-100 dark:border-slate-800 pt-3 mt-4 text-[10px] text-slate-400 dark:text-slate-500 flex justify-between items-center">
        <div className="flex items-center gap-4">
          <span><strong>ID Relatório:</strong> ST-{identification.certificateNumber || 'N/A'}/{new Date().getFullYear()}</span>
          <span className="hidden sm:inline">•</span>
          <span className="hidden sm:inline">SteelCheck Systems</span>
        </div>
        
        {/* QR Code Placeholder para visual de Autenticidade */}
        <div className="flex items-center gap-2">
          <span className="text-right text-[9px] text-slate-400 dark:text-slate-500 leading-tight hidden sm:block">Para validar o certificado<br/><span className="font-bold text-slate-500 dark:text-slate-400">Acesse via QR Code</span></span>
          <svg className="w-7 h-7 text-slate-800 dark:text-slate-200" viewBox="0 0 100 100" fill="currentColor">
            <rect x="0" y="0" width="30" height="30" />
            <rect x="10" y="10" width="10" height="10" fill="white" />
            <rect x="70" y="0" width="30" height="30" />
            <rect x="80" y="10" width="10" height="10" fill="white" />
            <rect x="0" y="70" width="30" height="30" />
            <rect x="10" y="80" width="10" height="10" fill="white" />
            <rect x="40" y="40" width="20" height="20" />
            <rect x="70" y="70" width="10" height="10" />
            <rect x="80" y="80" width="20" height="20" />
            <rect x="40" y="10" width="10" height="20" />
            <rect x="10" y="40" width="20" height="10" />
          </svg>
        </div>
      </footer>
    </div>
  );
};
