import { Button } from "@minmon/ui/components/button";
import { useForm } from "@tanstack/react-form";
import { useMutation, useQuery } from "@tanstack/react-query";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { toast } from "sonner";
import { FormCard, PageSection, QueryStateCard, SelectField, TextAreaField, TextField } from "@/components/dashboard-ui";
import { queryClient, trpc, trpcClient } from "@/utils/trpc";

export const Route = createFileRoute("/dashboard/notes_/new")({
  component: RouteComponent,
});

type NoteFormValues = {
  serverId: string;
  title: string;
  category: string;
  content: string;
};

function RouteComponent() {
  const navigate = useNavigate();
  const servers = useQuery(trpc.servers.list.queryOptions());
  const createNote = useMutation({
    mutationFn: async (values: NoteFormValues) =>
      trpcClient.notes.create.mutate({
        serverId: values.serverId,
        title: values.title,
        category: values.category || null,
        content: values.content,
      }),
    onSuccess: async (created) => {
      toast.success("Note created");
      await queryClient.invalidateQueries();
      navigate({ to: "/dashboard/notes/$noteId", params: { noteId: created.id } });
    },
    onError: (error) => toast.error(error.message),
  });

  const defaultValues: NoteFormValues = {
      serverId: "",
      title: "",
      category: "general",
      content: "",
    };

  const form = useForm({
    defaultValues,
    onSubmit: async ({ value }) => {
      await createNote.mutateAsync(value);
    },
  });

  if (servers.isLoading) {
    return <QueryStateCard title="Loading servers" description="Fetching server options for the note form." />;
  }

  if (servers.isError || !servers.data) {
    return <QueryStateCard title="Server options unavailable" description="Add or load servers before creating notes." />;
  }

  const serverOptions = servers.data.map((item) => ({
    value: item.id,
    label: `${item.name} (${item.id})`,
  }));

  return (
    <PageSection title="New note" description="Add documentation or operational notes for a server.">
      <form
        className="grid gap-4"
        onSubmit={(e) => {
          e.preventDefault();
          e.stopPropagation();
          form.handleSubmit();
        }}
      >
        <FormCard
          title="Note details"
          description="Each note belongs to one server."
          footer={
            <>
              <Button type="button" variant="ghost" onClick={() => navigate({ to: "/dashboard/notes" })}>
                Cancel
              </Button>
              <form.Subscribe selector={(state) => ({ isSubmitting: state.isSubmitting })}>
                {({ isSubmitting }) => <Button type="submit" loading={isSubmitting}>Save note</Button>}
              </form.Subscribe>
            </>
          }
        >
          <form.Field name="serverId">
            {(field) => (
              <SelectField
                label="Server"
                name={field.name}
                value={field.state.value}
                onBlur={field.handleBlur}
                onValueChange={field.handleChange}
                description="Select the server this note belongs to."
                placeholder="Select a server"
                options={serverOptions}
              />
            )}
          </form.Field>
          <div className="grid gap-4 md:grid-cols-2">
            <form.Field name="title">{(field) => <TextField label="Title" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
            <form.Field name="category">{(field) => <TextField label="Category" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
          </div>
          <form.Field name="content">{(field) => <TextAreaField label="Content" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} className="min-h-40" />}</form.Field>
        </FormCard>
      </form>
    </PageSection>
  );
}
