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, TextAreaField, TextField } from "@/components/dashboard-ui";
import { queryClient, trpc, trpcClient } from "@/utils/trpc";

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

type DomainFormValues = {
  serviceId: string;
  name: string;
  expectedServerIp: string;
  remarks: string;
};

function RouteComponent() {
  const navigate = useNavigate();
  const services = useQuery(trpc.domains.serviceOptions.queryOptions());
  const createDomain = useMutation({
    mutationFn: async (values: DomainFormValues) =>
      trpcClient.domains.create.mutate({
        serviceId: values.serviceId,
        name: values.name,
        expectedServerIp: values.expectedServerIp || undefined,
        remarks: values.remarks || null,
      }),
    onSuccess: async (created) => {
      toast.success("Domain created");
      await queryClient.invalidateQueries();
      navigate({ to: "/dashboard/domains/$domainId", params: { domainId: created.id } });
    },
    onError: (error) => toast.error(error.message),
  });

  const defaultValues: DomainFormValues = {
      serviceId: "",
      name: "",
      expectedServerIp: "",
      remarks: "",
    };

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

  if (services.isLoading) {
    return <QueryStateCard title="Loading services" description="Fetching service options for the domain form." />;
  }

  if (services.isError || !services.data) {
    return <QueryStateCard title="Service options unavailable" description="Create a service before adding domains." />;
  }

  return (
    <PageSection title="Add domain" description="Create a domain or subdomain attached to a service.">
      <form
        className="grid gap-4"
        onSubmit={(e) => {
          e.preventDefault();
          e.stopPropagation();
          form.handleSubmit();
        }}
      >
        <FormCard
          title="Domain details"
          description="Expected server IP will default from the selected service's server when omitted."
          footer={
            <>
              <Button type="button" variant="ghost" onClick={() => navigate({ to: "/dashboard/domains" })}>
                Cancel
              </Button>
              <form.Subscribe selector={(state) => ({ isSubmitting: state.isSubmitting })}>
                {({ isSubmitting }) => <Button type="submit">{isSubmitting ? "Saving..." : "Save domain"}</Button>}
              </form.Subscribe>
            </>
          }
        >
          <form.Field name="serviceId">
            {(field) => (
              <TextField
                label="Service ID"
                name={field.name}
                value={field.state.value}
                onBlur={field.handleBlur}
                onChange={(e) => field.handleChange(e.target.value)}
                description={`Available: ${services.data.map((item) => `${item.name} (${item.id})`).join(", ")}`}
              />
            )}
          </form.Field>
          <div className="grid gap-4 md:grid-cols-2">
            <form.Field name="name">{(field) => <TextField label="Domain name" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} placeholder="dashboard.minmon.dev" />}</form.Field>
            <form.Field name="expectedServerIp">{(field) => <TextField label="Expected server IP" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} placeholder="203.0.113.10" />}</form.Field>
          </div>
          <form.Field name="remarks">{(field) => <TextAreaField label="Remarks" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
        </FormCard>
      </form>
    </PageSection>
  );
}
