import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../../store/auth';
import api from '../../store/api';
import { GradeBadge } from '../../components/GradeBadge';
import {
  Users, DollarSign, MessageSquare, Calendar,
  Bell, Eye, ArrowRight, ChevronRight,
  Heart, CreditCard, Mail, Info
} from 'lucide-react';

export default function ParentDashboard() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    api.get('/dashboard/parent')
      .then(res => setData(res.data))
      .catch(err => {
        console.error('Failed to load parent dashboard:', err);
        setError(err?.response?.data?.error || 'Failed to load dashboard');
      })
      .finally(() => setLoading(false));
  }, []);

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

  if (error || !data) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
      <p className="text-text-muted font-medium">Unable to load dashboard data.</p>
      <p className="text-sm text-text-muted">{error}</p>
      <button onClick={() => window.location.reload()} className="px-4 py-2 bg-primary text-white rounded-xl">Retry</button>
    </div>
  );

  const children = data.children || [];
  const fees = data.feesSummary || { pending: 0, paid: 0, total: 0 };
  const messages = data.messages || [];
  const upcomingEvents = data.upcomingEvents || [];

  const stats = [
    { label: 'Children Enrolled', value: children.length, icon: Heart, color: 'blue' },
    { label: 'Total Invoiced', value: `$${fees.total.toLocaleString()}`, icon: CreditCard, color: 'orange' },
    { label: 'Payment Due', value: `$${fees.pending.toLocaleString()}`, icon: Bell, color: 'red' },
    { label: 'School Messages', value: messages.length, icon: Mail, color: 'purple' },
  ];

  const actionRoutes: Record<string, string> = {
    'Attendance': '/attendance',
    'Pay Fees': '/fees',
    'Message School': '/messages',
    'View Schedule': '/calendar',
  };

  const actionDefs = [
    { label: 'Attendance', icon: Calendar, color: 'bg-white/10' },
    { label: 'Pay Fees', icon: CreditCard, color: 'bg-accent text-[#002147]' },
    { label: 'Message School', icon: MessageSquare, color: 'bg-white/10' },
    { label: 'View Schedule', icon: Eye, color: 'bg-white/10' },
  ];

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-10">
      {/* Header Section */}
      <div>
        <h1 className="text-3xl font-extrabold text-text tracking-tight text-center lg:text-left">Welcome, {user?.first_name}!</h1>
        <p className="text-text-muted mt-1 text-lg font-medium text-center lg:text-left">Monitor your children's progress and manage school obligations.</p>
      </div>

      {/* Stats Bento Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center border group-hover:scale-110 transition-transform
              ${stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-900/30' :
                stat.color === 'orange' ? 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-900/30' :
                stat.color === 'red' ? 'bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 border-red-100 dark:border-red-900/30' :
                'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-900/30'}`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <p className="text-2xl font-black text-text">{stat.value}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Main Content Layout */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">

        {/* Children Progress (Left, 7/12) */}
        <div className="lg:col-span-7 space-y-6">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-black text-text uppercase tracking-tight">Student Overview</h3>
            <button onClick={() => navigate('/academic-progress')} className="text-primary text-[0.7rem] font-bold hover:underline flex items-center gap-1">
              View Detailed Reports <ArrowRight size={14} />
            </button>
          </div>

          <div className="space-y-4">
            {children.length > 0 ? children.map((child: any, i: number) => (
              <div key={child.id} className="bg-card border border-border rounded-3xl p-6 hover:border-primary transition-all shadow-sm group">
                <div className="flex flex-col sm:flex-row items-center gap-6">
                  <div className="w-20 h-20 rounded-2xl bg-muted border border-border flex items-center justify-center text-2xl font-black text-primary shadow-inner shrink-0 group-hover:scale-105 transition-transform">
                    {(child.first_name?.[0] || '?')}{(child.last_name?.[0] || '?')}
                  </div>
                  <div className="flex-1 text-center sm:text-left min-w-0">
                    <h4 className="text-xl font-bold text-text truncate">{child.full_name}</h4>
                    <p className="text-[0.65rem] text-text-muted font-black uppercase tracking-[2px] mt-1">
                      {child.className || 'Not enrolled'} • #EDU-{child.id}
                    </p>

                    <div className="mt-4 flex flex-wrap justify-center sm:justify-start gap-4">
                      <div className="px-3 py-1.5 bg-emerald-50 dark:bg-emerald-900/20 rounded-xl border border-emerald-100 dark:border-emerald-900/30">
                        <p className="text-[0.55rem] font-black text-emerald-600 dark:text-emerald-400 uppercase tracking-widest">Attendance</p>
                        <p className="text-sm font-black text-emerald-700 dark:text-emerald-300">{child.attendancePercent}%</p>
                      </div>
                      <div className="px-3 py-1.5 bg-blue-50 dark:bg-blue-900/20 rounded-xl border border-blue-100 dark:border-blue-900/30">
                        <p className="text-[0.55rem] font-black text-blue-600 dark:text-blue-400 uppercase tracking-widest">Average</p>
                        <div className="mt-1">
                          <GradeBadge
                            percentage={parseFloat(child.averageGrade) || 0}
                            gradingScale={(child as any).grading_scale ?? null}
                            band={(child as any).resolved_scale ? {
                              letter: child.letterGrade,
                              scale: { key: (child as any).resolved_scale, label: '' },
                            } : null}
                            size="sm"
                          />
                        </div>
                      </div>
                      <div className="px-3 py-1.5 bg-orange-50 dark:bg-orange-900/20 rounded-xl border border-orange-100 dark:border-orange-900/30">
                        <p className="text-[0.55rem] font-black text-orange-600 dark:text-orange-400 uppercase tracking-widest">Status</p>
                        <p className="text-sm font-black text-orange-700 dark:text-orange-300">
                          {child.averageGrade >= 60 ? 'On Track' : 'Needs Support'}
                        </p>
                      </div>
                    </div>
                  </div>
                  <button onClick={() => navigate('/academic-progress')} className="shrink-0 w-12 h-12 rounded-2xl bg-primary text-white flex items-center justify-center hover:bg-black transition-colors shadow-lg shadow-blue-900/10">
                    <ChevronRight size={24} />
                  </button>
                </div>
              </div>
            )) : (
              <div className="py-20 text-center bg-card border border-dashed border-border rounded-3xl">
                <Users size={48} className="mx-auto text-text-muted/30 mb-4" />
                <p className="text-text-muted font-bold uppercase tracking-widest text-xs">No children records linked to this account</p>
              </div>
            )}
          </div>

          {/* Upcoming Events */}
          {upcomingEvents.length > 0 && (
            <div className="pt-4">
              <h3 className="text-lg font-black text-text uppercase tracking-tight mb-4">Upcoming Events</h3>
              <div className="space-y-2">
                {upcomingEvents.map((e: any) => (
                  <div key={e.id} onClick={() => navigate('/calendar')} className="bg-card border border-border p-4 rounded-2xl flex items-center justify-between hover:border-primary transition-all cursor-pointer group">
                    <div>
                      <p className="font-bold text-text text-sm">{e.title}</p>
                      <p className="text-[0.7rem] text-text-muted">{e.formattedDate} {e.venue ? `• ${e.venue}` : ''}</p>
                    </div>
                    <span className="px-3 py-1 rounded-full text-[0.6rem] font-black uppercase tracking-tighter whitespace-nowrap border bg-blue-50 text-blue-600 border-blue-100">
                      {e.type}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Right Column (5/12) */}
        <div className="lg:col-span-5 space-y-8">
          {/* Quick Actions */}
          <div className="bg-slate-900 rounded-3xl p-8 text-white shadow-xl shadow-blue-900/10 relative overflow-hidden group">
            <div className="absolute right-[-20px] bottom-[-20px] opacity-10 group-hover:rotate-12 transition-transform duration-700">
              <Info size={160} strokeWidth={1} />
            </div>
            <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-white/40 mb-6 relative z-10">Parent Actions</h3>
            <div className="grid grid-cols-2 gap-3 relative z-10">
              {actionDefs.map((action) => (
                <button key={action.label} onClick={() => navigate(actionRoutes[action.label] || '/dashboard/parent')} className={`flex flex-col items-center justify-center p-5 rounded-2xl transition-all hover:scale-105 active:scale-95 ${action.color}`}>
                  <action.icon size={20} className="mb-2" />
                  <span className="text-[0.65rem] font-bold tracking-tight">{action.label}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Recent Messages */}
          <div className="bg-card border border-border rounded-3xl p-6 shadow-sm">
            <div className="flex justify-between items-center mb-6 px-2">
              <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">School Notices</h3>
              <span className="bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-[0.6rem] font-black px-2.5 py-1 rounded-full border border-red-100 dark:border-red-900/30 uppercase tracking-tighter">
                {messages.length} New
              </span>
            </div>
            <div className="space-y-4">
              {messages.length > 0 ? messages.map((msg: any) => (
                <div key={msg.id} className="p-4 bg-muted/80 rounded-2xl border border-border hover:border-primary transition-all cursor-pointer group">
                  <div className="flex items-center gap-2 mb-2 text-primary">
                    <div className="w-1.5 h-1.5 bg-primary rounded-full"></div>
                    <span className="text-[0.6rem] font-black uppercase tracking-widest leading-none">{msg.sender_role === 'admin' || msg.isAnnouncement ? 'Administration' : (msg.sender || 'Sender')}</span>
                  </div>
                  <h4 className="text-xs font-bold text-text mb-1 line-clamp-1 group-hover:text-primary transition-colors">{msg.subject}</h4>
                  <p className="text-[0.65rem] text-text-muted line-clamp-2 leading-relaxed font-medium mb-2">{msg.body}</p>
                  <p className="text-[0.6rem] text-text-muted font-bold uppercase tracking-tighter">
                    {msg.created_at ? new Date(msg.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : ''}
                  </p>
                </div>
              )) : (
                <p className="text-text-muted text-center py-10 font-bold uppercase tracking-widest text-[0.65rem]">No recent notices</p>
              )}
            </div>
            <button onClick={() => navigate('/messages')} className="w-full mt-6 py-4 px-4 bg-muted hover:bg-muted/80 text-text font-black text-[0.7rem] uppercase tracking-widest rounded-2xl transition-all border border-border">
              Go to Message Center
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
