"use client";

import { useEffect, useState } from "react";
import {
  AlertTriangle,
  BarChart3,
  CheckCircle2,
  Clock,
  FolderKanban,
  Target,
  TrendingUp,
} from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { Skeleton } from "@/components/ui/skeleton";
import { useWorkspaceStore } from "@/stores/workspace-store";
import { formatRelativeDate } from "@/lib/utils";

interface Stats {
  totalTasks: number;
  completedTasks: number;
  openTasks: number;
  totalNotes: number;
  totalProjects: number;
  totalEvents: number;
  totalGoals: number;
  completedGoals: number;
  alignedProjects: number;
  alignedTasks: number;
  atRiskProjects: number;
  stuckProjects: number;
}

interface RiskProject {
  id: string;
  name: string;
  icon: string;
  health: "at_risk" | "stuck";
  updated_at: string;
}

export default function AnalyticsPage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [riskProjects, setRiskProjects] = useState<RiskProject[]>([]);
  const [loading, setLoading] = useState(true);
  const supabase = createClient();
  const activeTeamId = useWorkspaceStore((state) => state.activeTeamId);
  const initialized = useWorkspaceStore((state) => state.initialized);

  useEffect(() => {
    async function fetchStats() {
      if (!initialized) return;

      setLoading(true);

      const tasksQuery = activeTeamId
        ? supabase
            .from("tasks")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
            .is("parent_task_id", null)
        : supabase
            .from("tasks")
            .select("id", { count: "exact", head: true })
            .is("team_id", null)
            .is("parent_task_id", null);

      const completedQuery = activeTeamId
        ? supabase
            .from("tasks")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
            .eq("status", "done")
            .is("parent_task_id", null)
        : supabase
            .from("tasks")
            .select("id", { count: "exact", head: true })
            .is("team_id", null)
            .eq("status", "done")
            .is("parent_task_id", null);

      const notesQuery = activeTeamId
        ? supabase
            .from("notes")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
        : supabase
            .from("notes")
            .select("id", { count: "exact", head: true })
            .is("team_id", null);

      const projectsQuery = activeTeamId
        ? supabase
            .from("projects")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
        : supabase
            .from("projects")
            .select("id", { count: "exact", head: true })
            .is("team_id", null);

      const eventsQuery = activeTeamId
        ? supabase
            .from("events")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
        : supabase
            .from("events")
            .select("id", { count: "exact", head: true })
            .is("team_id", null);

      const goalsQuery = activeTeamId
        ? supabase
            .from("goals")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
        : supabase
            .from("goals")
            .select("id", { count: "exact", head: true })
            .is("team_id", null);

      const completedGoalsQuery = activeTeamId
        ? supabase
            .from("goals")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
            .eq("completed", true)
        : supabase
            .from("goals")
            .select("id", { count: "exact", head: true })
            .is("team_id", null)
            .eq("completed", true);

      const alignedProjectsQuery = activeTeamId
        ? supabase
            .from("projects")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
            .not("goal_id", "is", null)
        : supabase
            .from("projects")
            .select("id", { count: "exact", head: true })
            .is("team_id", null)
            .not("goal_id", "is", null);

      const alignedTasksQuery = activeTeamId
        ? supabase
            .from("tasks")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
            .is("parent_task_id", null)
            .not("goal_id", "is", null)
        : supabase
            .from("tasks")
            .select("id", { count: "exact", head: true })
            .is("team_id", null)
            .is("parent_task_id", null)
            .not("goal_id", "is", null);

      const atRiskProjectsQuery = activeTeamId
        ? supabase
            .from("projects")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
            .eq("health", "at_risk")
        : supabase
            .from("projects")
            .select("id", { count: "exact", head: true })
            .is("team_id", null)
            .eq("health", "at_risk");

      const stuckProjectsQuery = activeTeamId
        ? supabase
            .from("projects")
            .select("id", { count: "exact", head: true })
            .eq("team_id", activeTeamId)
            .eq("health", "stuck")
        : supabase
            .from("projects")
            .select("id", { count: "exact", head: true })
            .is("team_id", null)
            .eq("health", "stuck");

      const riskProjectsQuery = activeTeamId
        ? supabase
            .from("projects")
            .select("id, name, icon, health, updated_at")
            .eq("team_id", activeTeamId)
            .in("health", ["at_risk", "stuck"])
            .order("updated_at", { ascending: false })
            .limit(6)
        : supabase
            .from("projects")
            .select("id, name, icon, health, updated_at")
            .is("team_id", null)
            .in("health", ["at_risk", "stuck"])
            .order("updated_at", { ascending: false })
            .limit(6);

      const [
        tasksRes,
        completedRes,
        notesRes,
        projectsRes,
        eventsRes,
        goalsRes,
        completedGoalsRes,
        alignedProjectsRes,
        alignedTasksRes,
        atRiskProjectsRes,
        stuckProjectsRes,
        riskProjectsRes,
      ] = await Promise.all([
        tasksQuery,
        completedQuery,
        notesQuery,
        projectsQuery,
        eventsQuery,
        goalsQuery,
        completedGoalsQuery,
        alignedProjectsQuery,
        alignedTasksQuery,
        atRiskProjectsQuery,
        stuckProjectsQuery,
        riskProjectsQuery,
      ]);

      const totalTasks = tasksRes.count || 0;
      const completedTasks = completedRes.count || 0;

      setStats({
        totalTasks,
        completedTasks,
        openTasks: totalTasks - completedTasks,
        totalNotes: notesRes.count || 0,
        totalProjects: projectsRes.count || 0,
        totalEvents: eventsRes.count || 0,
        totalGoals: goalsRes.count || 0,
        completedGoals: completedGoalsRes.count || 0,
        alignedProjects: alignedProjectsRes.count || 0,
        alignedTasks: alignedTasksRes.count || 0,
        atRiskProjects: atRiskProjectsRes.count || 0,
        stuckProjects: stuckProjectsRes.count || 0,
      });
      setRiskProjects((riskProjectsRes.data || []) as RiskProject[]);
      setLoading(false);
    }

    void fetchStats();
  }, [activeTeamId, initialized, supabase]);

  if (loading) {
    return (
      <div>
        <div className="flex items-center gap-3 mb-6">
          <BarChart3 className="h-5 w-5 text-muted-foreground" />
          <h1 className="text-2xl font-bold tracking-tight">Analytics</h1>
        </div>
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
          {Array.from({ length: 8 }).map((_, i) => (
            <Skeleton key={i} className="h-28 rounded-xl" />
          ))}
        </div>
      </div>
    );
  }

  const completionRate =
    stats && stats.totalTasks > 0
      ? Math.round((stats.completedTasks / stats.totalTasks) * 100)
      : 0;
  const goalCompletionRate =
    stats && stats.totalGoals > 0
      ? Math.round((stats.completedGoals / stats.totalGoals) * 100)
      : 0;
  const activeGoals = Math.max(
    0,
    (stats?.totalGoals || 0) - (stats?.completedGoals || 0)
  );

  const statCards = [
    { label: "Total tasks", value: stats?.totalTasks || 0, icon: Target, color: "text-blue-500" },
    { label: "Completed", value: stats?.completedTasks || 0, icon: CheckCircle2, color: "text-green-500" },
    { label: "Open", value: stats?.openTasks || 0, icon: Clock, color: "text-orange-500" },
    { label: "Task completion", value: `${completionRate}%`, icon: TrendingUp, color: "text-purple-500" },
    { label: "Goals", value: stats?.totalGoals || 0, icon: Target, color: "text-rose-500" },
    { label: "Active goals", value: activeGoals, icon: Target, color: "text-pink-500" },
    { label: "Aligned projects", value: stats?.alignedProjects || 0, icon: FolderKanban, color: "text-indigo-500" },
    { label: "Aligned tasks", value: stats?.alignedTasks || 0, icon: FolderKanban, color: "text-cyan-500" },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <BarChart3 className="h-5 w-5 text-muted-foreground" />
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Analytics</h1>
          <p className="text-sm text-muted-foreground">
            Track execution, goal alignment, and project health across the current workspace.
          </p>
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {statCards.map((card) => (
          <div
            key={card.label}
            className="rounded-xl border border-border bg-card p-5"
          >
            <div className="flex items-center gap-2 mb-3">
              <card.icon className={`h-4 w-4 ${card.color}`} />
              <span className="text-xs font-medium text-muted-foreground">
                {card.label}
              </span>
            </div>
            <p className="text-3xl font-bold">{card.value}</p>
          </div>
        ))}
      </div>

      <div className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
        <div className="rounded-2xl border border-border bg-card p-5">
          <div className="flex items-center gap-2">
            <Target className="h-4 w-4 text-rose-500" />
            <h2 className="text-sm font-semibold">Goal alignment</h2>
          </div>
          <p className="mt-1 text-sm text-muted-foreground">
            See how much of the workspace is anchored to explicit goals.
          </p>

          <div className="mt-5 grid gap-4 sm:grid-cols-2">
            <div className="rounded-xl border border-border/70 bg-muted/20 p-4">
              <p className="text-xs uppercase tracking-[0.16em] text-muted-foreground">
                Goal completion
              </p>
              <p className="mt-2 text-3xl font-bold">{goalCompletionRate}%</p>
              <p className="mt-2 text-sm text-muted-foreground">
                {stats?.completedGoals || 0} of {stats?.totalGoals || 0} goals completed.
              </p>
            </div>
            <div className="rounded-xl border border-border/70 bg-muted/20 p-4">
              <p className="text-xs uppercase tracking-[0.16em] text-muted-foreground">
                Workspace alignment
              </p>
              <p className="mt-2 text-3xl font-bold">
                {stats?.totalProjects
                  ? Math.round(((stats?.alignedProjects || 0) / stats.totalProjects) * 100)
                  : 0}
                %
              </p>
              <p className="mt-2 text-sm text-muted-foreground">
                {(stats?.alignedProjects || 0)} of {(stats?.totalProjects || 0)} projects are linked to a goal.
              </p>
            </div>
          </div>

          <div className="mt-5 grid gap-3 sm:grid-cols-3">
            <div className="rounded-xl border border-border/70 p-4">
              <p className="text-xs text-muted-foreground">Notes</p>
              <p className="mt-2 text-2xl font-semibold">{stats?.totalNotes || 0}</p>
            </div>
            <div className="rounded-xl border border-border/70 p-4">
              <p className="text-xs text-muted-foreground">Projects</p>
              <p className="mt-2 text-2xl font-semibold">{stats?.totalProjects || 0}</p>
            </div>
            <div className="rounded-xl border border-border/70 p-4">
              <p className="text-xs text-muted-foreground">Events</p>
              <p className="mt-2 text-2xl font-semibold">{stats?.totalEvents || 0}</p>
            </div>
          </div>
        </div>

        <div className="rounded-2xl border border-border bg-card p-5">
          <div className="flex items-center gap-2">
            <AlertTriangle className="h-4 w-4 text-amber-500" />
            <h2 className="text-sm font-semibold">Project health</h2>
          </div>
          <p className="mt-1 text-sm text-muted-foreground">
            Surface where the workspace may need attention next.
          </p>

          <div className="mt-5 grid gap-3 sm:grid-cols-2">
            <div className="rounded-xl border border-amber-500/20 bg-amber-500/10 p-4">
              <p className="text-xs uppercase tracking-[0.16em] text-amber-700 dark:text-amber-300">
                At risk
              </p>
              <p className="mt-2 text-3xl font-bold">{stats?.atRiskProjects || 0}</p>
            </div>
            <div className="rounded-xl border border-red-500/20 bg-red-500/10 p-4">
              <p className="text-xs uppercase tracking-[0.16em] text-red-700 dark:text-red-300">
                Stuck
              </p>
              <p className="mt-2 text-3xl font-bold">{stats?.stuckProjects || 0}</p>
            </div>
          </div>

          <div className="mt-5 space-y-2">
            {riskProjects.length === 0 ? (
              <div className="rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground">
                No risky projects right now. The current workspace looks healthy.
              </div>
            ) : (
              riskProjects.map((project) => (
                <div
                  key={project.id}
                  className="flex items-center justify-between gap-3 rounded-xl border border-border/70 p-3"
                >
                  <div className="min-w-0">
                    <p className="truncate text-sm font-medium">
                      {project.icon} {project.name}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      Updated {formatRelativeDate(project.updated_at)}
                    </p>
                  </div>
                  <span
                    className={
                      project.health === "stuck"
                        ? "rounded-full border border-red-500/20 bg-red-500/10 px-2.5 py-1 text-xs font-medium text-red-600 dark:text-red-300"
                        : "rounded-full border border-amber-500/20 bg-amber-500/10 px-2.5 py-1 text-xs font-medium text-amber-600 dark:text-amber-300"
                    }
                  >
                    {project.health === "stuck" ? "Stuck" : "At risk"}
                  </span>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
