import { useState, useEffect } from 'react';
import StatsCard from './StatsCard';
import RecentLeads from './RecentLeads';
import { fetchStats, fetchLeads } from '../../utils/api';

function Dashboard() {
  const [stats, setStats] = useState({ total: 0, active: 0, abandoned: 0, recovered: 0, submitted: 0, recovery_rate: 0 });
  const [recentLeads, setRecentLeads] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

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

  const loadDashboardData = async () => {
    try {
      setError(null);
      const [statsData, leadsData] = await Promise.all([fetchStats(), fetchLeads({ per_page: 10 })]);
      if (statsData.success) setStats(statsData.data);
      if (leadsData.success) setRecentLeads(leadsData.data);
    } catch (err) {
      setError('Failed to load dashboard data. Please refresh.');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="flex flex-col items-center gap-3">
          <div className="rf-spinner" />
          <p className="text-sm text-slate-500">Loading dashboard…</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="w-12 h-12 mx-auto mb-3 bg-red-50 rounded-xl flex items-center justify-center text-red-400">
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <p className="font-semibold text-slate-700 mb-1">Something went wrong</p>
          <p className="text-slate-500 text-sm mb-4">{error}</p>
          <button onClick={loadDashboardData} className="px-4 py-2 bg-indigo-600 text-white text-sm font-semibold rounded-lg hover:bg-indigo-700 transition-colors">
            Try Again
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Page header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-slate-900">Dashboard</h2>
          <p className="text-sm text-slate-500 mt-0.5">Overview of your lead recovery performance</p>
        </div>
        <button
          onClick={loadDashboardData}
          className="flex items-center gap-2 px-3.5 py-2 text-sm font-medium text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 hover:border-slate-300 transition-all"
          style={{ boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
          Refresh
        </button>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <StatsCard title="Total Leads"    value={stats.total.toLocaleString()}        icon="users"  color="blue" />
        <StatsCard title="Abandoned"      value={stats.abandoned.toLocaleString()}    icon="alert"  color="orange" />
        <StatsCard title="Recovered"      value={stats.recovered.toLocaleString()}    icon="check"  color="green" />
        <StatsCard title="Recovery Rate"  value={`${stats.recovery_rate}%`}           icon="chart"  color="purple" />
      </div>

      {/* Status breakdown */}
      <div className="bg-white rounded-xl border border-slate-200 p-5" style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
        <h3 className="text-sm font-bold text-slate-700 mb-4 uppercase tracking-wider">Lead Status Breakdown</h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {[
            { label: 'Active',    count: stats.active,    dotClass: 'bg-emerald-500' },
            { label: 'Abandoned', count: stats.abandoned,  dotClass: 'bg-orange-500' },
            { label: 'Recovered', count: stats.recovered,  dotClass: 'bg-blue-500' },
            { label: 'Submitted', count: stats.submitted,  dotClass: 'bg-purple-500' },
          ].map((item) => (
            <div key={item.label} className="flex items-center gap-2.5 p-3 bg-slate-50 rounded-lg">
              <div className={`w-2.5 h-2.5 rounded-full ${item.dotClass} shrink-0`} />
              <div>
                <p className="text-[0.6875rem] text-slate-500 font-medium uppercase tracking-wide">{item.label}</p>
                <p className="text-lg font-bold text-slate-900 leading-tight">{item.count.toLocaleString()}</p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Recent Leads */}
      <RecentLeads leads={recentLeads} />
    </div>
  );
}

export default Dashboard;
