import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Input, useNavigate } from "@tailor-platform/app-shell";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { useMutation, useQuery } from "urql";
import { z } from "zod";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { graphql } from "@/graphql";
import { useToast } from "@/hooks/use-toast";

const CategoriesQuery = graphql(`
  query CategoriesForParentSelect {
    productCategories {
      edges {
        node {
          id
          name
          code
        }
      }
    }
  }
`);

const CreateCategoryMutation = graphql(`
  mutation CreateCategory($code: String!, $name: String!, $parentId: ID) {
    createCategory(code: $code, name: $name, parentId: $parentId) {
      id
      name
      code
    }
  }
`);

const formSchema = z.object({
  code: z.string().min(1, "Code is required"),
  name: z.string().min(1, "Name is required"),
  parentId: z.string().optional(),
});

type FormValues = z.infer<typeof formSchema>;

export const CreateCategoryForm = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const [, createCategory] = useMutation(CreateCategoryMutation);
  const [{ data: categoriesData }] = useQuery({ query: CategoriesQuery });
  const [submitting, setSubmitting] = useState(false);

  const categories =
    categoriesData?.productCategories?.edges?.map((edge) => ({
      id: edge.node.id,
      label: `${edge.node.name} (${edge.node.code})`,
    })) ?? [];

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: { code: "", name: "", parentId: "" },
  });

  const onSubmit = async (values: FormValues) => {
    setSubmitting(true);
    const result = await createCategory(
      {
        code: values.code,
        name: values.name,
        parentId: values.parentId || undefined,
      },
      { additionalTypenames: ["ProductCategory"] },
    );
    setSubmitting(false);

    if (result.error) {
      toast.error(result.error);
      return;
    }

    toast.success("Category created successfully");
    void navigate("..");
  };

  const onCancel = () => void navigate("..");

  return (
    <Form {...form}>
      <form onSubmit={(e) => void form.handleSubmit(onSubmit)(e)} className="max-w-md space-y-4">
        <FormField
          control={form.control}
          name="code"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Code</FormLabel>
              <FormControl>
                <Input placeholder="Enter category code" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Name</FormLabel>
              <FormControl>
                <Input placeholder="Enter category name" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="parentId"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Parent Category</FormLabel>
              <FormControl>
                <select
                  className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
                  {...field}
                >
                  <option value="">None (root category)</option>
                  {categories.map((cat) => (
                    <option key={cat.id} value={cat.id}>
                      {cat.label}
                    </option>
                  ))}
                </select>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <div className="flex gap-2">
          <Button type="submit" disabled={submitting}>
            {submitting ? "Creating..." : "Create"}
          </Button>
          <Button type="button" variant="outline" onClick={onCancel}>
            Cancel
          </Button>
        </div>
      </form>
    </Form>
  );
};
