import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Field, Form, Select, useNavigate } from "@tailor-platform/app-shell";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useMutation, useQuery } from "urql";
import { z } from "zod";
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
      noValidate
      onSubmit={(e) => void form.handleSubmit(onSubmit)(e)}
      className="max-w-md space-y-4"
    >
      <Controller
        control={form.control}
        name="code"
        render={({ field, fieldState }) => (
          <Field.Root name={field.name} invalid={fieldState.invalid}>
            <Field.Label>Code</Field.Label>
            <Field.Control placeholder="Enter category code" {...field} />
            {fieldState.error && <Field.Error match>{fieldState.error.message}</Field.Error>}
          </Field.Root>
        )}
      />
      <Controller
        control={form.control}
        name="name"
        render={({ field, fieldState }) => (
          <Field.Root name={field.name} invalid={fieldState.invalid}>
            <Field.Label>Name</Field.Label>
            <Field.Control placeholder="Enter category name" {...field} />
            {fieldState.error && <Field.Error match>{fieldState.error.message}</Field.Error>}
          </Field.Root>
        )}
      />
      <Controller
        control={form.control}
        name="parentId"
        render={({ field, fieldState }) => (
          <Field.Root name={field.name} invalid={fieldState.invalid}>
            <Field.Label>Parent Category</Field.Label>
            <Select
              items={categories}
              value={categories.find((c) => c.id === field.value) ?? null}
              onValueChange={(item) => field.onChange(item?.id ?? "")}
              mapItem={(cat) => ({ label: cat.label, key: cat.id })}
              placeholder="None (root category)"
            />
            {fieldState.error && <Field.Error match>{fieldState.error.message}</Field.Error>}
          </Field.Root>
        )}
      />
      <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>
  );
};
