"use client";

import clsx from "clsx";
import Link from "next/link";
import { Suspense, useEffect } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Megaphone, Plus } from "lucide-react";
import { Button, EmptyState, PageHeader, Panel, Skeleton } from "@/components/ui/kit";
import { useSession } from "@/components/session";
import { CampaignStatusBadge, pct, ProgressBar } from "@/components/campaigns/campaign-status";
import { formatDateTime } from "@/lib/format";
import { qs } from "@/lib/api";
import { useApi } from "@/lib/use-api";
import type { Campaign } from "@/lib/types";

const FILTERS = [
  ["", "All"],
  ["running", "Sending"],
  ["scheduled", "Scheduled"],
  ["draft", "Drafts"],
  ["completed", "Completed"],
] as const;
const nf = new Intl.NumberFormat("en-IN");

function when(c: Campaign) {
  if (c.status === "scheduled") return `Sends ${formatDateTime(c.scheduled_at)}`;
  if (c.status === "draft") return `Created ${formatDateTime(c.created_at)}`;
  if (c.completed_at) return `Finished ${formatDateTime(c.completed_at)}`;
  if (c.started_at) return `Started ${formatDateTime(c.started_at)}`;
  return formatDateTime(c.created_at);
}

function CampaignList() {
  const params = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const { can } = useSession();
  const status = params.get("status") ?? "";
  const page = Number(params.get("page") ?? 1);
  const { data, loading, reload } = useApi<{ data: Campaign[]; meta: { total: number; last_page: number } }>(`/campaigns${qs({ status: status || undefined, page })}`);
  const rows = data?.data ?? [];
  const active = rows.some((c) => c.status === "running");

  // While anything is sending, refresh the numbers every few seconds.
  useEffect(() => {
    if (!active) return;
    const t = setInterval(reload, 4000);
    return () => clearInterval(t);
  }, [active, reload]);

  const go = (next: Record<string, string | number | undefined>) => router.replace(`${pathname}${qs({ status: status || undefined, page: undefined, ...next })}`);

  return (
    <>
      <PageHeader
        title="Campaigns"
        description="Broadcast approved templates to your contact groups and track delivery for each recipient."
        actions={
          can("campaigns.manage") && (
            <Button variant="primary" icon={<Plus className="size-4" />} onClick={() => router.push("/campaigns/new")}>
              New campaign
            </Button>
          )
        }
      />
      <div className="mb-4 flex gap-1 overflow-x-auto" role="tablist" aria-label="Filter campaigns">
        {FILTERS.map(([v, l]) => (
          <button key={v} role="tab" aria-selected={status === v} onClick={() => go({ status: v || undefined })} className={clsx("shrink-0 rounded-full px-3 py-1.5 text-sm", status === v ? "bg-ink text-white" : "text-muted hover:bg-white")}>
            {l}
          </button>
        ))}
      </div>
      <Panel>
        {!data && loading ? (
          <div className="space-y-3 p-6">
            {[0, 1, 2].map((i) => (
              <Skeleton key={i} className="h-14 w-full" />
            ))}
          </div>
        ) : rows.length === 0 ? (
          <EmptyState
            icon={<Megaphone />}
            title={status ? "No campaigns here" : "No campaigns yet"}
            body={status ? "Try another filter." : "Pick an audience and an approved template, then send now or schedule it for later."}
            action={
              !status &&
              can("campaigns.manage") && (
                <Button variant="primary" onClick={() => router.push("/campaigns/new")}>
                  Create your first campaign
                </Button>
              )
            }
          />
        ) : (
          <div className="relative overflow-x-auto">
            <table className="w-full min-w-[760px] text-sm">
              <thead className="border-b border-line text-left text-[13px] text-muted">
                <tr>
                  <th className="px-5 py-3 font-medium">Campaign</th>
                  <th className="px-3 py-3 font-medium">Status</th>
                  <th className="px-3 py-3 text-right font-medium">Recipients</th>
                  <th className="w-[200px] px-3 py-3 font-medium">Progress</th>
                  <th className="px-3 py-3 text-right font-medium">Read</th>
                  <th className="px-5 py-3 text-right font-medium">Failed</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-line">
                {rows.map((c) => {
                  const s = c.stats;
                  const reach = s ? s.total - s.skipped : 0;
                  const href = c.status === "draft" && can("campaigns.manage") ? `/campaigns/${c.id}/edit` : `/campaigns/${c.id}`;
                  return (
                    <tr key={c.id} className="group relative hover:bg-paper/60">
                      <td className="px-5 py-3">
                        <Link href={href} className="font-medium text-ink after:absolute after:inset-0 group-hover:text-teal">
                          {c.title}
                        </Link>
                        <p className="mt-0.5 flex flex-wrap gap-x-3 text-[13px] text-muted">
                          <span>{c.template.name}</span>
                          <span>{when(c)}</span>
                        </p>
                      </td>
                      <td className="px-3 py-3">
                        <CampaignStatusBadge status={c.status} />
                      </td>
                      <td className="tabular px-3 py-3 text-right">{s && s.total ? nf.format(reach) : "—"}</td>
                      <td className="px-3 py-3">
                        {s && s.total ? (
                          <div>
                            <ProgressBar stats={s} />
                            <p className="tabular mt-1 text-xs text-muted">
                              {nf.format(s.sent)} of {nf.format(reach)} sent
                            </p>
                          </div>
                        ) : (
                          <span className="text-muted">—</span>
                        )}
                      </td>
                      <td className="tabular px-3 py-3 text-right">{s && s.sent ? `${pct(s.read, s.sent)}%` : "—"}</td>
                      <td className={clsx("tabular px-5 py-3 text-right", s?.failed ? "text-brick" : "text-muted")}>{s && s.total ? nf.format(s.failed) : "—"}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
        {data && data.meta.last_page > 1 && (
          <footer className="flex items-center justify-between border-t border-line px-5 py-3 text-sm text-muted">
            <span className="tabular">
              Page {page} of {data.meta.last_page}
            </span>
            <div className="flex gap-2">
              <Button size="sm" disabled={page <= 1} onClick={() => go({ page: page - 1 })}>
                Previous
              </Button>
              <Button size="sm" disabled={page >= data.meta.last_page} onClick={() => go({ page: page + 1 })}>
                Next
              </Button>
            </div>
          </footer>
        )}
      </Panel>
    </>
  );
}

export default function CampaignsPage() {
  return (
    <Suspense>
      <CampaignList />
    </Suspense>
  );
}
