import { useState } from "react";
import { Link } from "@inertiajs/react";
import {
  ArrowLeft, CheckCircle2, Clock, Code2, Shield,
  Building2, GraduationCap, CreditCard, Video, Brain, FileText,
  BarChart3, Monitor, Settings, Rocket, Target,
  ChevronDown, ChevronRight, Zap
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";

type TaskStatus = "done" | "in-progress" | "planned";

interface Task {
  title: string;
  description: string;
  status: TaskStatus;
  effort: string; // e.g. "3 days"
}

interface Milestone {
  title: string;
  description: string;
}

interface MonthPlan {
  month: number;
  label: string;
  theme: string;
  icon: React.ElementType;
  summary: string;
  milestones: Milestone[];
  tasks: Task[];
}

const statusConfig: Record<TaskStatus, { label: string; color: string; icon: React.ElementType }> = {
  done: { label: "Done", color: "bg-emerald-500/20 text-emerald-400 border-emerald-500/30", icon: CheckCircle2 },
  "in-progress": { label: "In Progress", color: "bg-amber-500/20 text-amber-400 border-amber-500/30", icon: Clock },
  planned: { label: "Planned", color: "bg-muted text-muted-foreground border-border", icon: Target },
};

const months: MonthPlan[] = [
  {
    month: 1,
    label: "Month 1",
    theme: "Foundation & Auth",
    icon: Shield,
    summary: "Core infrastructure, authentication system, role-based access control, and database schema design.",
    milestones: [
      { title: "Auth System Live", description: "Email/password signup, login, OTP verification, password reset all functional." },
      { title: "RBAC Implemented", description: "8 roles (sys_admin → delegate) with RLS policies on all tables." },
    ],
    tasks: [
      { title: "Database schema design", description: "Design and deploy all core tables: profiles, user_roles, training_companies, courses, venues, trainers.", status: "done", effort: "5 days" },
      { title: "Authentication system", description: "Email/password auth with Supabase Auth, OTP verification for admin and delegate logins.", status: "done", effort: "4 days" },
      { title: "Role-based access control", description: "Create app_role enum, user_roles table, has_role() and is_sys_role() security definer functions.", status: "done", effort: "3 days" },
      { title: "RLS policies", description: "Row-level security on all tables scoped by role and company_id.", status: "done", effort: "4 days" },
      { title: "Admin layout scaffold", description: "Sidebar navigation, protected routes, role-filtered menu groups.", status: "done", effort: "3 days" },
      { title: "Password reset flow", description: "Reset password page with email link and token-based password update.", status: "done", effort: "2 days" },
    ],
  },
  {
    month: 2,
    label: "Month 2",
    theme: "Course Management",
    icon: GraduationCap,
    summary: "Full course CRUD, categorisation, scheduling, trainer assignment, venue/room allocation, and prerequisites.",
    milestones: [
      { title: "Course Catalogue Live", description: "Public-facing course listing with filtering by category and search." },
      { title: "Admin Course Builder", description: "Multi-step form for creating courses with venue schedules and trainer assignments." },
    ],
    tasks: [
      { title: "Course CRUD admin interface", description: "Create, edit, archive courses with rich form (pricing, content, PPE, certification details).", status: "done", effort: "5 days" },
      { title: "Venue & room management", description: "Venues with nested rooms and yards, capacity tracking, status management.", status: "done", effort: "3 days" },
      { title: "Trainer management", description: "Trainer profiles, course qualifications (course_trainers), company assignments.", status: "done", effort: "3 days" },
      { title: "Course prerequisites", description: "Prerequisite chain management with mandatory/optional flags.", status: "done", effort: "2 days" },
      { title: "Venue-schedule grid", description: "Day-by-day room/yard allocation grid per course with session assignments.", status: "done", effort: "3 days" },
      { title: "Public course pages", description: "Course listing, detail pages with booking CTAs, category navigation.", status: "done", effort: "4 days" },
    ],
  },
  {
    month: 3,
    label: "Month 3",
    theme: "Bookings & Payments",
    icon: CreditCard,
    summary: "Checkout flow, Stripe integration, order management, delegate registration, and waitlist functionality.",
    milestones: [
      { title: "Stripe Payments Live", description: "End-to-end card payment with payment intents and webhook confirmation." },
      { title: "Order Pipeline", description: "Full order lifecycle: pending → confirmed → completed with refund support." },
    ],
    tasks: [
      { title: "Checkout modal & flow", description: "Multi-step checkout with delegate details, payment method selection, and order summary.", status: "done", effort: "5 days" },
      { title: "Stripe integration", description: "Payment intents edge function, webhook handler, refund processing.", status: "done", effort: "5 days" },
      { title: "Order management admin", description: "Orders table with filtering, status badges, invoice generation, QR codes.", status: "done", effort: "4 days" },
      { title: "Booking delegates", description: "Delegate name/email capture per order, linking to course bookings.", status: "done", effort: "2 days" },
      { title: "Waitlist system", description: "Course waitlist with notification tracking when spaces become available.", status: "done", effort: "2 days" },
      { title: "Discount codes", description: "Percentage and fixed-amount codes with scope (global/company), usage limits, date ranges.", status: "done", effort: "2 days" },
    ],
  },
  {
    month: 4,
    label: "Month 4",
    theme: "Company Management",
    icon: Building2,
    summary: "Training and customer company onboarding, credit accounts, delegate management, and company portal foundation.",
    milestones: [
      { title: "Company Portal MVP", description: "Company managers can view delegates, orders, and certificates." },
      { title: "Credit System", description: "Company credit limits, available balance tracking, credit-based ordering." },
    ],
    tasks: [
      { title: "Company CRUD & types", description: "Training vs customer companies, contact details, registration/VAT numbers.", status: "done", effort: "3 days" },
      { title: "Company credit system", description: "Credit limit, available balance, company checkout edge function for credit-based orders.", status: "done", effort: "4 days" },
      { title: "Delegate management", description: "Add/edit/archive delegates per company with email/phone, bulk CSV import.", status: "done", effort: "4 days" },
      { title: "Company portal page", description: "Tabbed portal for company managers: Delegates, Orders, Certificates.", status: "done", effort: "5 days" },
      { title: "Company user invitations", description: "Invite company managers via email, pending role assignments, accept invite flow.", status: "done", effort: "3 days" },
      { title: "Role-aware dashboards", description: "Different dashboard views for sys_admin, company_manager, and training company roles.", status: "done", effort: "3 days" },
    ],
  },
  {
    month: 5,
    label: "Month 5",
    theme: "Certificates & Compliance",
    icon: FileText,
    summary: "Certificate lifecycle, expiry tracking, compliance RAG matrix, and automated notifications.",
    milestones: [
      { title: "Certificate Engine", description: "Issue, track, and expire certificates with automated status management." },
      { title: "Compliance Matrix", description: "RAG-status compliance view across all delegates and required qualifications." },
    ],
    tasks: [
      { title: "Certificate management", description: "Issue certificates with unique numbers, link to courses/orders, set expiry dates.", status: "done", effort: "4 days" },
      { title: "Expiry tracking", description: "Edge function to check certificate expiry, automated notifications for upcoming renewals.", status: "done", effort: "3 days" },
      { title: "Compliance RAG matrix", description: "Cross-reference delegate certificates against job role requirements. Green/Amber/Red status.", status: "done", effort: "5 days" },
      { title: "Job roles & requirements", description: "Define job roles per company with mandatory/optional course requirements.", status: "done", effort: "3 days" },
      { title: "Skills gap analysis", description: "Automated gap detection highlighting missing qualifications and suggesting courses.", status: "done", effort: "4 days" },
      { title: "Certificate wallet", description: "Delegate-facing certificate portfolio with download and share capabilities.", status: "done", effort: "2 days" },
    ],
  },
  {
    month: 6,
    label: "Month 6",
    theme: "AI Services Platform",
    icon: Brain,
    summary: "Company services framework, AI Risk Assessor with live vision, and compliance document generation.",
    milestones: [
      { title: "Services Framework", description: "company_services table with activation, entitlements, and usage logging." },
      { title: "AI Risk Assessor", description: "Live camera-based hazard detection with Gemini 2.5 Flash vision model." },
    ],
    tasks: [
      { title: "Company services table", description: "service_type, status (active/trial/expired), activation dates, config JSON.", status: "done", effort: "2 days" },
      { title: "Service usage logging", description: "Track every AI query/session per company for billing and analytics.", status: "done", effort: "2 days" },
      { title: "Admin services management", description: "Toggle services per company, view usage stats, global services overview page.", status: "done", effort: "3 days" },
      { title: "AI Risk Assessor edge function", description: "analyse-risk-frame: accept base64 JPEG frames, process via Gemini vision, return structured hazards.", status: "done", effort: "5 days" },
      { title: "Live risk assessment UI", description: "Camera capture every 8s, real-time hazard overlay, risk score calculation (severity × likelihood).", status: "done", effort: "5 days" },
      { title: "Compliance document generator", description: "AI-generated RAMS, method statements, toolbox talks customised to company sector.", status: "done", effort: "3 days" },
    ],
  },
  {
    month: 7,
    label: "Month 7",
    theme: "Field Operations & AR",
    icon: Video,
    summary: "AR Remote Assist module, session management, mentor/engineer workflow, and field ops dashboard.",
    milestones: [
      { title: "AR Assist Scaffold", description: "Session lifecycle (requested → active → completed) with KPI dashboard." },
      { title: "Engineer Support Portal", description: "Company engineers can request and track AR assist sessions." },
    ],
    tasks: [
      { title: "AR assist sessions table", description: "Session status workflow, engineer/mentor tracking, duration, recording URLs.", status: "done", effort: "2 days" },
      { title: "Admin AR dashboard", description: "KPI cards (active/total/completed/avg duration), session history table with status badges.", status: "done", effort: "4 days" },
      { title: "Company AR request UI", description: "Engineers request help with engineer name, job reference; track session history.", status: "done", effort: "3 days" },
      { title: "WebRTC signalling scaffold", description: "Edge function for signalling, Realtime channel subscription for peer connection.", status: "planned", effort: "5 days" },
      { title: "Canvas annotation layer", description: "Mentor draws arrows, measurements, highlights on live video feed overlay.", status: "planned", effort: "5 days" },
      { title: "Session recording pipeline", description: "MediaRecorder API to capture sessions, upload to storage bucket, link to session record.", status: "planned", effort: "3 days" },
    ],
  },
  {
    month: 8,
    label: "Month 8",
    theme: "E-Learning & Content",
    icon: Monitor,
    summary: "E-learning module player, enrolment tracking, progress management, and content delivery.",
    milestones: [
      { title: "E-Learning Platform", description: "Course enrolment, progress tracking, completion certificates." },
      { title: "Content Management", description: "Admin interface for managing e-learning course content and modules." },
    ],
    tasks: [
      { title: "E-learning player page", description: "Full-screen course player with module navigation and progress tracking.", status: "done", effort: "5 days" },
      { title: "Enrolment management", description: "Track enrolments with status (enrolled/in_progress/completed), progress percentage.", status: "done", effort: "3 days" },
      { title: "Admin e-learning dashboard", description: "Manage e-learning courses, view enrolment stats, content uploads.", status: "done", effort: "4 days" },
      { title: "VideoTile LMS integration", description: "Catalog browsing in admin, per-delegate provisioning, one-click SSO launch from delegate dashboard, 15-min progress polling against VT's API.", status: "done", effort: "5 days" },
      { title: "Completion certificates", description: "Auto-issue a certificates row when a VideoTile enrolment flips to completed; backfilled for historical completions.", status: "done", effort: "2 days" },
      { title: "Assessment engine", description: "Quiz builder with question banks, pass marks, and retry logic.", status: "planned", effort: "5 days" },
    ],
  },
  {
    month: 9,
    label: "Month 9",
    theme: "White-Label & Multi-Tenancy",
    icon: Settings,
    summary: "Company branding, subdomain routing, white-label portals, and tenant-specific content.",
    milestones: [
      { title: "White-Label Portals", description: "Training companies get branded booking pages with custom colours, logos, and domains." },
      { title: "Tenant Content", description: "Per-company featured courses, testimonials, and blog posts." },
    ],
    tasks: [
      { title: "Company branding panel", description: "Logo, colours, hero image, tagline, contact details, Stripe account configuration.", status: "done", effort: "4 days" },
      { title: "Subdomain routing", description: "TenantContext resolves company from subdomain, applies branding dynamically.", status: "done", effort: "3 days" },
      { title: "Tenant home pages", description: "Branded landing pages with company hero, featured courses, testimonials.", status: "done", effort: "4 days" },
      { title: "Tenant content management", description: "Admin tabs for featured courses, testimonials, blog posts per company.", status: "done", effort: "3 days" },
      { title: "Tenant Stripe Connect", description: "Per-company Stripe keys for direct payment processing on white-label sites.", status: "done", effort: "3 days" },
      { title: "Custom domain support", description: "CNAME mapping and SSL provisioning for custom company domains.", status: "planned", effort: "5 days" },
    ],
  },
  {
    month: 10,
    label: "Month 10",
    theme: "Analytics & Reporting",
    icon: BarChart3,
    summary: "Revenue analytics, training calendar, audit logging, operational dashboards, and CSV exports.",
    milestones: [
      { title: "Revenue Dashboard", description: "Monthly revenue trends, course performance, company spending analytics." },
      { title: "Audit Trail", description: "Complete activity logging with entity tracking and IP addresses." },
    ],
    tasks: [
      { title: "Revenue analytics page", description: "Charts for revenue trends, top courses, company spending, payment method breakdown.", status: "done", effort: "5 days" },
      { title: "Training calendar", description: "Calendar view of all bookings with trainer/venue overlays, conflict detection.", status: "done", effort: "4 days" },
      { title: "Audit log system", description: "activity_log table with entity tracking, action types, IP addresses, user attribution.", status: "done", effort: "3 days" },
      { title: "CSV export utilities", description: "Export orders, delegates, certificates, revenue data as CSV downloads.", status: "done", effort: "2 days" },
      { title: "Trainer availability system", description: "Weekly schedules, date overrides, bank holiday awareness, availability heatmaps.", status: "done", effort: "3 days" },
      { title: "Notification system", description: "In-app notifications with bell icon, read/unread states, entity linking.", status: "done", effort: "3 days" },
    ],
  },
  {
    month: 11,
    label: "Month 11",
    theme: "Onboarding & Forms",
    icon: FileText,
    summary: "Pre-course forms, onboarding workflows, delegate form submissions, digital signatures, and SOP management.",
    milestones: [
      { title: "Digital Forms", description: "TD02, TD07, TD29 forms with signature pads and submission tracking." },
      { title: "Onboarding Pipeline", description: "Automated pre-course form distribution and completion tracking." },
    ],
    tasks: [
      { title: "Onboarding form templates", description: "TD02 (health declaration), TD07 (assessment), TD29 (practical) with field validation.", status: "done", effort: "5 days" },
      { title: "Digital signature pad", description: "Canvas-based signature capture for candidate and assessor signatures.", status: "done", effort: "2 days" },
      { title: "Pre-course form distribution", description: "Edge function to email pre-course forms to delegates before training dates.", status: "done", effort: "3 days" },
      { title: "Form submission tracking", description: "Admin view of all submissions with form type, delegate, course, and completion status.", status: "done", effort: "3 days" },
      { title: "SOP documentation", description: "Standard Operating Procedures page with document management and version control.", status: "done", effort: "3 days" },
      { title: "Email templates", description: "Order confirmation, joining instructions, certificate issuance email templates.", status: "done", effort: "4 days" },
    ],
  },
  {
    month: 12,
    label: "Month 12",
    theme: "Polish, Testing & Launch",
    icon: Rocket,
    summary: "End-to-end testing, performance optimisation, security hardening, documentation, and production deployment.",
    milestones: [
      { title: "Production Ready", description: "All modules tested, documented, and deployed to production." },
      { title: "Client Sign-Off", description: "System requirements documentation with feature-by-feature approval." },
    ],
    tasks: [
      { title: "System requirements documentation", description: "Full specification with BDD tests, Mermaid diagrams, and client sign-off workflow.", status: "done", effort: "5 days" },
      { title: "End-to-end testing", description: "Test all user journeys: booking, payment, certification, company portal, AI tools.", status: "planned", effort: "5 days" },
      { title: "Performance optimisation", description: "Lazy loading, query optimisation, image compression, bundle analysis.", status: "planned", effort: "3 days" },
      { title: "Security audit", description: "RLS policy review, API endpoint hardening, secret rotation, penetration testing.", status: "planned", effort: "4 days" },
      { title: "User acceptance testing", description: "Structured UAT with stakeholders using sign-off documentation.", status: "planned", effort: "4 days" },
      { title: "Production deployment", description: "DNS, SSL, monitoring, error tracking, backup strategy, go-live checklist.", status: "planned", effort: "3 days" },
    ],
  },
];

const getMonthStats = (month: MonthPlan) => {
  const total = month.tasks.length;
  const done = month.tasks.filter(t => t.status === "done").length;
  const inProgress = month.tasks.filter(t => t.status === "in-progress").length;
  return { total, done, inProgress, percent: Math.round((done / total) * 100) };
};

const overallStats = () => {
  const allTasks = months.flatMap(m => m.tasks);
  const total = allTasks.length;
  const done = allTasks.filter(t => t.status === "done").length;
  const inProgress = allTasks.filter(t => t.status === "in-progress").length;
  const planned = allTasks.filter(t => t.status === "planned").length;
  return { total, done, inProgress, planned, percent: Math.round((done / total) * 100) };
};

const ProjectPlanPage = () => {
  const [selectedMonth, setSelectedMonth] = useState(0);
  const [expandedTasks, setExpandedTasks] = useState<Record<string, boolean>>({});
  const stats = overallStats();
  const currentMonth = months[selectedMonth];
  const monthStats = getMonthStats(currentMonth);

  const toggleTask = (key: string) => {
    setExpandedTasks(prev => ({ ...prev, [key]: !prev[key] }));
  };

  return (
    <div className="min-h-screen bg-background text-foreground flex flex-col">
      {/* Header */}
      <header className="border-b border-border bg-card/80 backdrop-blur sticky top-0 z-30">
        <div className="max-w-[1600px] mx-auto px-4 sm:px-6 py-3 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Link href="/">
              <Button variant="ghost" size="icon"><ArrowLeft className="h-4 w-4" /></Button>
            </Link>
            <div>
              <h1 className="text-lg font-bold text-foreground">Project Development Plan</h1>
              <p className="text-xs text-muted-foreground">12-Month Delivery Roadmap</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Link href="/build-programme">
              <Button variant="outline" size="sm" className="text-xs">
                <BarChart3 className="h-3 w-3 mr-1" /> Build Programme
              </Button>
            </Link>
            <Link href="/system-requirements">
              <Button variant="outline" size="sm" className="text-xs">
                <FileText className="h-3 w-3 mr-1" /> System Docs
              </Button>
            </Link>
          </div>
        </div>
      </header>

      <div className="flex-1 flex flex-col lg:flex-row max-w-[1600px] mx-auto w-full">
        {/* Sidebar - Month List */}
        <aside className="w-full lg:w-72 border-b lg:border-b-0 lg:border-r border-border bg-card/50 overflow-x-auto lg:overflow-x-visible">
          <div className="p-4">
            <div className="mb-4">
              <div className="flex items-center justify-between text-xs text-muted-foreground mb-1">
                <span>Overall Progress</span>
                <span className="font-medium text-foreground">{stats.percent}%</span>
              </div>
              <Progress value={stats.percent} className="h-2" />
              <div className="flex gap-3 mt-2 text-xs text-muted-foreground">
                <span className="flex items-center gap-1"><CheckCircle2 className="h-3 w-3 text-emerald-400" />{stats.done}</span>
                <span className="flex items-center gap-1"><Clock className="h-3 w-3 text-amber-400" />{stats.inProgress}</span>
                <span className="flex items-center gap-1"><Target className="h-3 w-3 text-muted-foreground" />{stats.planned}</span>
              </div>
            </div>
          </div>
          <ScrollArea className="lg:h-[calc(100vh-180px)]">
            <div className="flex lg:flex-col gap-1 px-4 pb-4 overflow-x-auto lg:overflow-x-visible">
              {months.map((m, i) => {
                const ms = getMonthStats(m);
                const Icon = m.icon;
                return (
                  <button
                    key={m.month}
                    onClick={() => setSelectedMonth(i)}
                    className={cn(
                      "flex items-center gap-3 w-full min-w-[200px] lg:min-w-0 text-left px-3 py-2.5 rounded-lg transition-all text-sm",
                      selectedMonth === i
                        ? "bg-primary/10 border border-primary/30 text-primary"
                        : "hover:bg-muted/50 text-muted-foreground border border-transparent"
                    )}
                  >
                    <Icon className="h-4 w-4 shrink-0" />
                    <div className="flex-1 min-w-0">
                      <div className="font-medium text-xs">{m.label}</div>
                      <div className="text-xs truncate opacity-70">{m.theme}</div>
                    </div>
                    <div className="text-xs font-mono shrink-0">
                      {ms.percent}%
                    </div>
                  </button>
                );
              })}
            </div>
          </ScrollArea>
        </aside>

        {/* Main Content */}
        <main className="flex-1 overflow-auto">
          <ScrollArea className="h-[calc(100vh-64px)]">
            <div className="p-4 sm:p-6 lg:p-8 space-y-6">
              {/* Month Header */}
              <div className="flex flex-col sm:flex-row sm:items-start gap-4">
                <div className="h-12 w-12 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center shrink-0">
                  <currentMonth.icon className="h-6 w-6 text-primary" />
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <h2 className="text-xl font-bold text-foreground">{currentMonth.label}: {currentMonth.theme}</h2>
                  </div>
                  <p className="text-sm text-muted-foreground">{currentMonth.summary}</p>
                  <div className="flex items-center gap-2 mt-3">
                    <Progress value={monthStats.percent} className="h-2 flex-1 max-w-xs" />
                    <span className="text-xs font-medium text-foreground">{monthStats.done}/{monthStats.total} tasks</span>
                  </div>
                </div>
              </div>

              {/* Milestones */}
              <div className="grid sm:grid-cols-2 gap-3">
                {currentMonth.milestones.map((ms, i) => (
                  <Card key={i} className="bg-primary/5 border-primary/20">
                    <CardContent className="p-4">
                      <div className="flex items-start gap-3">
                        <Zap className="h-4 w-4 text-primary mt-0.5 shrink-0" />
                        <div>
                          <h4 className="text-sm font-semibold text-foreground">{ms.title}</h4>
                          <p className="text-xs text-muted-foreground mt-0.5">{ms.description}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>

              {/* Tasks */}
              <div>
                <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                  <Code2 className="h-4 w-4 text-primary" /> Deliverables
                </h3>
                <div className="space-y-2">
                  {currentMonth.tasks.map((task, i) => {
                    const key = `${currentMonth.month}-${i}`;
                    const expanded = expandedTasks[key];
                    const sc = statusConfig[task.status];
                    const StatusIcon = sc.icon;
                    return (
                      <Card key={i} className="bg-card border-border hover:border-border/80 transition-colors">
                        <button
                          onClick={() => toggleTask(key)}
                          className="w-full text-left p-4 flex items-center gap-3"
                        >
                          {expanded ? <ChevronDown className="h-4 w-4 text-muted-foreground shrink-0" /> : <ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />}
                          <StatusIcon className={cn("h-4 w-4 shrink-0", task.status === "done" ? "text-emerald-400" : task.status === "in-progress" ? "text-amber-400" : "text-muted-foreground")} />
                          <span className="flex-1 text-sm font-medium text-foreground">{task.title}</span>
                          <Badge variant="outline" className={cn("text-xs", sc.color)}>{sc.label}</Badge>
                          <span className="text-xs text-muted-foreground font-mono hidden sm:inline">{task.effort}</span>
                        </button>
                        {expanded && (
                          <div className="px-4 pb-4 pl-14">
                            <p className="text-sm text-muted-foreground">{task.description}</p>
                          </div>
                        )}
                      </Card>
                    );
                  })}
                </div>
              </div>

              {/* Overall Summary (only on month 12) */}
              {selectedMonth === 11 && (
                <Card className="border-primary/20 bg-primary/5">
                  <CardHeader>
                    <CardTitle className="text-base flex items-center gap-2">
                      <Rocket className="h-5 w-5 text-primary" /> Project Summary
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 text-center">
                      <div>
                        <div className="text-2xl font-bold text-foreground">{stats.total}</div>
                        <div className="text-xs text-muted-foreground">Total Tasks</div>
                      </div>
                      <div>
                        <div className="text-2xl font-bold text-emerald-400">{stats.done}</div>
                        <div className="text-xs text-muted-foreground">Completed</div>
                      </div>
                      <div>
                        <div className="text-2xl font-bold text-amber-400">{stats.inProgress}</div>
                        <div className="text-xs text-muted-foreground">In Progress</div>
                      </div>
                      <div>
                        <div className="text-2xl font-bold text-muted-foreground">{stats.planned}</div>
                        <div className="text-xs text-muted-foreground">Planned</div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>
          </ScrollArea>
        </main>
      </div>
    </div>
  );
};

export default ProjectPlanPage;
