import { useState } from "react";
import type { AnalysisHistoryItem } from "../lib/types";

type Props = {
  history: AnalysisHistoryItem[];
  searchHistory?: any[];
};

export default function AnalysisHistory({ history, searchHistory }: Props) {
  const [expandedItems, setExpandedItems] = useState<string[]>([]);

  const toggleExpand = (id: string) => {
    setExpandedItems(prev => 
      prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
    );
  };

  const [activeHistoryTab, setActiveHistoryTab] = useState<"Analysis" | "Searches">("Analysis");

  if (!history.length) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[40vh] glass-card rounded-3xl border border-white/5 p-12 text-center animate-in fade-in duration-700">
        <div className="text-4xl mb-4 opacity-30">📜</div>
        <h3 className="text-xl font-bold text-white mb-2">No Analysis History</h3>
        <p className="text-slate-500 max-w-xs mx-auto">Your past agentic debates and reports will appear here for audit and review.</p>
      </div>
    );
  }

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700">
      <div className="flex items-center justify-between mb-4">
        <div className="flex bg-white/5 p-1 rounded-2xl border border-white/10">
          <button 
            onClick={() => setActiveHistoryTab("Analysis")} 
            className={`px-6 py-2 rounded-xl text-xs font-black uppercase transition-all ${activeHistoryTab === "Analysis" ? "bg-purple-600 text-white shadow-lg" : "text-slate-500"}`}
          >
            Analysis Logs
          </button>
          <button 
            onClick={() => setActiveHistoryTab("Searches")} 
            className={`px-6 py-2 rounded-xl text-xs font-black uppercase transition-all ${activeHistoryTab === "Searches" ? "bg-purple-600 text-white shadow-lg" : "text-slate-500"}`}
          >
            Search Audit
          </button>
        </div>
      </div>

      {activeHistoryTab === "Analysis" ? (
        <div className="space-y-6">
        {history.map((item) => {
          const itemId = `${item.tender_code}-${item.analyzed_at}`;
          const isExpanded = expandedItems.includes(itemId);
          
          return (
            <div key={itemId} className="glass-card rounded-3xl p-8 border border-white/5 hover:border-purple-500/30 transition-all duration-300">
              <div className="flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">
                <div className="space-y-1">
                  <div className="flex items-center gap-3 mb-2">
                     <span className="text-[10px] font-black uppercase tracking-widest text-purple-400 bg-purple-500/10 px-2 py-0.5 rounded border border-purple-500/20">Audit Record</span>
                     <span className="text-xs text-slate-500 font-mono">{item.tender_code}</span>
                  </div>
                  <h3 className="text-2xl font-bold text-white tracking-tight">{item.tender_name}</h3>
                  <p className="text-xs text-slate-500">{new Date(item.analyzed_at).toLocaleString()}</p>
                </div>
                
                <div className="flex items-center gap-8 bg-white/5 rounded-2xl p-6 border border-white/5">
                  <div className="text-center">
                    <p className="text-[9px] uppercase tracking-widest text-slate-500 font-bold mb-1">Fit Score</p>
                    <p className="text-3xl font-black text-white">{item.analysis.fit_score}%</p>
                  </div>
                  <div className="h-10 w-px bg-white/10" />
                  <div className="text-center">
                    <p className="text-[9px] uppercase tracking-widest text-slate-500 font-bold mb-1">Decision</p>
                    <p className={`text-xs font-black uppercase tracking-widest px-3 py-1 rounded-full ${item.analysis.decision === 'Recommended' ? 'bg-green-500/20 text-green-400' : 'bg-amber-500/20 text-amber-400'}`}>
                      {item.analysis.decision}
                    </p>
                  </div>
                </div>
                
                <div className="flex gap-2">
                   <button 
                     onClick={() => window.print()}
                     className="px-4 py-2 rounded-xl bg-white/5 border border-white/10 text-[10px] font-bold text-slate-400 hover:text-white hover:bg-white/10 transition uppercase tracking-[0.2em]"
                   >
                     Export PDF
                   </button>
                </div>
              </div>

              <div className="mt-8 grid gap-4 grid-cols-2 md:grid-cols-4">
                <div className="p-4 rounded-2xl bg-black/20 border border-white/5">
                  <p className="text-[9px] uppercase text-slate-500 font-bold mb-1">Risks Detected</p>
                  <p className="text-sm font-bold text-white">{item.analysis.risks.length}</p>
                </div>
                <div className="p-4 rounded-2xl bg-black/20 border border-white/5">
                  <p className="text-[9px] uppercase text-slate-500 font-bold mb-1">Key Requirements</p>
                  <p className="text-sm font-bold text-white">{item.analysis.key_requirements.length}</p>
                </div>
                <div className="p-4 rounded-2xl bg-black/20 border border-white/5">
                  <p className="text-[9px] uppercase text-slate-500 font-bold mb-1">Legal Gaps</p>
                  <p className="text-sm font-bold text-white">{item.analysis.compliance_gaps.length}</p>
                </div>
                <div className="p-4 rounded-2xl bg-black/20 border border-white/5">
                  <p className="text-[9px] uppercase text-slate-500 font-bold mb-1">Audit Logs</p>
                  <p className="text-sm font-bold text-white">{item.analysis.audit_log?.length ?? 0}</p>
                </div>
              </div>
              
              <div className="mt-6">
                <button 
                  onClick={() => toggleExpand(itemId)}
                  className="text-xs font-bold text-purple-400 hover:text-white transition-colors flex items-center gap-2"
                >
                  <span>{isExpanded ? "Hide Thought Process" : "View Agent Thought Process"}</span>
                  <span className={`transition-transform ${isExpanded ? "rotate-90" : ""}`}>→</span>
                </button>
              </div>

              {isExpanded && (
                <div className="mt-8 p-6 rounded-3xl bg-black/40 border border-white/5 animate-in slide-in-from-top-4 duration-500">
                  {/* Professional Print Header */}
                  <div className="hidden print-only mb-12 border-b-4 border-slate-900 pb-8 text-center">
                    <h1 className="text-4xl font-black text-slate-900 mb-2">ANDESOPS AI</h1>
                    <p className="text-sm font-bold uppercase tracking-[0.5em] text-slate-500">Historical Audit Report</p>
                    <div className="mt-6 flex justify-between text-[10px] font-mono text-slate-400">
                      <span>DATE: {new Date().toLocaleDateString()}</span>
                      <span>REF ID: {item.tender_code}</span>
                      <span>ORIGINAL ANALYSIS: {new Date(item.analyzed_at).toLocaleString()}</span>
                    </div>
                  </div>
                  
                  <h4 className="text-[10px] font-black uppercase tracking-widest text-slate-500 mb-4 no-print">Agent Intelligence Log (Full Audit)</h4>
                  
                  {item.analysis.raw_responses && (
                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
                       {Object.entries(item.analysis.raw_responses).map(([agent, content]) => (
                         <div key={agent} className="space-y-3">
                            <div className="flex items-center gap-2">
                               <span className="text-xl">{agent === 'legal' ? '⚖️' : agent === 'technical' ? '👨‍💻' : '🕵️'}</span>
                               <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-purple-400">{agent} Agent</span>
                            </div>
                            <div className="p-4 rounded-2xl bg-white/[0.03] border border-white/5 max-h-[300px] overflow-y-auto custom-scrollbar">
                               <p className="text-[11px] text-slate-400 leading-relaxed whitespace-pre-wrap">{content}</p>
                            </div>
                         </div>
                       ))}
                    </div>
                  )}

                  <div className="space-y-3">
                    {item.analysis.audit_log?.map((log, idx) => (
                      <div key={idx} className="flex gap-4 p-3 rounded-xl bg-white/[0.02] border border-white/[0.02]">
                        <span className="text-xs opacity-30 mt-0.5">[{idx + 1}]</span>
                        <p className="text-xs text-slate-400 font-mono leading-relaxed">{log}</p>
                      </div>
                    ))}
                    {(!item.analysis.audit_log || item.analysis.audit_log.length === 0) && (
                      <p className="text-xs text-slate-600 italic">No logs available for this session.</p>
                    )}
                  </div>
                </div>
              )}
            </div>
          );
        })}
        </div>
      ) : (
        <div className="glass-card rounded-3xl overflow-hidden border border-white/5">
          <table className="w-full text-left text-sm">
            <thead className="bg-white/5 text-slate-500 uppercase text-[10px] font-bold border-b border-white/5">
              <tr>
                <th className="px-6 py-5">Search Query</th>
                <th className="px-6 py-5">Results</th>
                <th className="px-6 py-5">Type</th>
                <th className="px-6 py-5 text-right">Timestamp</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/5">
              {searchHistory?.map((s, idx) => (
                <tr key={idx} className="hover:bg-white/[0.04] transition-colors">
                  <td className="px-6 py-5 font-bold text-white">{s.query}</td>
                  <td className="px-6 py-5 text-cyan font-mono">{s.results_count}</td>
                  <td className="px-6 py-5">
                    <span className={`px-2 py-0.5 rounded text-[10px] font-black uppercase ${s.is_agile ? 'bg-green-500/10 text-green-400' : 'bg-white/5 text-slate-500'}`}>
                      {s.is_agile ? "Agile" : "Standard"}
                    </span>
                  </td>
                  <td className="px-6 py-5 text-right text-slate-500 text-xs">{new Date(s.searched_at).toLocaleString()}</td>
                </tr>
              ))}
              {!searchHistory?.length && (
                <tr>
                  <td colSpan={4} className="px-6 py-12 text-center text-slate-600 italic">No search logs recorded yet.</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
