'use client';

import { useState, useEffect } from 'react';
import { DashboardHeader } from '@/components/DashboardHeader';
import { 
  Activity, 
  Clock, 
  Terminal, 
  RefreshCcw, 
  CheckCircle2, 
  XCircle, 
  Loader2,
  ChevronRight,
  ArrowRight
} from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';

export default function LogsPage() {
  const [logs, setLogs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchLogs = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/logs');
      const data = await res.json();
      setLogs(data.logs || []);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLogs();
  }, []);

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'SUCCESS': return <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />;
      case 'FAILED': return <XCircle className="w-3.5 h-3.5 text-red-500" />;
      default: return <Activity className="w-3.5 h-3.5 text-blue-500" />;
    }
  };

  return (
    <div className="flex-1 flex flex-col bg-white text-slate-900 font-sans">

      <main className="flex-1 p-4 lg:p-10 space-y-8 lg:space-y-12 overflow-y-auto w-full max-w-[1400px] mx-auto animate-fade-in shadow-inner bg-slate-50/20">
        
        {/* Controls Section */}
        <section className="space-y-6">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 px-2">
            <div className="flex flex-wrap items-center gap-3">
              <div className="flex items-center gap-2 px-3 py-1.5 lg:px-4 lg:py-2 bg-emerald-50 border border-emerald-100 rounded-full">
                <div className="w-1.5 h-1.5 lg:w-2 lg:h-2 rounded-full bg-emerald-500 animate-pulse" />
                <span className="text-[10px] lg:text-[11px] font-black text-emerald-600 uppercase tracking-widest">Active Monitoring</span>
              </div>
              <button 
                onClick={fetchLogs}
                disabled={loading}
                className="flex items-center justify-center gap-2 px-6 py-2.5 bg-[#121212] text-white hover:bg-black rounded-full text-[12px] lg:text-[13px] font-bold transition-all shadow-sm active:scale-[0.98]"
              >
                <RefreshCcw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
                {loading ? 'Syncing...' : 'Refresh Logs'}
              </button>
            </div>
          </div>
        </section>

        {/* Audit List */}
        <section className="space-y-4 max-w-5xl">
          {loading && logs.length === 0 ? (
            <div className="py-24 lg:py-32 flex flex-col items-center justify-center text-center opacity-40">
              <Loader2 className="w-8 h-8 lg:w-10 lg:h-10 text-slate-900 animate-spin mb-4" />
              <p className="text-[15px] lg:text-[16px] font-serif italic text-slate-400">Decrypting system sequences...</p>
            </div>
          ) : logs.length === 0 ? (
            <div className="py-20 lg:py-32 text-center border border-dashed border-slate-200 rounded-[28px] lg:rounded-[40px] bg-slate-50/30">
              <p className="text-[15px] lg:text-[16px] font-serif italic text-slate-400">The archives are currently empty.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-3 lg:gap-4">
              {logs.map((log) => (
                <div 
                  key={log.id} 
                  className="group relative flex flex-col sm:flex-row sm:items-center justify-between p-5 lg:p-6 bg-white border border-slate-100 rounded-[24px] lg:rounded-[32px] hover:border-slate-200 transition-all shadow-sm"
                >
                  <div className="flex items-start gap-4 lg:gap-6">
                    <div className="hidden sm:block mt-1">
                      <div className="h-10 w-10 lg:h-11 lg:w-11 rounded-full bg-slate-50 border border-slate-100 flex items-center justify-center text-slate-400 group-hover:text-slate-900 shadow-sm transition-colors">
                        <Terminal className="w-4 h-4" />
                      </div>
                    </div>
                    
                    <div className="space-y-1.5">
                      <div className="flex flex-wrap items-center gap-3">
                        <p className="text-[14px] lg:text-[15px] font-bold text-slate-900 capitalize tracking-tight">{log.action.replace('_', ' ')}</p>
                        <div className="flex items-center gap-1.5 px-2 py-0.5 bg-slate-50 border border-slate-100 rounded-lg">
                          {getStatusIcon(log.status)}
                          <span className="text-[9px] lg:text-[10px] font-black text-slate-400 uppercase tracking-widest">{log.status}</span>
                        </div>
                        <div className="sm:hidden text-[10px] font-bold text-slate-300 uppercase tracking-tighter ml-auto">
                           {formatDistanceToNow(new Date(log.createdAt), { addSuffix: true })}
                        </div>
                      </div>
                      <p className="text-[13px] lg:text-[14px] text-slate-500 font-medium max-w-2xl leading-relaxed">
                        {log.details}
                      </p>
                    </div>
                  </div>

                  <div className="mt-4 sm:mt-0 flex flex-row sm:flex-col items-center sm:items-end justify-between sm:justify-center gap-3 border-t sm:border-0 pt-4 sm:pt-0 border-slate-100">
                    <div className="hidden sm:flex items-center gap-1.5 text-[11px] font-bold text-slate-300 uppercase tracking-tighter">
                      <Clock className="w-3.5 h-3.5" />
                      {formatDistanceToNow(new Date(log.createdAt), { addSuffix: true })}
                    </div>
                    <button className="h-8 w-8 lg:h-9 lg:w-9 rounded-full bg-slate-50 border border-slate-200 flex items-center justify-center text-slate-400 hover:text-slate-900 hover:border-slate-400 transition-all ml-auto sm:ml-0">
                      <ChevronRight className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </section>

        {/* Footer Metric */}
        {!loading && logs.length > 0 && (
          <div className="pt-8 lg:pt-12 px-2 flex flex-col sm:flex-row items-center justify-between border-t border-slate-100 gap-4 sm:gap-0">
             <p className="text-[11px] lg:text-[12px] font-bold text-slate-400 uppercase tracking-widest text-center sm:text-left">
                Showing last <span className="text-slate-900">{logs.length}</span> audit sequences
             </p>
             <a href="/api/export/logs" target="_blank" rel="noreferrer" className="text-[12px] lg:text-[13px] font-bold text-slate-900 flex items-center gap-1 group">
                Download Full Registry <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
             </a>
          </div>
        )}
      </main>
    </div>
  );
}
