"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { IndianRupee, Wallet, Users, Percent, MousePointerClick, ShoppingCart, ArrowRight, Link2, Copy } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, StatCard, Card, Skeleton, Button, Badge } from "@/components/ui";
import { useToast } from "@/components/toast";
import { AreaChart, BarList, Donut } from "@/components/charts";

type Recent = { id: string; name: string; email: string; status: string; date: string };
type KPI = {
  programName: string;
  shop: string;
  revenue: number;
  commissionsOwed: number;
  activeAffiliates: number;
  pendingAffiliates: number;
  clicks: number;
  conversions: number;
  convRate: number;
  recentAffiliates: Recent[];
};
type Analytics = {
  days: { label: string; revenue: number; commission: number; orders: number }[];
  topAffiliates: { name: string; earnings: number; sales: number }[];
  statusBreakdown: Record<string, number>;
};

const inr = (n: number) => "₹" + Math.round(n).toLocaleString("en-IN");

export default function OverviewPage() {
  const toast = useToast();
  const [kpi, setKpi] = useState<KPI | null>(null);
  const [an, setAn] = useState<Analytics | null>(null);
  const [origin, setOrigin] = useState("");

  useEffect(() => {
    api.get("/admin/dashboard").then(setKpi).catch(() => {});
    api.get("/admin/analytics").then(setAn).catch(() => {});
    setOrigin(window.location.origin);
  }, []);

  // Scope every affiliate link to THIS store (?shop=…) so signups, logins and the
  // portal all attach to this merchant — not the shared default store. Without
  // the shop, an approved affiliate would keep seeing "pending" in their portal.
  const shopQ = kpi?.shop ? `?shop=${encodeURIComponent(kpi.shop)}` : "";
  const links = [
    { label: "Affiliate sign-up", url: `${origin}/signup${shopQ}`, hint: "New affiliates apply here" },
    { label: "Affiliate login", url: `${origin}/login${shopQ}`, hint: "Approved affiliates log in here" },
    { label: "Affiliate portal", url: `${origin}/dashboard${shopQ}`, hint: "Their dashboard after logging in" },
  ];
  const copy = (url: string) => {
    navigator.clipboard?.writeText(url);
    toast.success("Link copied.");
  };

  return (
    <div>
      <PageHeader title="Overview" subtitle={kpi?.programName ? `${kpi.programName} — affiliate program` : "Program dashboard"} />

      {/* KPI cards */}
      <div className="grid grid-cols-2 gap-4 lg:grid-cols-3 xl:grid-cols-6">
        {!kpi
          ? Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-[92px]" />)
          : [
              { label: "Revenue via affiliates", value: inr(kpi.revenue), icon: <IndianRupee className="h-5 w-5" />, accent: "#1A3C6E" },
              { label: "Commissions owed", value: inr(kpi.commissionsOwed), icon: <Wallet className="h-5 w-5" />, accent: "#d97706" },
              { label: "Active affiliates", value: kpi.activeAffiliates, icon: <Users className="h-5 w-5" />, accent: "#16a34a", hint: `${kpi.pendingAffiliates} pending` },
              { label: "Total clicks", value: kpi.clicks, icon: <MousePointerClick className="h-5 w-5" />, accent: "#7c3aed" },
              { label: "Conversions", value: kpi.conversions, icon: <ShoppingCart className="h-5 w-5" />, accent: "#0891b2" },
              { label: "Conversion rate", value: `${kpi.convRate.toFixed(1)}%`, icon: <Percent className="h-5 w-5" />, accent: "#2563eb" },
            ].map((c) => <StatCard key={c.label} {...c} />)}
      </div>

      {/* Pending banner */}
      {kpi && kpi.pendingAffiliates > 0 && (
        <div className="mt-4 flex items-center justify-between rounded-xl border border-amber-200 bg-amber-50 px-4 py-3">
          <p className="text-sm text-amber-900">
            <span className="font-semibold">{kpi.pendingAffiliates}</span> affiliate application(s) waiting for review.
          </p>
          <Link href="/admin/affiliates">
            <Button size="sm" variant="secondary" icon={<ArrowRight className="h-4 w-4" />}>
              Review
            </Button>
          </Link>
        </div>
      )}

      {/* Important links + New registrations (GoAffPro-style) */}
      <div className="mt-4 grid gap-4 lg:grid-cols-2">
        <Card title="Important links" subtitle="Share these with your affiliates">
          <ul className="divide-y divide-gray-50">
            {links.map((l) => (
              <li key={l.label} className="flex items-center justify-between gap-3 py-2.5">
                <div className="min-w-0">
                  <p className="text-sm font-medium text-gray-800">{l.label}</p>
                  {l.hint && <p className="text-xs text-gray-400">{l.hint}</p>}
                  <a href={l.url} target="_blank" rel="noreferrer" className="mt-0.5 flex items-center gap-1 truncate text-xs text-[var(--brand)] hover:underline">
                    <Link2 className="h-3 w-3 shrink-0" /> <span className="truncate">{l.url || "…"}</span>
                  </a>
                </div>
                <button onClick={() => copy(l.url)} className="shrink-0 rounded-lg border border-gray-300 p-1.5 text-gray-500 hover:bg-gray-50"><Copy className="h-3.5 w-3.5" /></button>
              </li>
            ))}
          </ul>
        </Card>

        <Card title="New registrations" subtitle="Latest affiliate signups">
          {!kpi ? (
            <Skeleton className="h-40" />
          ) : kpi.recentAffiliates.length === 0 ? (
            <p className="py-6 text-center text-sm text-gray-400">No signups yet.</p>
          ) : (
            <ul className="divide-y divide-gray-50">
              {kpi.recentAffiliates.map((a) => (
                <li key={a.id} className="flex items-center justify-between gap-3 py-2.5">
                  <Link href={`/admin/affiliates/${a.id}`} className="min-w-0">
                    <p className="truncate text-sm font-medium text-gray-800 hover:text-[var(--brand)]">{a.name}</p>
                    <p className="truncate text-xs text-gray-400">{a.email} · {a.date}</p>
                  </Link>
                  <Badge tone={a.status === "ACTIVE" ? "success" : a.status === "PENDING" ? "warning" : "neutral"}>{a.status}</Badge>
                </li>
              ))}
            </ul>
          )}
        </Card>
      </div>

      {/* Charts */}
      <div className="mt-4 grid gap-4 lg:grid-cols-3">
        <Card title="Revenue" subtitle="Last 14 days" className="lg:col-span-2">
          {!an ? <Skeleton className="h-[220px]" /> : <AreaChart data={an.days.map((d) => ({ label: d.label, value: d.revenue }))} format={inr} />}
        </Card>
        <Card title="Affiliate status">
          {!an ? (
            <Skeleton className="h-[220px]" />
          ) : (
            <div className="py-4">
              <Donut
                centerLabel="Affiliates"
                data={[
                  { label: "Active", value: an.statusBreakdown.ACTIVE ?? 0, color: "#16a34a" },
                  { label: "Pending", value: an.statusBreakdown.PENDING ?? 0, color: "#d97706" },
                  { label: "Rejected", value: an.statusBreakdown.REJECTED ?? 0, color: "#dc2626" },
                ]}
              />
            </div>
          )}
        </Card>
      </div>

      <div className="mt-4 grid gap-4 lg:grid-cols-2">
        <Card title="Top affiliates" subtitle="By lifetime commission">
          {!an ? (
            <Skeleton className="h-40" />
          ) : an.topAffiliates.length === 0 ? (
            <p className="py-6 text-center text-sm text-gray-400">No earnings yet.</p>
          ) : (
            <BarList data={an.topAffiliates.map((a) => ({ label: a.name, value: a.earnings }))} format={inr} />
          )}
        </Card>
        <Card title="Orders" subtitle="Last 14 days">
          {!an ? <Skeleton className="h-40" /> : <AreaChart data={an.days.map((d) => ({ label: d.label, value: d.orders }))} height={168} color="#16a34a" />}
        </Card>
      </div>
    </div>
  );
}
