import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Field, Form, useNavigate } from "@tailor-platform/app-shell";
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";

const UpdateUserProfileMutation = graphql(`
  mutation UpdateUserProfile($userId: ID!, $name: String!, $email: String!) {
    updateUserProfile(userId: $userId, name: $name, email: $email) {
      id
      name
      email
    }
  }
`);

export const EditUserFormFragment = graphql(`
  fragment EditUserForm on User {
    id
    name
    email
  }
`);

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

type FormValues = z.infer<typeof formSchema>;

interface EditUserFormProps {
  user: FragmentOf<typeof EditUserFormFragment>;
}

export const EditUserForm = ({ user: userFragment }: EditUserFormProps) => {
  const user = readFragment(EditUserFormFragment, userFragment);
  const navigate = useNavigate();
  const toast = useToast();
  const [, updateUserProfile] = useMutation(UpdateUserProfileMutation);

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

  const onSubmit = (values: FormValues) => {
    void updateUserProfile({ userId: user.id, ...values }, { additionalTypenames: ["User"] }).then(
      (result) => {
        if (result.error) {
          toast.error(result.error);
          return;
        }
        toast.success("User 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 name" {...field} />
            {fieldState.error && <Field.Error match>{fieldState.error.message}</Field.Error>}
          </Field.Root>
        )}
      />
      <Controller
        control={form.control}
        name="email"
        render={({ field, fieldState }) => (
          <Field.Root name={field.name} invalid={fieldState.invalid}>
            <Field.Label>Email</Field.Label>
            <Field.Control
              inputMode="email"
              autoComplete="email"
              placeholder="Enter email"
              {...field}
            />
            {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>
  );
};
