'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { DashboardHeader } from '@/components/DashboardHeader';
import { 
  Users, 
  Zap, 
  TrendingUp, 
  Target,
  ShieldCheck,
  Globe,
  MapPin,
  Activity,
  Database,
  ArrowRight
} from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';

export default function DashboardPage() {
  const [stats, setStats] = useState({
    totalLeads: 0,
    contactedLeads: 0,
    interestedLeads: 0,
    recentActivity: [] as any[],
    conversionRate: 0
  });

  const fetchStats = async () => {
    try {
      const res = await fetch('/api/dashboard/stats');
      const data = await res.json();
      if (data.stats) {
        setStats(data.stats);
      }
    } catch (e) {
      console.error('Failed to fetch stats', e);
    }
  };

  useEffect(() => {
    fetchStats();
    const interval = setInterval(fetchStats, 5000); // poll every 5s
    return () => clearInterval(interval);
  }, []);

  const cards = [
    { label: 'Total Leads', value: stats.totalLeads, icon: Users, trend: '+12%', subtitle: 'Database size' },
    { label: 'Outreach Sent', value: stats.contactedLeads, icon: Zap, trend: '+5%', subtitle: 'Last 7 days' },
    { label: 'Hot Prospects', value: stats.interestedLeads, icon: Target, trend: '+18%', subtitle: 'High intent' },
    { label: 'Conversion', value: `${stats.conversionRate}%`, icon: TrendingUp, trend: '+2%', subtitle: 'Engagement' },
  ];

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

      <main className="flex-1 p-4 sm:p-6 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/30">
        
        {/* Editorial Stats Section */}
        <section className="space-y-6">
           <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 px-2">
             <Link href="/dashboard/leads" className="text-[13px] font-bold text-slate-900 flex items-center gap-1 hover:translate-x-1 transition-transform w-fit ml-auto">
               Detailed Report <ArrowRight className="w-3.5 h-3.5" />
             </Link>
           </div>

          <div className="grid grid-cols-1 xs:grid-cols-2 lg:grid-cols-4 gap-4 lg:gap-6">
            {cards.map((card) => (
              <div 
                key={card.label} 
                className="bg-white border border-slate-100 p-6 lg:p-8 rounded-[24px] lg:rounded-[32px] shadow-sm flex flex-col gap-4 lg:gap-6 group hover:border-slate-200 transition-all"
              >
                <div className="flex items-center justify-between">
                  <div className="h-10 w-10 rounded-full bg-slate-50 border border-slate-100 flex items-center justify-center">
                    <card.icon className="w-4 h-4 text-slate-900" />
                  </div>
                  <span className="text-[10px] lg:text-[12px] font-bold text-emerald-500 bg-emerald-50 px-2 py-1 rounded-full uppercase tracking-tight">
                    {card.trend}
                  </span>
                </div>
                
                <div className="space-y-1">
                   <p className="text-[11px] lg:text-[13px] font-bold text-slate-400 uppercase tracking-wide">{card.label}</p>
                   <h3 className="text-[32px] lg:text-[48px] font-serif italic text-slate-900 leading-[1.1] tracking-tight">{card.value}</h3>
                   <p className="text-[11px] lg:text-[12px] text-slate-400 font-medium">{card.subtitle}</p>
                </div>
              </div>
            ))}
          </div>
        </section>

        {/* Detailed Insights & Integrations Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12 pt-4">
          
          {/* Recent Activity */}
          <div className="lg:col-span-7 space-y-6 lg:space-y-8">
            <div className="flex items-center justify-between px-2 border-b border-slate-100 pb-4">
              <h3 className="text-[11px] lg:text-[12px] font-bold uppercase tracking-widest text-slate-400 flex items-center gap-2">
                <Activity className="w-4 h-4" />
                Recent Logs
              </h3>
            </div>
            
            <div className="space-y-1 max-h-[700px] overflow-y-auto pr-2 custom-scrollbar">
              {stats.recentActivity.length > 0 ? stats.recentActivity.map((log) => (
                <div 
                  key={log.id} 
                  className="group flex flex-col sm:flex-row sm:items-center justify-between py-4 px-4 rounded-xl lg:rounded-2xl hover:bg-white hover:shadow-sm transition-all border border-transparent hover:border-slate-100 gap-3 sm:gap-0"
                >
                  <div className="flex items-center gap-4 lg:gap-5">
                    <div className="h-10 w-10 lg:h-11 lg:w-11 rounded-full bg-white border border-slate-100 flex items-center justify-center text-slate-900 shadow-sm group-hover:scale-110 transition-transform">
                      <Target className="w-4 h-4" />
                    </div>
                    <div>
                      <p className="text-[14px] lg:text-[15px] font-semibold text-slate-900 capitalize tracking-tight">{log.action.replace('_', ' ')}</p>
                      <p className="text-[12px] lg:text-[13px] text-slate-400 font-medium mt-0.5">{log.details}</p>
                    </div>
                  </div>
                  <div className="sm:text-right pl-14 sm:pl-0">
                    <span className="text-[10px] lg:text-[12px] text-slate-400 font-bold uppercase tracking-tighter">
                      {formatDistanceToNow(new Date(log.createdAt), { addSuffix: true })}
                    </span>
                  </div>
                </div>
              )) : (
                <div className="p-12 lg:p-16 text-center text-slate-400 font-serif italic border-2 border-dashed border-slate-100 rounded-[30px] lg:rounded-[40px]">
                  No activity sequences recorded...
                </div>
              )}
            </div>
          </div>

          {/* System Health Section */}
          <div className="lg:col-span-5 space-y-6 lg:space-y-8">
              <div className="flex items-center justify-between px-2 border-b border-slate-100 pb-4">
                <h3 className="text-[11px] lg:text-[12px] font-bold uppercase tracking-widest text-slate-400 flex items-center gap-2">
                  <ShieldCheck className="w-4 h-4 text-emerald-500" />
                  Network Status
                </h3>
              </div>

              <div className="bg-white border border-slate-100 rounded-[30px] lg:rounded-[40px] p-6 lg:p-8 shadow-sm space-y-6 lg:space-y-8">
                {[
                  { name: 'G-Places API', status: 'Operational', color: 'bg-emerald-500', icon: MapPin },
                  { name: 'Registry DB', status: 'Operational', color: 'bg-emerald-500', icon: Database },
                  { name: 'Enrichment Node', status: 'Standby', color: 'bg-amber-400', icon: Globe },
                ].map(svc => (
                  <div key={svc.name} className="flex items-center justify-between group">
                    <div className="flex items-center gap-4">
                      <div className="h-9 w-9 lg:h-10 lg:w-10 rounded-full bg-slate-50 border border-slate-100 flex items-center justify-center group-hover:bg-white transition-colors">
                        <svc.icon className="w-3.5 h-3.5 text-slate-900" />
                      </div>
                      <span className="text-[13px] lg:text-[14px] font-bold text-slate-900 tracking-tight">{svc.name}</span>
                    </div>
                    <div className="flex items-center gap-2 lg:gap-3">
                      <span className="text-[10px] lg:text-[11px] font-black uppercase tracking-widest text-slate-300">{svc.status}</span>
                      <div className={`w-2 h-2 lg:w-2.5 lg:h-2.5 rounded-full ${svc.color} shadow-sm`} />
                    </div>
                  </div>
                ))}
                
                <div className="pt-4 border-t border-slate-100/50">
                  <div className="p-4 bg-slate-50 rounded-2xl border border-slate-100/50">
                    <p className="text-[11px] lg:text-[12px] text-slate-400 font-medium leading-relaxed">
                      All systems are performing within <span className="text-slate-900 font-bold tracking-tight">optimum parameters</span>.
                    </p>
                  </div>
                </div>
              </div>
          </div>

        </div>
      </main>
    </div>
  );
}
