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 { useEffect } from "react";
import { toast } from "sonner";
import { DetailCard, FormCard, PageSection, QueryStateCard, SelectField, TextAreaField, TextField } from "@/components/dashboard-ui";
import { queryClient, trpc, trpcClient } from "@/utils/trpc";

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

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

function RouteComponent() {
  const { noteId } = Route.useParams();
  const navigate = useNavigate();
  const note = useQuery(trpc.notes.byId.queryOptions({ id: noteId }));
  const servers = useQuery(trpc.servers.list.queryOptions());

  const updateNote = useMutation({
    mutationFn: async (values: NoteFormValues) =>
      trpcClient.notes.update.mutate({
        id: noteId,
        serverId: values.serverId,
        title: values.title,
        category: values.category || null,
        content: values.content,
      }),
    onSuccess: async () => {
      toast.success("Note updated");
      await queryClient.invalidateQueries();
    },
    onError: (error) => toast.error(error.message),
  });

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

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

  useEffect(() => {
    if (!note.data) {
      return;
    }

    form.reset({
      serverId: note.data.serverId,
      title: note.data.title,
      category: note.data.category ?? "",
      content: note.data.content,
    });
  }, [note.data, form]);

  if (note.isLoading || servers.isLoading) {
    return <QueryStateCard title="Loading note" description="Fetching the selected note details." />;
  }

  if (note.isError || servers.isError || !note.data || !servers.data) {
    return <QueryStateCard title="Note unavailable" description="The requested note could not be loaded." />;
  }

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

  return (
    <div className="grid gap-6">
      <PageSection title={note.data.title} description="View and edit this note.">
        <DetailCard
          title="Note summary"
          description="Current note metadata and content preview."
          rows={[
            { label: "Server", value: serverMap.get(note.data.serverId) || note.data.serverId },
            { label: "Category", value: note.data.category || "-" },
            { label: "Updated", value: new Date(note.data.updatedAt).toLocaleString() },
            { label: "Content", value: note.data.content },
          ]}
        />
      </PageSection>

      <form
        className="grid gap-4"
        onSubmit={(e) => {
          e.preventDefault();
          e.stopPropagation();
          form.handleSubmit();
        }}
      >
        <FormCard
          title="Edit note"
          description="Update note content and category."
          footer={
            <>
              <Button type="button" variant="ghost" onClick={() => navigate({ to: "/dashboard/notes" })}>
                Back
              </Button>
              <form.Subscribe selector={(state) => ({ isSubmitting: state.isSubmitting })}>
                {({ isSubmitting }) => <Button type="submit">{isSubmitting ? "Saving..." : "Save changes"}</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>
    </div>
  );
}
