import Link from "next/link";
import { ArrowUpRight } from "lucide-react";
import { requireUser } from "@/lib/auth/session";
import { createClient } from "@/lib/supabase/server";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { LEAD_STATUSES, LEAD_STATUS_STYLES } from "@/lib/leads/constants";
import {
  APPLICATION_STATUSES,
  APPLICATION_STATUS_STYLES,
} from "@/lib/applications/constants";
import type { LeadStatus } from "@/lib/types";

type TodayFollowup = {
  id: string;
  lead_id: string;
  from_time: string | null;
  lead: { id: string; full_name: string; phone: string | null } | null;
};

export default async function DashboardPage() {
  const user = await requireUser();
  const supabase = await createClient();
  const today = new Date().toISOString().slice(0, 10);

  // Count helper bound to the leads table.
  const leadCount = (status?: LeadStatus) => {
    let query = supabase
      .from("leads")
      .select("*", { count: "exact", head: true });
    if (status) query = query.eq("lead_status", status);
    return query;
  };

  // Count helper bound to the student_applications table.
  const appCount = (status?: string) => {
    let query = supabase
      .from("student_applications")
      .select("*", { count: "exact", head: true });
    if (status) query = query.eq("status", status);
    return query;
  };

  const [
    branchRes,
    userRes,
    totalLeadsRes,
    newLeadsRes,
    todayFollowupsCountRes,
    statusBreakdownRes,
    todayFollowupsRes,
    totalAppsRes,
    visaApprovedRes,
    travelledRes,
    offersFlagRes,
    coachingRes,
    loanRes,
    feesRes,
    appStatusBreakdownRes,
  ] = await Promise.all([
    supabase.from("branches").select("*", { count: "exact", head: true }),
    supabase.from("users").select("*", { count: "exact", head: true }),
    leadCount(),
    leadCount("New"),
    supabase
      .from("followups")
      .select("*", { count: "exact", head: true })
      .eq("next_date", today)
      .eq("status", "pending"),
    Promise.all(
      LEAD_STATUSES.map(async (status) => {
        const { count } = await leadCount(status);
        return [status, count ?? 0] as const;
      }),
    ),
    supabase
      .from("followups")
      .select("id, lead_id, from_time, lead:leads(id, full_name, phone)")
      .eq("next_date", today)
      .eq("status", "pending")
      .order("from_time"),
    appCount(),
    // "Visa Approved" KPI counts approvals and those who have already travelled.
    supabase
      .from("student_applications")
      .select("*", { count: "exact", head: true })
      .in("status", ["Visa Approved", "Travelled"]),
    appCount("Travelled"),
    // Offers: explicit flag OR any status at/past the offer stage.
    supabase
      .from("student_applications")
      .select("*", { count: "exact", head: true })
      .or(
        "offer_received.eq.true,status.in.(Offer Received,Visa Applied,Visa Approved,Visa Rejected,Travelled)",
      ),
    supabase
      .from("coaching_applications")
      .select("*", { count: "exact", head: true }),
    supabase
      .from("education_loan_inquiries")
      .select("*", { count: "exact", head: true }),
    supabase.from("fee_payments").select("amount"),
    Promise.all(
      APPLICATION_STATUSES.map(async (status) => {
        const { count } = await appCount(status);
        return [status, count ?? 0] as const;
      }),
    ),
  ]);

  const branchCount = branchRes.count ?? 0;
  const userCount = userRes.count ?? 0;
  const totalLeads = totalLeadsRes.count ?? 0;
  const newLeads = newLeadsRes.count ?? 0;
  const todayFollowupsCount = todayFollowupsCountRes.count ?? 0;
  const statusBreakdown = statusBreakdownRes;
  const todayFollowups = (todayFollowupsRes.data ?? []) as unknown as TodayFollowup[];

  const totalApps = totalAppsRes.count ?? 0;
  const visaApproved = visaApprovedRes.count ?? 0;
  const travelled = travelledRes.count ?? 0;
  const offers = offersFlagRes.count ?? 0;
  const coachingStudents = coachingRes.count ?? 0;
  const loanInquiries = loanRes.count ?? 0;
  const appStatusBreakdown = appStatusBreakdownRes;

  const totalFees = (feesRes.data ?? []).reduce(
    (sum, row) => sum + (Number((row as { amount: number | null }).amount) || 0),
    0,
  );
  const totalFeesLabel = `₹${totalFees.toLocaleString("en-IN")}`;

  const kpis = [
    { label: "Total Leads", value: totalLeads, accent: "text-brand-blue", href: "/leads" },
    { label: "Total Applications", value: totalApps, accent: "text-brand-blue", href: "/applications/student" },
    { label: "Visa Approved", value: visaApproved, accent: "text-green-600", href: "/applications/visa" },
    {
      label: "Total Fees Collected",
      value: totalFeesLabel,
      accent: "text-brand-orange",
      href: "/fee-payments",
    },
  ];

  const secondaryKpis = [
    { label: "Offers", value: offers, accent: "text-indigo-600", href: "/applications/student" },
    { label: "Coaching Students", value: coachingStudents, accent: "text-brand-blue", href: "/applications/coaching" },
    { label: "Loan Inquiries", value: loanInquiries, accent: "text-brand-orange", href: "/loan-inquiry" },
    { label: "Travelled", value: travelled, accent: "text-emerald-600", href: "/applications/student" },
  ];

  const greeting = (() => {
    const h = new Date().getHours();
    return h < 12 ? "Good morning" : h < 17 ? "Good afternoon" : "Good evening";
  })();

  return (
    <div className="space-y-8">
      {/* Editorial hero band — aubergine canvas with primary KPIs inset */}
      <section className="atlas-canvas grain relative overflow-hidden rounded-3xl px-7 py-8 text-white sm:px-10 sm:py-10">
        <div className="relative z-10">
          <p className="eyebrow text-[var(--gold)]">{greeting}</p>
          <h1 className="font-display mt-3 text-4xl font-light tracking-tight sm:text-5xl">
            {user.full_name.split(" ")[0]}.
          </h1>
          <p className="mt-3 max-w-md text-white/70">
            {todayFollowupsCount} follow-up{todayFollowupsCount === 1 ? "" : "s"} today
            {" · "}
            {newLeads} new lead{newLeads === 1 ? "" : "s"} waiting. Keep guiding
            students to their dream destinations.
          </p>

          <div className="mt-9 grid grid-cols-2 gap-x-8 gap-y-6 sm:grid-cols-4">
            {kpis.map((kpi) => (
              <Link
                key={kpi.label}
                href={kpi.href}
                className="group border-l border-white/15 pl-4 transition-colors hover:border-[var(--gold)]"
              >
                <div className="font-display text-4xl font-light leading-none transition-transform group-hover:-translate-y-0.5">
                  {kpi.value}
                </div>
                <div className="mt-2 flex items-center gap-1 text-xs uppercase tracking-widest text-white/55 group-hover:text-white/80">
                  {kpi.label}
                  <ArrowUpRight className="size-3 opacity-0 transition-opacity group-hover:opacity-100" />
                </div>
              </Link>
            ))}
          </div>
        </div>
        <span
          className="font-display pointer-events-none absolute -bottom-20 right-2 z-0 select-none text-[16rem] leading-none text-white/[0.05]"
          aria-hidden
        >
          ✦
        </span>
      </section>

      {/* Secondary KPIs — thin editorial cards */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {secondaryKpis.map((kpi) => (
          <Link key={kpi.label} href={kpi.href} className="group block">
            <Card className="border-border/70 transition-all hover:-translate-y-0.5 hover:border-brand-blue/40 hover:shadow-md">
              <CardContent className="flex items-baseline justify-between py-5">
                <span className="flex items-center gap-1 text-sm text-muted-foreground group-hover:text-foreground">
                  {kpi.label}
                  <ArrowUpRight className="size-3 opacity-0 transition-opacity group-hover:opacity-100" />
                </span>
                <span className={`font-display text-3xl font-light ${kpi.accent}`}>
                  {kpi.value}
                </span>
              </CardContent>
            </Card>
          </Link>
        ))}
      </div>

      {/* Pipelines */}
      <div className="grid gap-8 lg:grid-cols-2">
        <section>
          <div className="mb-4 flex items-center gap-3">
            <div className="h-px w-8 bg-[var(--gold)]" />
            <h3 className="eyebrow text-muted-foreground">Lead pipeline</h3>
          </div>
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
            {statusBreakdown.map(([status, count]) => (
              <Link
                key={status}
                href={`/leads?status=${encodeURIComponent(status)}`}
                className="block"
              >
                <Card className="border-border/70 transition-all hover:-translate-y-0.5 hover:border-brand-blue/40 hover:shadow-md">
                  <CardContent className="flex flex-col items-start gap-2 py-4">
                    <Badge className={`${LEAD_STATUS_STYLES[status] ?? ""} border-0`} variant="secondary">
                      {status}
                    </Badge>
                    <span className="font-display text-3xl font-light">{count}</span>
                  </CardContent>
                </Card>
              </Link>
            ))}
          </div>
        </section>

        <section>
          <div className="mb-4 flex items-center gap-3">
            <div className="h-px w-8 bg-[var(--gold)]" />
            <h3 className="eyebrow text-muted-foreground">Application pipeline</h3>
          </div>
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
            {appStatusBreakdown.map(([status, count]) => (
              <Link
                key={status}
                href={`/applications/student?status=${encodeURIComponent(status)}`}
                className="block"
              >
                <Card className="border-border/70 transition-all hover:-translate-y-0.5 hover:border-brand-blue/40 hover:shadow-md">
                  <CardContent className="flex flex-col items-start gap-2 py-4">
                    <Badge className={`${APPLICATION_STATUS_STYLES[status] ?? ""} border-0`} variant="secondary">
                      {status}
                    </Badge>
                    <span className="font-display text-3xl font-light">{count}</span>
                  </CardContent>
                </Card>
              </Link>
            ))}
          </div>
        </section>
      </div>

      {/* Today's follow-ups + org counts */}
      <div className="grid gap-4 lg:grid-cols-3">
        <Card className="border-border/70 lg:col-span-2">
          <CardHeader>
            <CardTitle className="font-display text-xl font-normal">
              Today&apos;s Follow-ups
            </CardTitle>
          </CardHeader>
          <CardContent>
            {todayFollowups.length === 0 ? (
              <p className="text-sm text-muted-foreground">
                No follow-ups scheduled for today.
              </p>
            ) : (
              <ul className="divide-y divide-border/70">
                {todayFollowups.map((f) => (
                  <li key={f.id} className="flex items-center justify-between gap-4 py-3">
                    <div className="min-w-0">
                      <Link
                        href={`/leads/${f.lead_id}`}
                        className="font-medium text-brand-blue hover:text-brand-orange"
                      >
                        {f.lead?.full_name ?? "Unknown lead"}
                      </Link>
                      {f.lead?.phone ? (
                        <p className="text-sm text-muted-foreground">{f.lead.phone}</p>
                      ) : null}
                    </div>
                    {f.from_time ? (
                      <span className="font-display shrink-0 text-lg text-brand-orange">
                        {f.from_time.slice(0, 5)}
                      </span>
                    ) : null}
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>

        <div className="grid gap-4">
          <Card className="border-border/70">
            <CardContent className="flex items-baseline justify-between py-5">
              <span className="text-sm text-muted-foreground">Branches</span>
              <span className="font-display text-3xl font-light">{branchCount}</span>
            </CardContent>
          </Card>
          <Card className="border-border/70">
            <CardContent className="flex items-baseline justify-between py-5">
              <span className="text-sm text-muted-foreground">Users</span>
              <span className="font-display text-3xl font-light">{userCount}</span>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
