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

const MeQuery = graphql(`
  query MeForEditProfile {
    me {
      id
      name
      email
    }
  }
`);

const UpdateOwnProfileMutation = graphql(`
  mutation UpdateOwnProfile($name: String!, $email: String!) {
    updateOwnProfile(name: $name, email: $email) {
      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>;

export const EditProfileForm = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({ query: MeQuery });
  const [, updateProfile] = useMutation(UpdateOwnProfileMutation);

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    values: {
      name: data?.me?.name ?? "",
      email: data?.me?.email ?? "",
    },
  });

  if (fetching) return <Loading />;

  if (error || !data?.me) {
    return (
      <ErrorFallback
        title="Failed to load profile"
        message="An error occurred while fetching your profile."
        onReset={() => reexecuteQuery({ requestPolicy: "network-only" })}
      />
    );
  }

  const onSubmit = (values: FormValues) => {
    void updateProfile(values, { additionalTypenames: ["User"] }).then((result) => {
      if (result.error) {
        toast.error(result.error);
        return;
      }
      toast.success("Profile 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>
  );
};
