"use client";

import { useRouter, usePathname, useSearchParams } from "next/navigation";
import { useTransition } from "react";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { Select } from "@/components/ui/Select";
import {
  adminSetWorkspacePlan,
  toggleWorkspaceSuspension,
} from "@/lib/actions/admin";
import type { AdminClientRow } from "@/lib/queries/admin-queries";
import type { PlanTier } from "@/types";

interface AdminClientsTableProps {
  clients: AdminClientRow[];
  showPlanFilter?: boolean;
}

const PLAN_OPTIONS: PlanTier[] = ["free", "pro", "enterprise"];

export function AdminClientsTable({
  clients,
  showPlanFilter = true,
}: AdminClientsTableProps) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [pending, startTransition] = useTransition();

  const plan = searchParams.get("plan") ?? "all";
  const search = searchParams.get("search") ?? "";

  function updateParams(key: string, value: string) {
    const params = new URLSearchParams(searchParams.toString());
    if (value) params.set(key, value);
    else params.delete(key);
    router.push(`${pathname}?${params.toString()}`);
  }

  function handleSuspend(id: string) {
    startTransition(async () => {
      await toggleWorkspaceSuspension(id);
      router.refresh();
    });
  }

  function handlePlanChange(id: string, planTier: PlanTier) {
    startTransition(async () => {
      await adminSetWorkspacePlan({ workspaceId: id, planTier });
      router.refresh();
    });
  }

  return (
    <div>
      {showPlanFilter && (
        <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex flex-wrap gap-2">
            {(["all", "free", "pro", "enterprise"] as const).map((p) => (
              <button
                key={p}
                type="button"
                onClick={() => updateParams("plan", p === "all" ? "" : p)}
                className={`rounded-full px-3 py-1.5 text-xs font-semibold capitalize transition-colors ${
                  (plan === p || (p === "all" && !searchParams.get("plan")))
                    ? "bg-primary text-white"
                    : "border border-border bg-white text-muted hover:border-primary/30"
                }`}
              >
                {p === "all" ? "All Plans" : p}
              </button>
            ))}
          </div>
          <input
            type="search"
            placeholder="Search clients..."
            defaultValue={search}
            onChange={(e) => updateParams("search", e.target.value)}
            className="w-full rounded-sm border border-border px-3 py-2 text-sm sm:max-w-[240px]"
          />
        </div>
      )}

      <div className="overflow-x-auto rounded-lg border border-border bg-card shadow">
        <table className="w-full min-w-[640px] text-left text-sm">
          <thead>
            <tr className="border-b border-border bg-bg/50 text-xs font-semibold text-muted">
              <th className="px-4 py-3">Client</th>
              <th className="px-4 py-3">Plan</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3">Surveys</th>
              <th className="px-4 py-3">MRR</th>
              <th className="px-4 py-3 text-right">Actions</th>
            </tr>
          </thead>
          <tbody>
            {clients.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-4 py-10 text-center text-muted">
                  No clients match your filters.
                </td>
              </tr>
            ) : (
              clients.map((c) => (
                <tr
                  key={c.id}
                  className="border-b border-border/60 last:border-0 hover:bg-bg/40"
                >
                  <td className="px-4 py-3">
                    <div className="font-semibold text-navy">{c.name}</div>
                    <div className="text-xs text-muted">{c.ownerEmail ?? "—"}</div>
                  </td>
                  <td className="px-4 py-3 capitalize">
                    <Badge status={c.planTier} />
                  </td>
                  <td className="px-4 py-3">
                    {c.isSuspended ? (
                      <span className="text-xs font-bold text-danger">Suspended</span>
                    ) : (
                      <span className="text-xs font-semibold capitalize text-success">
                        {c.subscriptionStatus.replace("_", " ")}
                      </span>
                    )}
                  </td>
                  <td className="px-4 py-3 font-mono text-xs">{c.surveyCount}</td>
                  <td className="px-4 py-3 font-mono text-xs">{c.mrrFormatted}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center justify-end gap-2">
                      <Select
                        className="h-8 max-w-[110px] py-1 text-xs"
                        value={c.planTier}
                        disabled={pending}
                        onChange={(e) =>
                          handlePlanChange(c.id, e.target.value as PlanTier)
                        }
                      >
                        {PLAN_OPTIONS.map((p) => (
                          <option key={p} value={p}>
                            {p}
                          </option>
                        ))}
                      </Select>
                      <Button
                        variant="outline"
                        size="sm"
                        disabled={pending}
                        onClick={() => handleSuspend(c.id)}
                      >
                        {c.isSuspended ? "Restore" : "Suspend"}
                      </Button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
