"use client";

import { useActionState, useEffect, useRef, useState } from "react";
import { Check, Copy, Loader2, UserPlus } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { inviteMemberAction } from "@/lib/appwrite/team-actions";
import { initialInviteState } from "@/lib/appwrite/team-types";

export function InviteForm() {
  const [state, formAction, isPending] = useActionState(inviteMemberAction, initialInviteState);
  const [copied, setCopied] = useState(false);
  const formRef = useRef<HTMLFormElement>(null);

  useEffect(() => {
    if (state.ok && formRef.current) {
      formRef.current.reset();
    }
  }, [state.ok, state.shortUrl]);

  const copy = async () => {
    if (!state.shortUrl) return;
    try {
      await navigator.clipboard.writeText(state.shortUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      /* ignore */
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>Üye davet et</CardTitle>
        <CardDescription>
          Email ve rol girin, oluşturulan kısa linki kopyalayıp davet edeceğiniz kişiye gönderin.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form ref={formRef} action={formAction} className="grid gap-4 md:grid-cols-[1fr_180px_auto]">
          <div className="grid gap-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              name="email"
              type="email"
              placeholder="ornek@firma.com"
              required
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="role">Rol</Label>
            <Select name="role" defaultValue="member">
              <SelectTrigger id="role">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="member">Üye</SelectItem>
                <SelectItem value="admin">Yönetici</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="flex items-end">
            <Button type="submit" disabled={isPending} className="w-full md:w-auto">
              {isPending ? (
                <>
                  <Loader2 className="size-4 animate-spin" />
                  Gönderiliyor...
                </>
              ) : (
                <>
                  <UserPlus className="size-4" />
                  Davet et
                </>
              )}
            </Button>
          </div>
        </form>

        {state.error && (
          <p className="text-destructive mt-3 text-sm" role="alert">
            {state.error}
          </p>
        )}

        {state.ok && state.shortUrl && (
          <div className="bg-muted/50 mt-4 flex flex-col gap-2 rounded-md border p-3">
            {state.message && (
              <p className="text-muted-foreground text-xs">{state.message}</p>
            )}
            <div className="flex items-center gap-2">
              <Input value={state.shortUrl} readOnly className="font-mono text-xs" />
              <Button type="button" variant="outline" size="sm" onClick={copy}>
                {copied ? <Check className="size-4" /> : <Copy className="size-4" />}
                {copied ? "Kopyalandı" : "Kopyala"}
              </Button>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
