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-700 bg-emerald-50 dark:bg-emerald-900/30 dark:text-emerald-400';
    case 'FALHA':
    case 'NÃO CONFORME':
      return 'text-rose-700 bg-rose-50 dark:bg-rose-900/30 dark:text-rose-400';
    default:
      return 'text-slate-600 bg-slate-50 dark:bg-slate-800/50 dark:text-slate-400';
  }
};

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-[8mm_12mm] p-4 sm:p-6 md:p-8 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 h-auto">
      
      {/* Cabeçalho (Header) */}
      <header className="border-b border-slate-100 dark:border-slate-800 pb-2.5">
        <div className="flex flex-col sm:flex-row justify-between items-start gap-2 sm:gap-0 w-full">
          <div className="flex-shrink-0">
            {/* Logo SteelCheck com visual geométrico */}
            <div className="flex items-center gap-1.5">
              <span className="bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 font-extrabold px-2 py-0.5 rounded text-[11px] tracking-tight">STEEL CHECK</span>
              <span className="text-[8px] uppercase font-bold tracking-widest text-slate-400 dark:text-slate-500 border border-slate-200 dark:border-slate-700 px-1 py-0.5 rounded">IA Quality Report</span>
            </div>
            <h2 className="text-[11px] font-semibold text-slate-500 dark:text-slate-400 mt-1.5">Relatório Técnico de Qualidade</h2>
            <p className="text-[9px] text-slate-400 dark:text-slate-500">Análise de conformidade normativa assistida por inteligência artificial</p>
          </div>

          <div className="flex gap-3 w-full sm:w-auto justify-end flex-grow">
            {/* Status Global de Conformidade */}
            <div className="text-right flex flex-col items-end">
              <span className="text-[8px] uppercase font-bold tracking-wider text-slate-400 dark:text-slate-500">Status Geral</span>
              <div className={`flex items-center gap-1 mt-0.5 px-2.5 py-1 rounded-full ${statusClass(compliance.status)}`}>
                <span className={`w-1.5 h-1.5 rounded-full animate-pulse ${compliance.status === 'CONFORME' ? 'bg-emerald-500' : 'bg-red-500'}`}></span>
                <span className="text-[10px] 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-[8px] uppercase font-bold tracking-wider text-slate-400 dark:text-slate-500">Confiança</span>
              <div className="mt-0.5 bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-300 px-2.5 py-1 rounded-full text-[10px] font-bold">
                {confidence}% <span className="text-[8px] text-slate-400 dark:text-slate-500 font-normal">IA-Score</span>
              </div>
              {report.analysisSource && (
                <span className="text-[7px] text-slate-400 mt-1 uppercase tracking-widest" title="Origem dos parâmetros de conformidade usados pela IA">
                  {report.analysisSource === 'Banco Local' ? '🏦 Banco Local' : '🧠 Rede Neural'}
                </span>
              )}
            </div>
          </div>
        </div>
      </header>

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

        {/* Banner de Não Conformidade se aplicável */}
        {compliance.status === 'NÃO CONFORME' && compliance.nonComplianceReason && (
          <div className="mb-4 bg-rose-50 dark:bg-rose-950/20 border border-rose-200 dark:border-rose-800/50 rounded-lg p-3 text-[10px] text-rose-800 dark:text-rose-300 leading-normal flex gap-2.5 items-start">
            <svg className="w-4 h-4 shrink-0 text-rose-600 dark:text-rose-400 mt-0.5" fill="none" viewBox="0 0 24 24" strokeWidth="2.5" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <div>
              <h4 className="font-black uppercase tracking-wider text-[9px] text-rose-900 dark:text-rose-200 mb-0.5">Motivo da Não Conformidade Normativa</h4>
              <p className="font-medium">{compliance.nonComplianceReason}</p>
            </div>
          </div>
        )}

        {/* Seções 2 e 3: Propriedades (Lado a Lado no Desktop) */}
        <section className="grid grid-cols-1 md:grid-cols-12 gap-2 mb-3 flex-grow">
          
          {/* 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-1.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/60 rounded-xl overflow-hidden bg-white dark:bg-slate-900 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.05)] flex flex-col justify-between">
              <div className="overflow-x-auto min-w-0 w-full scrollbar-none">
                <table className="w-full min-w-[320px] sm:min-w-0 table-fixed text-left border-collapse text-xs">
                  <thead>
                    <tr className="bg-slate-50/80 dark:bg-slate-800/40 border-b border-slate-50 dark:border-slate-800/60 text-[9px] text-slate-500 dark:text-slate-400 font-bold uppercase tracking-wider">
                      <th className="py-0.5 px-1 w-[35%]">Propriedade</th>
                      <th className="py-0.5 px-1 w-[25%]">Certificado</th>
                      <th className="py-0.5 px-1 w-[15%] text-center">% Rel.</th>
                      <th className="py-0.5 px-1 w-[25%] text-right">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-0.5 px-1.5">
                            <span className="font-semibold text-[10px] block text-slate-700 dark:text-slate-300 leading-tight" title={item.property}>{item.property}</span>
                          </td>
                          <td className="py-0.5 px-1 font-mono font-bold text-[10px] text-slate-900 dark:text-slate-100 break-words leading-tight" title={item.certificate}>{item.certificate}</td>
                          <td className="py-0.5 px-1 text-center leading-tight">
                            {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-0.5 px-1 text-right">
                            <span className={`inline-flex items-center gap-1 text-[8px] font-bold px-1 py-0.5 rounded-md ${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-1.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/60 rounded-xl overflow-hidden bg-white dark:bg-slate-900 shadow-[0_2px_10px_-3px_rgba(6,81,237,0.05)] flex flex-col justify-start">
              <div className="overflow-x-auto min-w-0 w-full scrollbar-none">
                <table className="w-full min-w-[320px] sm:min-w-0 table-fixed text-left border-collapse text-xs">
                  <thead>
                    <tr className="bg-slate-50/80 dark:bg-slate-800/40 border-b border-slate-50 dark:border-slate-800/60 text-[9px] text-slate-500 dark:text-slate-400 font-bold uppercase tracking-wider">
                      <th className="py-0.5 px-1.5 w-[15%]">Elem.</th>
                      <th className="py-0.5 px-1 w-[40%]">Norma de Referência</th>
                      <th className="py-0.5 px-1 w-[25%]">Valor Certificado</th>
                      <th className="py-0.5 px-1.5 w-[20%] text-right">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-0.5 px-1.5 font-sans font-semibold text-[10px] text-slate-700 dark:text-slate-300 leading-tight" title={item.element}>{item.element}</td>
                        <td className="py-0.5 px-1 text-slate-500 dark:text-slate-400 text-[9px] leading-tight break-words" title={item.norm}>{item.norm}</td>
                        <td className="py-0.5 px-1 font-bold text-[10px] text-slate-900 dark:text-slate-100 break-words leading-tight" title={item.certificate}>{item.certificate}</td>
                        <td className="py-0.5 px-1.5 text-right">
                          <span className={`inline-flex items-center text-[8px] font-bold px-1 py-0.5 rounded-md ${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>
  );
};
