"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { Check } from "lucide-react";
import clsx from "clsx";
import { PageHeader, Panel, Skeleton } from "@/components/ui/kit";
import { useSession } from "@/components/session";
import { useRouter } from "next/navigation";
import { api } from "@/lib/api";

interface Stats {
  contacts: { total: number; opted_in: number; opted_out: number; added_last_7_days: number };
  groups: { total: number };
  team_members: { total: number };
  whatsapp: { connected_numbers: number; messages_received_24h: number };
  templates: { approved: number };
  campaigns: { launched: number };
  bots: { active_replies: number; automated_replies_24h: number; flows: number };
  inbox: { open_conversations: number; unassigned: number };
}

const nf = new Intl.NumberFormat("en-IN");

export default function DashboardPage() {
  const { me, can, loading } = useSession();
  const router = useRouter();
  // Reseller organisations have no customer dashboard: send them to their portal.
  const elsewhere = !loading && me && !can("dashboard.view") ? (can("reseller.view") ? "/reseller" : can("platform.organizations.view") ? "/admin" : null) : null;
  useEffect(() => {
    if (elsewhere) router.replace(elsewhere);
  }, [elsewhere, router]);
  const [stats, setStats] = useState<Stats | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!can("dashboard.view")) return;
    api
      .get<{ data: Stats }>("/dashboard/stats")
      .then((r) => setStats(r.data))
      .catch((e) => setError(e.message));
  }, [can]);

  const firstName = me?.user.name.split(" ")[0];
  const c = stats?.contacts;
  const unknown = c ? c.total - c.opted_in - c.opted_out : 0;
  const pct = (n: number) => (c && c.total ? (n / c.total) * 100 : 0);

  const steps = [
    { label: "Add or import your contacts", done: (c?.total ?? 0) > 0, href: "/contacts", cta: "Go to contacts" },
    { label: "Sort contacts into groups for targeting", done: (stats?.groups.total ?? 0) > 0, href: "/contacts/groups", cta: "Create a group" },
    { label: "Invite your team", done: (stats?.team_members.total ?? 0) > 1, href: "/team", cta: "Add a teammate" },
    { label: "Connect your WhatsApp Business number", done: (stats?.whatsapp.connected_numbers ?? 0) > 0, href: "/settings/whatsapp", cta: "Connect a number" },
    { label: "Sync or create approved message templates", done: (stats?.templates.approved ?? 0) > 0, href: "/templates", cta: "Go to templates" },
    { label: "Schedule your first campaign", done: (stats?.campaigns.launched ?? 0) > 0, href: "/campaigns/new", cta: "Create a campaign" },
    { label: "Answer common questions with bot replies", done: (stats?.bots.active_replies ?? 0) > 0, href: "/bot-replies", cta: "Set up bot replies" },
  ];

  return (
    <>
      <PageHeader title={firstName ? `Hi ${firstName}` : "Dashboard"} description={me?.organization ? `Here's where ${me.organization.name} stands today.` : undefined} />

      {error && <p className="mb-4 rounded-md bg-brick-soft px-3 py-2 text-sm text-brick">{error}</p>}

      <Panel className="grid divide-y divide-line sm:grid-cols-4 sm:divide-x sm:divide-y-0">
        {[
          { label: "Contacts", value: c?.total, href: "/contacts" },
          { label: "Added this week", value: c?.added_last_7_days, href: "/contacts" },
          { label: "Groups", value: stats?.groups.total, href: "/contacts/groups" },
          { label: "Open conversations", value: stats?.inbox.open_conversations, href: "/inbox" },
        ].map((s) => (
          <Link key={s.label} href={s.href} className="group px-6 py-5 hover:bg-paper/60">
            <div className="text-sm text-muted group-hover:text-teal">{s.label}</div>
            {s.value === undefined ? <Skeleton className="mt-2 h-8 w-16" /> : <div className="tabular mt-1 text-[32px] font-semibold leading-none tracking-tight text-ink">{nf.format(s.value)}</div>}
          </Link>
        ))}
      </Panel>

      <div className="mt-6 grid gap-6 lg:grid-cols-[3fr_2fr]">
        <Panel className="p-6">
          <h2 className="font-semibold">Marketing consent</h2>
          <p className="mt-1 text-sm text-muted">Campaigns only go to opted-in contacts. Opted-out contacts are always excluded.</p>
          {c ? (
            <>
              <div className="mt-5 flex h-3 overflow-hidden rounded-full bg-paper" role="img" aria-label={`${c.opted_in} opted in, ${unknown} unknown, ${c.opted_out} opted out`}>
                <div className="bg-teal" style={{ width: `${pct(c.opted_in)}%` }} />
                <div className="bg-line" style={{ width: `${pct(unknown)}%` }} />
                <div className="bg-brick" style={{ width: `${pct(c.opted_out)}%` }} />
              </div>
              <div className="mt-4 grid grid-cols-3 gap-4 text-sm">
                {[
                  { label: "Opted in", value: c.opted_in, dot: "bg-teal", href: "/contacts?opt_in_status=opted_in" },
                  { label: "Unknown", value: unknown, dot: "bg-line", href: "/contacts?opt_in_status=unknown" },
                  { label: "Opted out", value: c.opted_out, dot: "bg-brick", href: "/contacts?opt_in_status=opted_out" },
                ].map((x) => (
                  <Link key={x.label} href={x.href} className="group -m-2 rounded-md p-2 hover:bg-paper">
                    <span className="flex items-center gap-2 text-muted group-hover:text-teal">
                      <span className={clsx("size-2.5 rounded-full", x.dot)} />
                      {x.label}
                    </span>
                    <span className="tabular mt-1 block text-xl font-semibold text-ink">{nf.format(x.value)}</span>
                  </Link>
                ))}
              </div>
            </>
          ) : (
            <Skeleton className="mt-5 h-20 w-full" />
          )}
        </Panel>

        <Panel className="p-6">
          <h2 className="font-semibold">Getting set up</h2>
          <ol className="mt-4 space-y-3">
            {steps.map((s, i) => (
              <li key={s.label} className="flex items-start gap-3 text-sm">
                <span
                  className={clsx(
                    "tabular mt-px grid size-6 shrink-0 place-items-center rounded-full text-xs font-semibold",
                    s.done ? "bg-teal text-white" : "bg-paper text-muted ring-1 ring-inset ring-line",
                  )}
                >
                  {s.done ? <Check className="size-3.5" /> : i + 1}
                </span>
                <div className="flex-1">
                  <span className={clsx(s.done ? "text-muted line-through decoration-line" : "text-text")}>{s.label}</span>
                  {!s.done && (
                    <Link href={s.href} className="block text-[13px] font-medium text-teal hover:underline">
                      {s.cta}
                    </Link>
                  )}
                </div>
              </li>
            ))}
          </ol>
        </Panel>
      </div>
    </>
  );
}
