/**
 * Parent Dashboard (parent) — Phase 3 Recharts + Phase 2 endpoints
 *
 * Per-dependent cards now include:
 *   - Attendance donut (Recharts PieChart)
 *   - Grade progression line chart (recent vs prior 3-month avg)
 *   - Upcoming deadlines list (from fetchParentDeadlines)
 *   - Fee summary (from fetchParentFees)
 *
 * Refactored to be incremental: lazy-fetch per-child details so the main
 * dashboard renders fast, and individual child cards drill into details.
 */

import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  AlertCircle, ShieldX, RefreshCw, Users, CreditCard, Bell, Mail,
  Calendar, TrendingUp, ArrowRight, Info, AlertTriangle, CheckCircle2,
  GraduationCap, FileText, DollarSign,
} from 'lucide-react';
import {
  PieChart, Pie, Cell, ResponsiveContainer, Tooltip,
  BarChart, Bar, XAxis, YAxis, CartesianGrid, ReferenceLine,
} from 'recharts';
import { useDashboardStore } from '../../store/dashboard';

export default function ParentDashboard() {
  const navigate = useNavigate();
  const {
    parent, loading, error, accessDenied, fetchParent,
    parentDeadlinesByChild, fetchParentDeadlines,
    parentFeesByChild, fetchParentFees,
  } = useDashboardStore();

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

  // Lazy-load per-child detail when dashboard mounts
  useEffect(() => {
    const dependents = parent?.per_dependent || [];
    for (const d of dependents) {
      if (!parentDeadlinesByChild[d.student_id]) fetchParentDeadlines(d.student_id);
      if (!parentFeesByChild[d.student_id]) fetchParentFees(d.student_id);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [parent?.per_dependent]);

  if (loading && !parent) {
    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" />
        <p className="text-text-muted font-medium animate-pulse">Loading parent dashboard...</p>
      </div>
    );
  }
  if (accessDenied) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
        <ShieldX size={56} className="text-red-500" />
        <h2 className="text-2xl font-extrabold text-text">Access denied</h2>
        <p className="text-text-muted text-sm max-w-md text-center">
          {error || 'You do not have permission to view the parent dashboard.'}
        </p>
        <button onClick={() => navigate('/dashboard/parent')} className="px-4 py-2 bg-primary text-white rounded-xl hover:opacity-90">Go back</button>
      </div>
    );
  }
  if (error && !parent) {
    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 dashboard data.</p>
        <p className="text-sm text-text-muted">{error}</p>
        <button onClick={() => fetchParent()} className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-xl">
          <RefreshCw size={16} /> Retry
        </button>
      </div>
    );
  }
  if (!parent) return null;

  const dependents = parent.per_dependent || [];
  const children = parent.children || [];
  const messages = parent.messages || [];
  const events = parent.upcomingEvents || [];

  // Empty state: no linked dependents
  if (dependents.length === 0 && children.length === 0) {
    return (
      <div className="space-y-8 animate-in fade-in duration-500 pb-10">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">Parent Dashboard</h1>
          <p className="text-text-muted mt-1 text-lg">Monitor your children&apos;s progress and school obligations.</p>
        </div>
        <div className="bg-card border border-dashed border-border rounded-3xl p-12 text-center">
          <Users size={64} className="mx-auto text-text-muted/40 mb-4" />
          <h2 className="text-2xl font-extrabold text-text mb-2">No dependents linked</h2>
          <p className="text-text-muted text-sm max-w-md mx-auto mb-6">
            Your account is not linked to any student yet. Contact the school administration to add a dependent.
          </p>
          <div className="flex flex-col sm:flex-row gap-3 justify-center">
            <button onClick={() => navigate('/messages')}
              className="px-5 py-3 bg-primary text-white rounded-xl font-bold text-sm hover:opacity-90 transition-all inline-flex items-center justify-center gap-2">
              <Mail size={16} /> Message School to Add Dependent
            </button>
            <button onClick={() => navigate('/academic-progress')}
              className="px-5 py-3 bg-card border border-border text-text rounded-xl font-bold text-sm hover:border-primary hover:text-primary transition-all inline-flex items-center justify-center gap-2">
              <Info size={16} /> Learn More
            </button>
          </div>
        </div>
      </div>
    );
  }

  const totalOutstanding = dependents.reduce((sum, d) => sum + (d.fee_status?.outstanding || 0), 0);
  const flaggedAttendance = dependents.filter((d) => d.attendance_flags?.flag !== 'ok').length;
  const totalUpcoming = dependents.reduce((sum, d) => sum + (d.upcoming_deadlines || 0), 0);

  const kpis = [
    { label: 'Dependents', value: dependents.length, icon: Users, color: 'blue' },
    { label: 'Outstanding', value: `$${totalOutstanding.toLocaleString()}`, icon: DollarSign, color: totalOutstanding > 0 ? 'red' : 'emerald' },
    { label: 'Upcoming (14d)', value: totalUpcoming, icon: FileText, color: totalUpcoming > 0 ? 'orange' : 'emerald' },
    { label: 'Notices', value: messages.length, icon: Mail, color: 'purple' },
  ];

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-10">
      <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">Parent Dashboard</h1>
          <p className="text-text-muted mt-1 text-lg">Monitor your children&apos;s progress and school obligations.</p>
        </div>
        <button onClick={() => fetchParent()} className="flex items-center gap-2 px-4 py-2 bg-card border border-border text-text rounded-xl text-sm font-semibold hover:border-primary hover:text-primary transition-all">
          <RefreshCw size={16} /> Refresh
        </button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {kpis.map((kpi) => (
          <div key={kpi.label} className="bg-card p-5 rounded-2xl border border-border flex items-center gap-4 hover:shadow-md transition-all">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center border ${
              kpi.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'
              : kpi.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'
              : kpi.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30'
              : kpi.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'
              : 'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-900/30'
            }`}>
              <kpi.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{kpi.label}</p>
              <p className="text-2xl font-black text-text">{kpi.value}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Per-dependent cards */}
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-black text-text uppercase tracking-tight">Dependents</h3>
          {flaggedAttendance > 0 && (
            <span className="px-3 py-1 rounded-full bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-[0.6rem] font-black uppercase tracking-widest border border-red-100 dark:border-red-900/30 inline-flex items-center gap-1">
              <AlertTriangle size={12} /> {flaggedAttendance} need attention
            </span>
          )}
        </div>
        <div className="grid grid-cols-1 xl:grid-cols-2 gap-5">
          {dependents.map((dep) => (
            <DependentCard
              key={dep.student_id}
              dep={dep}
              deadlines={parentDeadlinesByChild[dep.student_id] || []}
              fees={parentFeesByChild[dep.student_id] || null}
              onViewReport={() => navigate('/academic-progress')}
            />
          ))}
        </div>
      </div>

      {/* Bottom row: messages + events */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {messages.length > 0 && (
          <div className="bg-card border border-border rounded-2xl p-6">
            <div className="flex justify-between items-center mb-4">
              <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">School Notices</h4>
              <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">
                {messages.length} new
              </span>
            </div>
            <div className="space-y-3 max-h-72 overflow-y-auto">
              {messages.slice(0, 6).map((m) => (
                <div key={m.id} className="p-3 bg-muted/40 rounded-xl border border-border hover:border-primary cursor-pointer transition-all" onClick={() => navigate('/messages')}>
                  <div className="flex items-center gap-2 mb-1 text-primary">
                    <div className="w-1.5 h-1.5 bg-primary rounded-full" />
                    <span className="text-[0.6rem] font-black uppercase tracking-widest leading-none">
                      {m.sender_role === 'admin' || m.isAnnouncement ? 'Administration' : m.sender}
                    </span>
                  </div>
                  <p className="text-xs font-bold text-text line-clamp-1">{m.subject}</p>
                  <p className="text-[0.65rem] text-text-muted line-clamp-2 mt-1">{m.body}</p>
                </div>
              ))}
            </div>
          </div>
        )}

        {events.length > 0 && (
          <div className="bg-card border border-border rounded-2xl p-6">
            <div className="flex justify-between items-center mb-4">
              <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Upcoming Events</h4>
              <button onClick={() => navigate('/calendar')} className="text-primary text-[0.7rem] font-bold hover:underline">View All</button>
            </div>
            <div className="space-y-3">
              {events.slice(0, 5).map((e) => (
                <div key={e.id} className="p-3 bg-muted/40 rounded-xl border border-border hover:border-primary transition-all cursor-pointer flex items-center justify-between gap-3" onClick={() => navigate('/calendar')}>
                  <div className="min-w-0">
                    <p className="text-sm font-bold text-text truncate">{e.title}</p>
                    <p className="text-[0.65rem] text-text-muted">{e.formattedDate} {e.venue ? `• ${e.venue}` : ''}</p>
                  </div>
                  {e.type && (
                    <span className="px-3 py-1 rounded-full text-[0.6rem] font-black uppercase tracking-tighter whitespace-nowrap bg-blue-50 text-blue-600 border border-blue-100 shrink-0">
                      {e.type}
                    </span>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {messages.length === 0 && events.length === 0 && (
          <div className="lg:col-span-2 bg-card border border-dashed border-border rounded-2xl p-8 text-center text-text-muted text-sm">
            No recent notices or upcoming events.
          </div>
        )}
      </div>
    </div>
  );
}

interface DependentCardProps {
  dep: {
    student_id: number;
    name: string;
    upcoming_deadlines: number;
    attendance_flags: { percent: number; total: number; present: number; absent: number; late: number; flag: string };
    fee_status: { outstanding: number; paid_count: number; pending_count: number; total_count: number; flag: string };
    grade_progression: { recent_avg_percent: number | null; prior_avg_percent: number | null; trend: number | null; direction: string };
  };
  deadlines: Array<{ id: number; title: string; due_date: string; days_until_due: number; urgency: string; subject_name: string | null }>;
  fees: { summary: { total_fees: number; total_paid: number; total_outstanding: number; paid_count: number; pending_count: number; overdue_count: number }; items: Array<{ id: number; description: string | null; amount: number; paid_amount: number; status: string; due_date: string | null; paid_percent: number }> } | null;
  onViewReport: () => void;
}

function DependentCard({ dep, deadlines, fees, onViewReport }: DependentCardProps) {
  const attFlagColor = dep.attendance_flags.flag === 'ok'
    ? { ring: 'border-emerald-200 dark:border-emerald-900/30', bg: 'bg-emerald-50 dark:bg-emerald-900/20', text: 'text-emerald-700 dark:text-emerald-300', label: 'On Track' }
    : { ring: 'border-red-200 dark:border-red-900/30', bg: 'bg-red-50 dark:bg-red-900/20', text: 'text-red-700 dark:text-red-300', label: dep.attendance_flags.flag === 'low_attendance' ? 'Low Attendance' : 'Excessive Absences' };
  const feeColor = dep.fee_status.flag === 'clear'
    ? { bg: 'bg-emerald-50 dark:bg-emerald-900/20', text: 'text-emerald-600 dark:text-emerald-400', label: 'Clear' }
    : { bg: 'bg-orange-50 dark:bg-orange-900/20', text: 'text-orange-600 dark:text-orange-400', label: 'Outstanding' };
  const trendIcon = dep.grade_progression.direction === 'improving'
    ? <TrendingUp size={14} className="text-emerald-500" />
    : dep.grade_progression.direction === 'declining'
      ? <TrendingUp size={14} className="text-red-500 rotate-180" />
      : <CheckCircle2 size={14} className="text-blue-500" />;
  const trendLabel = dep.grade_progression.direction === 'improving' ? 'Improving'
    : dep.grade_progression.direction === 'declining' ? 'Declining'
    : dep.grade_progression.direction === 'stable' ? 'Stable'
    : 'No data';

  // Attendance donut
  const attPresent = Math.max(0, dep.attendance_flags.present);
  const attAbsent = Math.max(0, dep.attendance_flags.absent);
  const attLate = Math.max(0, dep.attendance_flags.late);
  const attOther = Math.max(0, dep.attendance_flags.total - attPresent - attAbsent - attLate);
  const attPie = [
    { name: 'Present', value: attPresent, color: '#10b981' },
    { name: 'Absent', value: attAbsent, color: '#ef4444' },
    { name: 'Late', value: attLate, color: '#f59e0b' },
    { name: 'Other', value: attOther, color: '#94a3b8' },
  ].filter((s) => s.value > 0);

  // Grade progression bar chart (prior vs recent)
  const gradeBar = [
    { label: 'Prior', pct: dep.grade_progression.prior_avg_percent ?? 0 },
    { label: 'Recent', pct: dep.grade_progression.recent_avg_percent ?? 0 },
  ];

  return (
    <div className="bg-card border border-border rounded-2xl p-6 hover:shadow-md transition-all">
      <div className="flex items-center gap-3 mb-4">
        <div className="w-12 h-12 rounded-xl bg-primary/10 text-primary flex items-center justify-center font-black text-base shrink-0 border border-primary/20">
          {(dep.name || '??').split(' ').map((s) => s[0]).slice(0, 2).join('').toUpperCase()}
        </div>
        <div className="min-w-0 flex-1">
          <p className="text-base font-extrabold text-text truncate">{dep.name}</p>
          <p className="text-[0.6rem] text-text-muted font-mono">#{dep.student_id}</p>
        </div>
        <span className={`px-2.5 py-1 rounded-full text-[0.6rem] font-black uppercase tracking-widest border ${attFlagColor.bg} ${attFlagColor.text} ${attFlagColor.ring}`}>
          {attFlagColor.label}
        </span>
      </div>

      <div className="grid grid-cols-2 gap-3 mb-3">
        <div className="p-3 bg-muted/40 rounded-xl border border-border">
          <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted">Upcoming Deadlines</p>
          <p className={`text-2xl font-black ${dep.upcoming_deadlines > 0 ? 'text-orange-600 dark:text-orange-400' : 'text-text'}`}>
            {dep.upcoming_deadlines}
          </p>
          <p className="text-[0.6rem] text-text-muted">next 14 days</p>
        </div>

        <div className="p-3 bg-muted/40 rounded-xl border border-border">
          <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted">Attendance (30d)</p>
          <p className={`text-2xl font-black ${
            dep.attendance_flags.percent >= 90 ? 'text-emerald-600 dark:text-emerald-400'
            : dep.attendance_flags.percent >= 75 ? 'text-blue-600 dark:text-blue-400'
            : 'text-red-600 dark:text-red-400'
          }`}>
            {dep.attendance_flags.percent}%
          </p>
          <p className="text-[0.6rem] text-text-muted">{dep.attendance_flags.present}/{dep.attendance_flags.total} present</p>
        </div>

        <div className="p-3 bg-muted/40 rounded-xl border border-border">
          <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted">Fees</p>
          <p className={`text-2xl font-black ${feeColor.text}`}>${dep.fee_status.outstanding.toLocaleString()}</p>
          <p className={`text-[0.6rem] font-black uppercase tracking-wider ${feeColor.text}`}>{feeColor.label}</p>
        </div>

        <div className="p-3 bg-muted/40 rounded-xl border border-border">
          <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted">Grade Trend</p>
          <p className="text-2xl font-black text-text flex items-center gap-2">
            {trendIcon}
            {dep.grade_progression.recent_avg_percent != null ? `${dep.grade_progression.recent_avg_percent}%` : '—'}
          </p>
          <p className="text-[0.6rem] text-text-muted">{trendLabel}</p>
        </div>
      </div>

      {/* Charts row */}
      <div className="grid grid-cols-2 gap-3 mb-3">
        <div className="p-2 bg-muted/30 rounded-xl border border-border">
          <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted text-center mb-1">Attendance Mix</p>
          {attPie.length === 0 ? (
            <div className="text-[0.65rem] text-text-muted text-center py-4">No data</div>
          ) : (
            <div className="h-24 w-full">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie data={attPie} dataKey="value" nameKey="name" innerRadius={22} outerRadius={36} paddingAngle={2}>
                    {attPie.map((s, i) => <Cell key={i} fill={s.color} />)}
                  </Pie>
                  <Tooltip
                    contentStyle={{ backgroundColor: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, color: 'var(--text)', fontSize: 11 }}
                    formatter={(v: number, n: string) => [v, n]}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
          )}
        </div>
        <div className="p-2 bg-muted/30 rounded-xl border border-border">
          <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted text-center mb-1">Grade Trend</p>
          <div className="h-24 w-full">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={gradeBar} margin={{ top: 5, right: 5, left: 0, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="rgba(148,163,184,0.2)" />
                <XAxis dataKey="label" tick={{ fill: 'currentColor', fontSize: 9 }} />
                <YAxis domain={[0, 100]} hide />
                <Tooltip
                  cursor={{ fill: 'currentColor', className: 'text-muted/10' }}
                  contentStyle={{ backgroundColor: 'var(--card)', border: '1px solid var(--border)', borderRadius: 8, color: 'var(--text)', fontSize: 11 }}
                  formatter={(v: number) => [`${v}%`, 'Avg']}
                />
                <ReferenceLine y={50} stroke="#ef4444" strokeDasharray="2 2" />
                <Bar dataKey="pct" radius={[4, 4, 0, 0]}>
                  {gradeBar.map((e, i) => (
                    <Cell key={i} fill={e.pct >= 70 ? '#10b981' : e.pct >= 50 ? '#f59e0b' : e.pct > 0 ? '#ef4444' : '#94a3b8'} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      {/* Upcoming deadlines list (Phase 2 endpoint) */}
      {deadlines.length > 0 && (
        <div className="mt-3 p-3 bg-orange-50/30 dark:bg-orange-950/10 border border-orange-100 dark:border-orange-900/30 rounded-xl">
          <p className="text-[0.55rem] uppercase font-black tracking-widest text-orange-700 dark:text-orange-300 mb-2">
            <FileText size={10} className="inline mr-1" />Next due
          </p>
          <div className="space-y-1">
            {deadlines.slice(0, 3).map((d) => (
              <div key={d.id} className="flex items-center justify-between gap-2 text-xs">
                <span className="font-bold text-text truncate flex-1">{d.title}</span>
                <span className="text-[0.65rem] text-text-muted shrink-0">
                  {d.subject_name && `${d.subject_name} • `}{d.due_date}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Fees summary (Phase 2 endpoint) */}
      {fees && (
        <div className="mt-3 p-3 bg-muted/30 rounded-xl border border-border">
          <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted mb-2">Fee Items</p>
          <div className="grid grid-cols-3 gap-2 text-center">
            <div>
              <p className="text-[0.6rem] text-text-muted">Total</p>
              <p className="text-sm font-black text-text">${fees.summary.total_fees.toLocaleString()}</p>
            </div>
            <div>
              <p className="text-[0.6rem] text-text-muted">Paid</p>
              <p className="text-sm font-black text-emerald-600">${fees.summary.total_paid.toLocaleString()}</p>
            </div>
            <div>
              <p className="text-[0.6rem] text-text-muted">Outstanding</p>
              <p className={`text-sm font-black ${fees.summary.total_outstanding > 0 ? 'text-orange-600' : 'text-text'}`}>
                ${fees.summary.total_outstanding.toLocaleString()}
              </p>
            </div>
          </div>
          {fees.summary.overdue_count > 0 && (
            <p className="mt-2 text-[0.6rem] text-red-600 font-black uppercase">
              <AlertTriangle size={10} className="inline mr-1" />
              {fees.summary.overdue_count} overdue
            </p>
          )}
        </div>
      )}

      <button onClick={onViewReport}
        className="mt-4 w-full py-2.5 px-4 bg-primary/10 hover:bg-primary hover:text-white text-primary rounded-xl text-sm font-bold transition-all inline-flex items-center justify-center gap-2">
        View Full Report <ArrowRight size={14} />
      </button>
    </div>
  );
}