import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Users, HardHat, UserCircle, Mail, AlertTriangle, FolderKanban, ShieldAlert } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import StatusPill from '@/components/workshop/StatusPill';
import { accountService } from '@/services/accountService';
import { invitationService } from '@/services/invitationService';
import { adapters } from '@/services/serviceConfig';

function StatCard({ icon: Icon, label, value, tone = 'cyan', to }) {
  const tones = { cyan: 'text-violet-300', green: 'text-emerald-300', red: 'text-red-300', amber: 'text-amber-300' };
  return (
    <Link to={to || '#'} className="panel p-5 transition hover:border-shire-purple/40">
      <div className="flex items-center justify-between">
        <Icon className={`h-7 w-7 ${tones[tone]}`} />
        <span className="text-3xl font-bold text-white">{value}</span>
      </div>
      <p className="mt-2 text-sm text-shire-text-secondary">{label}</p>
    </Link>
  );
}

export default function AdminConsole() {
  const [accounts, setAccounts] = useState(null);
  const [invites, setInvites] = useState(null);
  const [projects, setProjects] = useState(null);
  const [audit, setAudit] = useState(null);

  useEffect(() => {
    accountService.list().then(setAccounts);
    invitationService.list().then(setInvites);
    adapters.database.list('CoverProject').then(setProjects);
    adapters.database.filter('AuditEvent', {}, '-created_date', 10).then(setAudit);
  }, []);

  if (!accounts || !invites || !projects) return <LoadingPanel label="Loading admin console" />;

  const byRole = (r) => accounts.filter(a => a.role === r && a.account_status === 'Active');
  const pendingInvites = invites.filter(i => i.status === 'pending');
  const suspended = accounts.filter(a => a.account_status === 'Suspended');
  const customers = byRole('customer');
  const builders = byRole('builder');
  const admins = [...byRole('owner_admin'), ...byRole('admin')];
  const noPortal = customers.filter(c => !c.user_id);
  const unassigned = projects.filter(p => !p.assigned_builder);

  return (
    <>
      <PageHeader eyebrow="Workshop Console" title="Admin Dashboard" description="Real-time counts across accounts, invitations, projects and security events." />
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard icon={ShieldAlert} label="Active Admins" value={admins.length} tone="cyan" to="/admin/users" />
        <StatCard icon={HardHat} label="Active Builders" value={builders.length} tone="cyan" to="/admin/users" />
        <StatCard icon={UserCircle} label="Active Customers" value={customers.length} tone="green" to="/admin/users" />
        <StatCard icon={Mail} label="Pending Invitations" value={pendingInvites.length} tone="amber" to="/admin/invitations" />
        <StatCard icon={AlertTriangle} label="Suspended Accounts" value={suspended.length} tone="red" to="/admin/users" />
        <StatCard icon={UserCircle} label="Customers w/o Portal Access" value={noPortal.length} tone="amber" to="/admin/users" />
        <StatCard icon={FolderKanban} label="Unassigned Projects" value={unassigned.length} tone="amber" to="/admin/assignments" />
        <StatCard icon={Users} label="Total Accounts" value={accounts.length} tone="cyan" to="/admin/users" />
      </div>

      <div className="mt-8 grid gap-6 lg:grid-cols-2">
        <section className="panel p-5">
          <h2 className="section-title">Pending Invitations</h2>
          {pendingInvites.length === 0 ? <p className="text-sm text-shire-text-muted">No pending invitations.</p> : (
            <ul className="space-y-2">
              {pendingInvites.slice(0, 6).map(i => (
                <li key={i.uuid} className="flex items-center justify-between text-sm">
                  <span className="text-slate-200">{i.email}</span>
                  <span className="flex items-center gap-2">
                    <StatusPill tone="amber">{i.intended_role}</StatusPill>
                    <Link to="/admin/invitations" className="text-xs text-violet-300 hover:underline">manage</Link>
                  </span>
                </li>
              ))}
            </ul>
          )}
        </section>
        <section className="panel p-5">
          <h2 className="section-title">Recent Audit Events</h2>
          {!audit ? <LoadingPanel label="Loading" /> : audit.length === 0 ? <p className="text-sm text-shire-text-muted">No events yet.</p> : (
            <ul className="space-y-2 text-sm">
              {audit.map(e => (
                <li key={e.id || e.uuid} className="flex items-start justify-between gap-3 border-b border-shire-border pb-2">
                  <span className="text-slate-200">{e.summary}</span>
                  <span className="text-xs text-shire-text-muted shrink-0">{e.actor_name}</span>
                </li>
              ))}
            </ul>
          )}
        </section>
      </div>
    </>
  );
}