"use client";

import { useActionState } from "react";
import Link from "next/link";
import { ArrowRightIcon, Loader2Icon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { addAccountAction, type AddAccountResult } from "@/actions/accounts";

const initialState: AddAccountResult = { ok: true, accountId: "" };

export function PairForm() {
  const [state, action, isPending] = useActionState(addAccountAction, initialState);

  return (
    <form action={action} className="space-y-5">
      <div className="space-y-1.5">
        <Label htmlFor="label" className="text-sm font-medium">
          Account label
        </Label>
        <Input
          id="label"
          name="label"
          type="text"
          placeholder="e.g. Personal, Work, Support"
          maxLength={60}
          required
          aria-invalid={state.ok === false ? true : undefined}
          aria-describedby={state.ok === false ? "label-error" : undefined}
          className="h-9"
          autoFocus
        />
        {state.ok === false && (
          <p
            id="label-error"
            role="alert"
            className="flex items-center gap-1.5 text-xs text-destructive"
          >
            <span className="inline-block size-1 rounded-full bg-destructive shrink-0" />
            {state.error}
          </p>
        )}
        <p className="text-xs text-muted-foreground">
          A short name to identify this WhatsApp account. You can have multiple accounts.
        </p>
      </div>

      <div className="flex items-center gap-3 pt-1">
        <Button
          type="submit"
          disabled={isPending}
          className="gap-2"
          size="default"
        >
          {isPending ? (
            <>
              <Loader2Icon className="size-3.5 animate-spin" />
              Adding…
            </>
          ) : (
            <>
              Add Account
              <ArrowRightIcon className="size-3.5" />
            </>
          )}
        </Button>

        <Button asChild variant="ghost" size="default">
          {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
          <Link href={"/accounts" as any}>Cancel</Link>
        </Button>
      </div>
    </form>
  );
}
