"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { GROUP_NAME_MAX_LENGTH } from "@/lib/constants";

export function CreateGroupForm() {
  const [name, setName] = useState("");
  const queryClient = useQueryClient();
  const router = useRouter();

  const createGroup = useMutation({
    mutationFn: async (groupName: string) => {
      const res = await fetch("/api/groups", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: groupName }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to create group");
      }
      return res.json();
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ["groups"] });
      setName("");
      const id = data?.group?.id;
      if (id) router.push(`/list/${id}`);
    },
  });

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const trimmed = name.trim();
    if (!trimmed) return;
    createGroup.mutate(trimmed);
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-4">
      <div>
        <label htmlFor="group-name" className="block text-sm font-medium mb-1">
          Group Name
        </label>
        <input
          id="group-name"
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          maxLength={GROUP_NAME_MAX_LENGTH}
          placeholder="e.g., Movie Night Crew"
          required
          className="w-full rounded-md border border-gray-300 bg-transparent px-3 py-2 text-sm placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-gray-700"
        />
        <p className="mt-1 text-xs text-gray-500">
          {name.length}/{GROUP_NAME_MAX_LENGTH} characters
        </p>
      </div>

      {createGroup.error && (
        <p className="text-sm text-red-500" role="alert">
          {createGroup.error.message}
        </p>
      )}

      <button
        type="submit"
        disabled={createGroup.isPending || createGroup.isSuccess || !name.trim()}
        className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
      >
        {createGroup.isPending ? "Creating..." : "Create Group"}
      </button>
    </form>
  );
}
