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/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) => {
      try {
        await trpcClient.domains.check.mutate({ id: created.id });
        toast.success("Domain created and DNS checked");
      } catch (error) {
        toast.success("Domain created");
        toast.error(
          error instanceof Error ? `DNS check failed: ${error.message}` : "DNS check failed",
        );
      }
      await queryClient.invalidateQueries({ queryKey: trpc.domains.list.queryKey() });
      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." />;
  }

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

  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" loading={isSubmitting}>Save domain</Button>}
              </form.Subscribe>
            </>
          }
        >
          <form.Field name="serviceId">
            {(field) => (
              <SelectField
                label="Service"
                name={field.name}
                value={field.state.value}
                onBlur={field.handleBlur}
                onValueChange={field.handleChange}
                description="Select the service this domain belongs to."
                placeholder="Select a service"
                options={serviceOptions}
              />
            )}
          </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>
  );
}
