"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Modal from "./Modal";
import { inviteAccessAction } from "@/lib/actions/team-actions";

const ROLE_OPTIONS: { value: string; label: string }[] = [
  { value: "ADMIN", label: "Admin" },
  { value: "DEVELOPER", label: "Developer" },
  { value: "CLIENT_VIEWER", label: "Client viewer" },
  { value: "VIEWER", label: "Viewer" },
];

export default function InviteAccessButton({
  siteId,
  allowAllSitesScope = true,
}: {
  siteId?: string;
  allowAllSitesScope?: boolean;
}) {
  const router = useRouter();
  const [scope, setScope] = useState<"ALL_SITES" | "SPECIFIC">(
    siteId && !allowAllSitesScope ? "SPECIFIC" : "ALL_SITES"
  );
  const [inviteLink, setInviteLink] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(formData: FormData, close: () => void) {
    setError(null);
    setLoading(true);
    try {
      const { token } = await inviteAccessAction(formData);
      setInviteLink(`${window.location.origin}/accept-invite?token=${token}`);
      router.refresh();
    } catch (e: any) {
      setError(e?.message ?? "Something went wrong.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <Modal
      title="Invite access"
      trigger={
        <button className="bg-accent text-white font-bold text-[12.5px] px-3.5 py-2 rounded-lg whitespace-nowrap">
          + Invite access
        </button>
      }
    >
      {(close) =>
        inviteLink ? (
          <div className="flex flex-col gap-3">
            <div className="text-sm text-text-secondary">
              There's no email service configured yet, so share this link with them directly:
            </div>
            <input
              readOnly
              value={inviteLink}
              onFocus={(e) => e.currentTarget.select()}
              className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-[12px] font-mono outline-none"
            />
            <button
              onClick={() => {
                setInviteLink(null);
                close();
              }}
              className="bg-accent text-white font-bold text-sm px-4 py-2 rounded-lg self-end"
            >
              Done
            </button>
          </div>
        ) : (
          <form
            onSubmit={(e) => {
              e.preventDefault();
              handleSubmit(new FormData(e.currentTarget), close);
            }}
            className="flex flex-col gap-3.5"
          >
            {siteId && <input type="hidden" name="siteId" value={siteId} />}
            <div>
              <label className="block text-xs text-text-secondary mb-1.5">Name</label>
              <input
                name="name"
                required
                className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-sm outline-none"
              />
            </div>
            <div>
              <label className="block text-xs text-text-secondary mb-1.5">Email</label>
              <input
                name="email"
                type="email"
                required
                className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-sm font-mono outline-none"
              />
            </div>
            <div>
              <label className="block text-xs text-text-secondary mb-1.5">Role</label>
              <select
                name="role"
                className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-sm outline-none"
              >
                {ROLE_OPTIONS.map((r) => (
                  <option key={r.value} value={r.value}>
                    {r.label}
                  </option>
                ))}
              </select>
            </div>
            {siteId && (
              <div>
                <label className="block text-xs text-text-secondary mb-1.5">Scope</label>
                <select
                  name="scope"
                  value={scope}
                  onChange={(e) => setScope(e.target.value as any)}
                  className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-sm outline-none"
                >
                  {allowAllSitesScope && <option value="ALL_SITES">All sites</option>}
                  <option value="SPECIFIC">This site only</option>
                </select>
              </div>
            )}
            {!siteId && <input type="hidden" name="scope" value="ALL_SITES" />}
            {error && <div className="text-[12px] text-error">{error}</div>}
            <div className="flex gap-2.5 justify-end mt-2">
              <button
                type="button"
                onClick={close}
                className="bg-transparent border border-border-input text-text-secondary font-semibold text-sm px-3.5 py-2 rounded-lg"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={loading}
                className="bg-accent text-white font-bold text-sm px-4 py-2 rounded-lg disabled:opacity-60"
              >
                {loading ? "Sending…" : "Send invite"}
              </button>
            </div>
          </form>
        )
      }
    </Modal>
  );
}
