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

const UnitsQuery = graphql(`
  query UnitsForEditProductForm {
    units {
      edges {
        node {
          id
          name
          symbol
        }
      }
    }
  }
`);

const UpdateProductMutation = graphql(`
  mutation UpdateProduct($id: ID!, $name: String, $description: String, $unitId: ID) {
    updateProduct(id: $id, name: $name, description: $description, unitId: $unitId) {
      id
      name
    }
  }
`);

export const EditProductFormFragment = graphql(`
  fragment EditProductForm on Product {
    id
    name
    description
    unitId
    status
  }
`);

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

type FormValues = z.infer<typeof formSchema>;

interface EditProductFormProps {
  product: FragmentOf<typeof EditProductFormFragment>;
}

export const EditProductForm = ({ product: productFragment }: EditProductFormProps) => {
  const product = readFragment(EditProductFormFragment, productFragment);
  const navigate = useNavigate();
  const toast = useToast();
  const [, updateProduct] = useMutation(UpdateProductMutation);
  const [{ data: unitsData }] = useQuery({ query: UnitsQuery });

  const units =
    unitsData?.units?.edges?.map((edge) => {
      const node = edge.node;
      return { id: node.id, label: `${node.name} (${node.symbol})` };
    }) ?? [];

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: product.name,
      description: product.description ?? "",
      unitId: product.unitId,
    },
  });

  const isDraft = product.status === "DRAFT";

  const onSubmit = (values: FormValues) => {
    void updateProduct(
      {
        id: product.id,
        name: values.name,
        description: values.description?.trim() ? values.description : null,
        // UoM can only be changed in DRAFT status
        unitId: isDraft && values.unitId !== product.unitId ? values.unitId : undefined,
      },
      { additionalTypenames: ["Product"] },
    ).then((result) => {
      if (result.error) {
        toast.error(result.error);
        return;
      }
      toast.success("Product 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 product name" {...field} />
            {fieldState.error && <Field.Error match>{fieldState.error.message}</Field.Error>}
          </Field.Root>
        )}
      />
      <Controller
        control={form.control}
        name="description"
        render={({ field, fieldState }) => (
          <Field.Root name={field.name} invalid={fieldState.invalid}>
            <Field.Label>Description</Field.Label>
            <Field.Control placeholder="Enter product description (optional)" {...field} />
            {fieldState.error && <Field.Error match>{fieldState.error.message}</Field.Error>}
          </Field.Root>
        )}
      />
      <Controller
        control={form.control}
        name="unitId"
        render={({ field, fieldState }) => (
          <Field.Root name={field.name} invalid={fieldState.invalid} disabled={!isDraft}>
            <Field.Label>Unit</Field.Label>
            <Select
              disabled={!isDraft}
              items={units}
              value={units.find((u) => u.id === field.value) ?? null}
              onValueChange={(item) => field.onChange(item?.id ?? "")}
              mapItem={(u) => ({ label: u.label, key: u.id })}
              placeholder="Select a unit"
            />
            {fieldState.error && <Field.Error match>{fieldState.error.message}</Field.Error>}
          </Field.Root>
        )}
      />
      <div className="flex gap-2">
        <Button type="submit">Save</Button>
        <Button type="button" variant="outline" onClick={onCancel}>
          Cancel
        </Button>
      </div>
    </Form>
  );
};
