import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Field, Form, useNavigate } from "@tailor-platform/app-shell";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useMutation } from "urql";
import { z } from "zod";
import { graphql, type FragmentOf, readFragment } from "@/graphql";
import { useToast } from "@/hooks/use-toast";

export const EditCategoryFormFragment = graphql(`
  fragment EditCategoryForm on ProductCategory {
    id
    name
  }
`);

const UpdateCategoryMutation = graphql(`
  mutation UpdateCategory($id: ID!, $name: String!) {
    updateCategory(id: $id, name: $name) {
      id
      name
    }
  }
`);

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

type FormValues = z.infer<typeof formSchema>;

interface EditCategoryFormProps {
  category: FragmentOf<typeof EditCategoryFormFragment>;
}

export const EditCategoryForm = ({ category: categoryFragment }: EditCategoryFormProps) => {
  const category = readFragment(EditCategoryFormFragment, categoryFragment);
  const navigate = useNavigate();
  const toast = useToast();
  const [submitting, setSubmitting] = useState(false);
  const [, updateCategory] = useMutation(UpdateCategoryMutation);

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: category.name,
    },
  });

  const onSubmit = async (values: FormValues) => {
    setSubmitting(true);
    const result = await updateCategory(
      { id: category.id, name: values.name },
      { additionalTypenames: ["ProductCategory"] },
    );
    setSubmitting(false);

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

    toast.success("Category updated 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="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>
        )}
      />
      <div className="flex gap-2">
        <Button type="submit" disabled={submitting}>
          {submitting ? "Saving..." : "Save"}
        </Button>
        <Button type="button" variant="outline" onClick={onCancel}>
          Cancel
        </Button>
      </div>
    </Form>
  );
};
