/**
 * Nurse Dashboard (school doctor / sanatorium console)
 * Landing page after nurse@school.com login.
 */

import { Link } from 'react-router-dom';
import { useEffect, useState } from 'react';
import {
  Stethoscope, HeartPulse, UtensilsCrossed, Pill, FileText, AlertTriangle,
  LayoutDashboard, Bed, Syringe, Activity, UserCheck, Plus, ArrowRight
} from 'lucide-react';
import api from '../../store/auth';

export default function NurseDashboard() {
  const [stats, setStats] = useState({
    totalStudents: 0,
    activeVisits: 0,
    occupiedBeds: 0,
    allergyAlerts: 0,
  });

  useEffect(() => {
    (async () => {
      try {
        const [usersRes, visitsRes, diningRes] = await Promise.all([
          api.get('/users?role=student&limit=1000').catch(() => ({ data: { users: [] } })),
          api.get('/medical/visits?limit=100').catch(() => ({ data: [] })),
          api.get('/medical/dining/allergies').catch(() => ({ data: [] })),
        ]);

        const users = usersRes.data.users || usersRes.data || [];
        const visits = Array.isArray(visitsRes.data) ? visitsRes.data : [];
        const dining = Array.isArray(diningRes.data) ? diningRes.data : [];

        const occupied = visits.filter((v: any) => v.disposition === 'admitted').length;

        setStats({
          totalStudents: users.length,
          activeVisits: visits.length,
          occupiedBeds: occupied,
          allergyAlerts: dining.filter((d: any) => d.allergies || d.dietary_restrictions).length,
        });
      } catch (e) {
        // Soft fail
      }
    })();
  }, []);

  const cards = [
    { path: '/sanatorium', label: 'Sanatorium Console', hint: 'Student lookup, Sick Bay beds, visit encounters & immunizations', icon: Stethoscope, color: 'rose' },
    { path: '/dining-hall', label: 'Dining Hall Alerts', hint: 'Kitchen-tablet roster of allergens & dietary restrictions', icon: UtensilsCrossed, color: 'amber' },
    { path: '/messages', label: 'Messages & Alerts', hint: 'Direct messaging to parents, teachers, and school admin', icon: FileText, color: 'blue' },
    { path: '/notice-board', label: 'Notice Board', hint: 'School-wide health announcements', icon: Activity, color: 'emerald' },
  ];

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-16">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-card border border-border p-8 rounded-[2rem] shadow-sm">
        <div>
          <div className="flex items-center gap-3 mb-1">
            <div className="p-2 bg-rose-50 dark:bg-rose-950/40 rounded-xl text-rose-600">
              <Stethoscope size={22} />
            </div>
            <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Health Office & Clinic</span>
          </div>
          <h1 className="text-3xl font-black text-text tracking-tight uppercase">Sanatorium Dashboard</h1>
          <p className="text-text-muted text-sm font-medium">Real-time healthcare, sick bay beds, and student medical records.</p>
        </div>

        <Link
          to="/sanatorium"
          className="flex items-center gap-2 px-6 py-3 bg-primary text-white font-bold text-xs rounded-xl hover:bg-primary/90 transition-all shadow-md active:scale-95 cursor-pointer"
        >
          <Plus size={16} /> Open Sanatorium Console
        </Link>
      </div>

      {/* KPI Stats Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        <div className="bg-card border border-border p-6 rounded-[1.75rem] shadow-sm space-y-2">
          <div className="flex justify-between items-start">
            <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Learners Index</span>
            <div className="p-2 bg-blue-50 dark:bg-blue-950/30 text-blue-600 rounded-xl">
              <HeartPulse size={20} />
            </div>
          </div>
          <h3 className="text-2xl font-black text-text">{stats.totalStudents}</h3>
          <p className="text-xs text-text-muted">Registered student profiles</p>
        </div>

        <div className="bg-card border border-border p-6 rounded-[1.75rem] shadow-sm space-y-2">
          <div className="flex justify-between items-start">
            <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Daily Clinic Encounters</span>
            <div className="p-2 bg-rose-50 dark:bg-rose-950/30 text-rose-600 rounded-xl">
              <Activity size={20} />
            </div>
          </div>
          <h3 className="text-2xl font-black text-text">{stats.activeVisits}</h3>
          <p className="text-xs text-text-muted">Recent walk-in visits</p>
        </div>

        <div className="bg-card border border-border p-6 rounded-[1.75rem] shadow-sm space-y-2">
          <div className="flex justify-between items-start">
            <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Sick Bay Beds</span>
            <div className="p-2 bg-purple-50 dark:bg-purple-950/30 text-purple-600 rounded-xl">
              <Bed size={20} />
            </div>
          </div>
          <h3 className="text-2xl font-black text-text">{stats.occupiedBeds} / 6</h3>
          <p className="text-xs text-text-muted">Active bed occupancy</p>
        </div>

        <div className="bg-card border border-border p-6 rounded-[1.75rem] shadow-sm space-y-2">
          <div className="flex justify-between items-start">
            <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Kitchen Allergy Alerts</span>
            <div className="p-2 bg-amber-50 dark:bg-amber-950/30 text-amber-600 rounded-xl">
              <UtensilsCrossed size={20} />
            </div>
          </div>
          <h3 className="text-2xl font-black text-text">{stats.allergyAlerts}</h3>
          <p className="text-xs text-text-muted">Flagged dietary alerts</p>
        </div>
      </div>

      {/* Navigation Quick Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {cards.map((card) => {
          const Icon = card.icon;
          return (
            <Link
              key={card.path}
              to={card.path}
              className="bg-card border border-border rounded-[1.75rem] p-6 hover:shadow-md transition-all group space-y-3 flex flex-col justify-between"
            >
              <div>
                <div className="p-3 bg-primary/10 text-primary rounded-xl w-fit mb-3 group-hover:scale-110 transition-transform">
                  <Icon size={24} />
                </div>
                <h3 className="text-lg font-black text-text tracking-tight">{card.label}</h3>
                <p className="text-xs font-medium text-text-muted mt-1 leading-relaxed">{card.hint}</p>
              </div>
              <div className="flex items-center text-xs font-bold text-primary gap-1 pt-2">
                <span>Access Console</span>
                <ArrowRight size={14} className="group-hover:translate-x-1 transition-transform" />
              </div>
            </Link>
          );
        })}
      </div>
    </div>
  );
}
