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

const UpdateUserProfileMutation = graphql(`
  mutation UpdateUserProfile($userId: String!, $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 {...form}>
      <form onSubmit={(e) => void form.handleSubmit(onSubmit)(e)} className="max-w-md space-y-4">
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Name</FormLabel>
              <FormControl>
                <Input placeholder="Enter name" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Email</FormLabel>
              <FormControl>
                <Input type="email" placeholder="Enter email" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <div className="flex gap-2">
          <Button type="submit">Save</Button>
          <Button type="button" variant="outline" onClick={onCancel}>
            Cancel
          </Button>
        </div>
      </form>
    </Form>
  );
};
