"use client";

import { useActionState, useEffect, useRef } from "react";
import { Link2, Loader2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { requestConnectionAction } from "@/lib/appwrite/connection-actions";
import { initialConnectionRequestState } from "@/lib/appwrite/connection-types";

export function ConnectionRequestForm({ counterpartLabel }: { counterpartLabel: string }) {
  const [state, formAction, isPending] = useActionState(
    requestConnectionAction,
    initialConnectionRequestState,
  );
  const formRef = useRef<HTMLFormElement>(null);

  useEffect(() => {
    if (state.ok) {
      toast.success("Bağlantı talebi gönderildi.");
      formRef.current?.reset();
    } else if (state.error) {
      toast.error(state.error);
    }
  }, [state]);

  return (
    <form ref={formRef} action={formAction} className="grid gap-3 sm:grid-cols-[1fr_auto] sm:items-end">
      <div className="grid gap-2">
        <Label htmlFor="memberNumber">{counterpartLabel.charAt(0).toUpperCase() + counterpartLabel.slice(1)} bağlantı kodu</Label>
        <Input
          id="memberNumber"
          name="memberNumber"
          type="text"
          placeholder="6 hane"
          maxLength={12}
          autoCapitalize="characters"
          autoComplete="off"
          required
          style={{ textTransform: "uppercase", letterSpacing: "0.3em" }}
          className="font-mono"
        />
      </div>
      <Button type="submit" disabled={isPending}>
        {isPending ? (
          <>
            <Loader2 className="size-4 animate-spin" />
            Gönderiliyor...
          </>
        ) : (
          <>
            <Link2 className="size-4" />
            Talep gönder
          </>
        )}
      </Button>
    </form>
  );
}
