"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";

type ExtensionRequest = {
  id: string;
  status: string;
  message: string;
  requestedAt: string;
  processedAt: string | null;
  adminNote: string | null;
};

type ExtensionUsage = {
  used: number;
  limit: number;
  remaining: number;
  requests: ExtensionRequest[];
};

type Props = {
  initialUsage: ExtensionUsage;
};

export function PlanBillingActions({ initialUsage }: Props) {
  const router = useRouter();
  const [usage, setUsage] = useState(initialUsage);
  const [cancelling, setCancelling] = useState(false);
  const [requesting, setRequesting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  async function handleCancelPlan() {
    if (
      !confirm(
        "Cancel your Pro plan? You will be moved to the free plan immediately and lose Pro benefits.",
      )
    ) {
      return;
    }

    setCancelling(true);
    setError(null);
    setSuccess(null);

    try {
      const res = await fetch("/api/account/cancel-subscription", { method: "POST" });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to cancel subscription");
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to cancel subscription");
    } finally {
      setCancelling(false);
    }
  }

  async function handleQuotaRequest() {
    if (usage.remaining <= 0) return;

    const reason = prompt(
      "Optional: tell us why you need a quota reset or extension (leave blank to skip).",
    );
    if (reason === null) return;

    setRequesting(true);
    setError(null);
    setSuccess(null);

    try {
      const res = await fetch("/api/account/quota-extension-request", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: reason }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to submit request");

      setUsage({
        used: data.used,
        limit: data.limit,
        remaining: data.remaining,
        requests: data.requests ?? usage.requests,
      });
      setSuccess(
        `Request submitted. ${data.used} of ${data.limit} extension requests used this year. Support will process it shortly.`,
      );
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to submit request");
    } finally {
      setRequesting(false);
    }
  }

  const hasPending = usage.requests.some((r) => r.status === "PENDING");

  return (
    <div className="mt-4 space-y-4">
      <div className="rounded border border-gray-700 bg-surface px-4 py-3 text-sm">
        <p className="text-gray-300">
          Extension requests this year:{" "}
          <span className="font-medium text-white">
            {usage.used} / {usage.limit}
          </span>
          {usage.remaining > 0 ? (
            <span className="text-gray-500"> · {usage.remaining} remaining</span>
          ) : (
            <span className="text-yellow-400"> · limit reached</span>
          )}
        </p>
      </div>

      {error && (
        <div className="rounded border border-red-500/50 bg-red-500/10 px-4 py-3 text-sm text-red-300">
          {error}
        </div>
      )}

      {success && (
        <div className="rounded border border-green-500/50 bg-green-500/10 px-4 py-3 text-sm text-green-300">
          {success}
        </div>
      )}

      <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap">
        <button
          type="button"
          onClick={handleCancelPlan}
          disabled={cancelling}
          className="inline-flex items-center justify-center rounded border border-yellow-600/50 px-4 py-2 text-sm font-medium text-yellow-300 transition-colors hover:bg-yellow-500/10 disabled:opacity-50"
        >
          {cancelling ? "Cancelling…" : "Cancel your plan"}
        </button>

        <button
          type="button"
          onClick={handleQuotaRequest}
          disabled={requesting || usage.remaining <= 0 || hasPending}
          className="inline-flex items-center justify-center rounded border border-accent/40 px-4 py-2 text-sm font-medium text-accent transition-colors hover:bg-accent/10 disabled:cursor-not-allowed disabled:opacity-50"
        >
          {requesting
            ? "Submitting…"
            : hasPending
              ? "Request pending…"
              : "Request quota reset & extension"}
        </button>
      </div>

      {usage.requests.length > 0 && (
        <div className="space-y-2">
          <p className="text-xs font-semibold uppercase tracking-wider text-gray-500">
            Request history
          </p>
          <ul className="space-y-2">
            {usage.requests.slice(0, 5).map((req) => (
              <li
                key={req.id}
                className="rounded border border-gray-800 bg-surface px-3 py-2 text-xs text-gray-400"
              >
                <div className="flex items-center justify-between gap-2">
                  <span className="text-gray-300">
                    {new Date(req.requestedAt).toLocaleDateString(undefined, {
                      month: "short",
                      day: "numeric",
                      year: "numeric",
                    })}
                  </span>
                  <span
                    className={
                      req.status === "APPROVED"
                        ? "text-green-400"
                        : req.status === "REJECTED"
                          ? "text-red-400"
                          : "text-yellow-400"
                    }
                  >
                    {req.status}
                  </span>
                </div>
                {req.message && <p className="mt-1 text-gray-500">{req.message}</p>}
                <p className="mt-1 font-mono text-[10px] text-gray-600">ID: {req.id}</p>
              </li>
            ))}
          </ul>
        </div>
      )}

      <p className="text-xs text-gray-500">
        Pro users may request up to 5 manual quota resets or extensions per calendar year. See our{" "}
        <a href="/terms" className="text-gray-400 underline hover:text-white">
          Terms of Service
        </a>
        .
      </p>
    </div>
  );
}
