"use client";

import { useState } from "react";
import { requestSuperUser } from "./actions";

interface Props {
  pendingRequest: { createdAt: Date; status: string } | null;
}

export function SuperUserRequestForm({ pendingRequest }: Props) {
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState("");
  const [pending, setPending] = useState(false);

  if (pendingRequest) {
    const isPending = pendingRequest.status === "PENDING";
    const isApproved = pendingRequest.status === "APPROVED";
    return (
      <div className={`rounded-lg border px-4 py-3 text-sm ${
        isPending
          ? "border-warning-200 bg-warning-50 text-warning-800"
          : isApproved
          ? "border-success-200 bg-success-50 text-success-800"
          : "border-danger-200 bg-danger-50 text-danger-800"
      }`}>
        {isPending && "Your SuperUser access request is pending admin review."}
        {isApproved && "Your SuperUser access request was approved."}
        {!isPending && !isApproved && "Your SuperUser access request was not approved."}
      </div>
    );
  }

  if (submitted) {
    return (
      <div className="rounded-lg border border-success-200 bg-success-50 px-4 py-3 text-sm text-success-800">
        Your request has been submitted. An admin will review it shortly.
      </div>
    );
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setPending(true);
    setError("");
    const result = await requestSuperUser(new FormData(e.currentTarget));
    setPending(false);
    if ("error" in result) setError(result.error);
    else setSubmitted(true);
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <p className="text-sm text-neutral-600">
        SuperUser access grants additional cross-team permissions. Describe why you need elevated access and an admin will review your request.
      </p>
      <div>
        <label className="block text-sm font-medium text-neutral-700 mb-1.5">
          Reason (optional)
        </label>
        <textarea
          name="reason"
          rows={3}
          className="w-full rounded-lg border border-neutral-300 px-3 py-2.5 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 resize-none"
          placeholder="Explain why you need SuperUser access…"
        />
      </div>
      {error && (
        <p className="text-sm text-danger-700 bg-danger-50 rounded-lg px-3 py-2">{error}</p>
      )}
      <button
        type="submit"
        disabled={pending}
        className="rounded-lg bg-primary-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-primary-700 disabled:opacity-60 transition-colors"
      >
        {pending ? "Submitting…" : "Request SuperUser Access"}
      </button>
    </form>
  );
}
