import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Users, ClipboardList, CalendarCheck2, TrendingUp, AlertCircle, Receipt, Wallet } from 'lucide-react';
import { useHRStore } from '../../store/hr';
import { useAuthStore } from '../../store/auth';

const currency = (n: number) =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(
    Number.isFinite(n) ? n : 0,
  );

const statusColor = (status?: string) => {
  const s = (status || '').toLowerCase();
  if (s === 'paid') return 'bg-emerald-50 text-emerald-700 border-emerald-100 dark:bg-emerald-900/20 dark:text-emerald-300 dark:border-emerald-900/30';
  if (s === 'calculated') return 'bg-blue-50 text-blue-700 border-blue-100 dark:bg-blue-900/20 dark:text-blue-300 dark:border-blue-900/30';
  if (s === 'draft') return 'bg-amber-50 text-amber-700 border-amber-100 dark:bg-amber-900/20 dark:text-amber-300 dark:border-amber-900/30';
  if (s === 'cancelled' || s === 'rejected') return 'bg-red-50 text-red-700 border-red-100 dark:bg-red-900/20 dark:text-red-300 dark:border-red-900/30';
  return 'bg-muted text-text-muted border-border';
};

export default function HRDashboard() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const { dashboardSummary, loading, error, fetchDashboardSummary } = useHRStore();

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

  if (!dashboardSummary) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
        <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin" />
        <p className="font-medium animate-pulse">Loading HR dashboard…</p>
      </div>
    );
  }

  if (error && !dashboardSummary) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
        <AlertCircle size={48} className="text-red-500" />
        <p className="text-text-muted font-medium">Unable to load HR dashboard.</p>
        <p className="text-sm text-text-muted">{error}</p>
        <button
          onClick={() => fetchDashboardSummary()}
          className="px-4 py-2 bg-primary text-white rounded-xl"
        >
          Retry
        </button>
      </div>
    );
  }

  const summary = dashboardSummary!;
  const headcount = summary.headcount ?? 0;
  const openLeave = summary.open_leave_requests ?? 0;
  const last = summary.last_payroll_run;
  const attendancePct = Number.isFinite(summary.attendance_today_pct) ? summary.attendance_today_pct : 0;

  const cards = [
    {
      label: 'Active Staff',
      value: headcount,
      icon: Users,
      sub: 'Total active staff records',
      color: 'blue',
      path: '/hr/management',
    },
    {
      label: 'Open Leave Requests',
      value: openLeave,
      icon: ClipboardList,
      sub: 'Pending approval',
      color: 'orange',
      path: '/hr/management',
    },
    {
      label: 'Last Payroll Run',
      value: last ? last.period : '—',
      icon: Wallet,
      sub: last ? `Status: ${last.status}` : 'No payroll run yet',
      color: 'emerald',
      badge: last?.status,
      path: '/finance/payroll/runs',
    },
    {
      label: "Today's Attendance",
      value: `${attendancePct}%`,
      icon: CalendarCheck2,
      sub: 'Staff check-ins for today',
      color: 'primary',
      path: '/hr/attendance',
    },
  ];

  return (
    <div className="space-y-8 animate-in fade-in duration-500">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">
            HR Dashboard
          </h1>
          <p className="text-text-muted mt-1 text-lg">
            Welcome, {user?.first_name || 'HR'}. Here's how the people side is looking today.
          </p>
        </div>
        <button
          onClick={() => navigate('/hr/management')}
          className="flex items-center gap-2 bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl font-semibold transition-all shadow-lg shadow-blue-900/10 active:scale-[0.98]"
        >
          <Users size={20} />
          <span>Open HR Center</span>
        </button>
      </div>

      {/* Stat cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {cards.map((card) => (
          <div
            key={card.label}
            onClick={() => navigate(card.path)}
            className="p-6 rounded-2xl border bg-card border-border transition-all duration-300 hover:shadow-md cursor-pointer"
          >
            <div className="flex justify-between items-start mb-4">
              <div className="p-2.5 rounded-xl bg-muted text-[#0047AB]">
                <card.icon size={22} />
              </div>
              {card.badge && (
                <span
                  className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${statusColor(
                    card.badge,
                  )}`}
                >
                  {card.badge}
                </span>
              )}
            </div>
            <p className="text-xs font-bold uppercase tracking-wider text-text-muted">
              {card.label}
            </p>
            <h3 className="text-3xl font-black mt-1 tracking-tight">{card.value}</h3>
            <p className="text-[0.65rem] mt-2 italic font-medium text-text-muted">
              {card.sub}
            </p>
          </div>
        ))}
      </div>

      {/* Two-column body */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Attendance — primary widget */}
        <div className="lg:col-span-2 bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
          <div className="px-6 py-4 border-b border-border bg-muted/50">
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
              Staff attendance today
            </h4>
          </div>
          <div className="p-6 space-y-4">
            <div className="flex items-end justify-between">
              <div>
                <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">
                  Check-in rate
                </p>
                <h5 className="text-2xl font-bold text-text">{attendancePct}% Present</h5>
              </div>
              <span
                className={`text-[0.65rem] font-bold uppercase px-2.5 py-1 rounded-full border ${statusColor(
                  attendancePct >= 80 ? 'paid' : attendancePct >= 50 ? 'draft' : 'cancelled',
                )}`}
              >
                {attendancePct >= 80 ? 'On Track' : attendancePct >= 50 ? 'Below Target' : 'Critical'}
              </span>
            </div>
            <div className="w-full bg-muted rounded-full h-3.5 overflow-hidden p-0.5 border border-border shadow-inner">
              <div
                className="bg-primary h-full rounded-full transition-all duration-1000 relative overflow-hidden"
                style={{ width: `${Math.min(100, attendancePct)}%` }}
              >
                <div className="absolute inset-0 bg-white/20 animate-pulse" />
              </div>
            </div>
            <p className="text-xs text-text-muted font-medium leading-relaxed">
              Computed from staff_attendance rows logged today (present / late / half-day counted as attended).
            </p>
          </div>
        </div>

        {/* Right — payroll card */}
        <div className="bg-slate-900 rounded-2xl p-6 text-white shadow-xl shadow-blue-900/10 relative overflow-hidden">
          <div className="absolute -right-8 -bottom-8 opacity-10">
            <Wallet size={120} />
          </div>
          <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-white/40 mb-4 relative z-10">
            Payroll Summary
          </h4>
          {last ? (
            <div className="space-y-4 relative z-10">
              <div>
                <p className="text-[0.6rem] text-white/40 uppercase tracking-widest font-black">
                  Period
                </p>
                <p className="text-xl font-bold">{last.period}</p>
              </div>
              <div className="flex items-center gap-2">
                <span
                  className={`text-[0.65rem] uppercase font-black px-2.5 py-1 rounded-full border ${statusColor(
                    last.status,
                  )}`}
                >
                  {last.status}
                </span>
                <span className="text-[0.65rem] text-white/40 uppercase font-black">
                  Run #{last.id}
                </span>
              </div>
              <button
                onClick={() => navigate('/finance/payroll/runs')}
                className="w-full mt-2 py-2.5 px-4 rounded-xl bg-white/10 hover:bg-white/20 text-white text-[0.75rem] font-black uppercase tracking-widest transition-all border border-white/10"
              >
                Open Payroll
              </button>
            </div>
          ) : (
            <div className="space-y-4 relative z-10">
              <p className="text-white/60 text-sm">
                No payroll runs yet. Create one from the HR Center.
              </p>
              <button
                onClick={() => navigate('/hr/management')}
                className="w-full mt-2 py-2.5 px-4 rounded-xl bg-white/10 hover:bg-white/20 text-white text-[0.75rem] font-black uppercase tracking-widest transition-all border border-white/10"
              >
                Go to HR Center
              </button>
            </div>
          )}
        </div>
      </div>

      {/* Bottom — quick links */}
      <div className="bg-card rounded-2xl border border-border p-6 shadow-sm">
        <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary mb-4">
          Quick links
        </h4>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {[
            { label: 'HR Center', icon: Users, path: '/hr/management' },
            { label: 'Staff Attendance', icon: CalendarCheck2, path: '/hr/attendance' },
            { label: 'Payroll', icon: Wallet, path: '/finance/payroll/runs' },
            { label: 'Expenses', icon: Receipt, path: '/finance/expenses' },
          ].map((q) => (
            <button
              key={q.label}
              onClick={() => navigate(q.path)}
              className="flex items-center gap-3 p-4 bg-muted/50 hover:bg-primary hover:text-white rounded-2xl transition-all duration-300 group border border-border hover:border-transparent hover:shadow-lg hover:shadow-blue-900/10"
            >
              <q.icon size={20} />
              <span className="text-[0.75rem] font-bold text-left leading-tight">{q.label}</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
