import { DetailCard, FormCard, PageSection, QueryStateCard, SelectField, TextAreaField, TextField } from "@/components/dashboard-ui";
import { queryClient, trpc, trpcClient } from "@/utils/trpc";
import { Button } from "@minmon/ui/components/button";
import { StatusBadge } from "@minmon/ui/components/status-badge";
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";

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

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

function dnsStatusVariant(status: "MATCH" | "MISMATCH" | "UNRESOLVED") {
  if (status === "MATCH") return "success" as const;
  if (status === "MISMATCH") return "warning" as const;
  return "destructive" as const;
}

function RouteComponent() {
  const { domainId } = Route.useParams();
  const navigate = useNavigate();
  const domain = useQuery(trpc.domains.byId.queryOptions({ id: domainId }));
  const services = useQuery(trpc.domains.serviceOptions.queryOptions());

  const updateDomain = useMutation({
    mutationFn: async (values: DomainFormValues) =>
      trpcClient.domains.update.mutate({
        id: domainId,
        serviceId: values.serviceId || undefined,
        name: values.name,
        expectedServerIp: values.expectedServerIp || undefined,
        remarks: values.remarks || null,
      }),
    onSuccess: async () => {
      try {
        await trpcClient.domains.check.mutate({ id: domainId });
        toast.success("Domain updated and DNS re-checked");
      } catch (error) {
        toast.success("Domain updated");
        toast.error(
          error instanceof Error ? `DNS check failed: ${error.message}` : "DNS check failed",
        );
      }
      await queryClient.invalidateQueries({ queryKey: trpc.domains.byId.queryKey({ id: domainId }) });
      await queryClient.invalidateQueries({ queryKey: trpc.domains.list.queryKey() });
    },
    onError: (error) => toast.error(error.message),
  });
  const checkDns = useMutation({
    mutationFn: async () => trpcClient.domains.check.mutate({ id: domainId }),
    onSuccess: async () => {
      toast.success("DNS check completed");
      await queryClient.invalidateQueries({ queryKey: trpc.domains.byId.queryKey({ id: domainId }) });
      await queryClient.invalidateQueries({ queryKey: trpc.domains.list.queryKey() });
    },
    onError: (error) => toast.error(error.message),
  });

  const form = useForm({
    defaultValues: {
      serviceId: "",
      name: "",
      expectedServerIp: "",
      remarks: "",
    } satisfies DomainFormValues,
    onSubmit: async ({ value }) => {
      await updateDomain.mutateAsync(value);
    },
  });

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

    form.reset({
      serviceId: domain.data.serviceId,
      name: domain.data.name,
      expectedServerIp: domain.data.expectedServerIp,
      remarks: domain.data.remarks ?? "",
    });
  }, [domain.data, form]);

  if (!domain.data || !services.data) {
    if (domain.isError || services.isError) {
      return <QueryStateCard title="Domain unavailable" description="The requested domain could not be loaded." />;
    }
    return <QueryStateCard title="Loading domain" description="Fetching the selected domain details." />;
  }

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

  return (
    <div className="grid gap-6">
      <PageSection title={domain.data.name} description="View DNS check results and edit this domain record.">
        <DetailCard
          title="Domain DNS result"
          description="Stored check result and IP comparison summary."
          rows={[
            { label: "Status", value: <StatusBadge variant={dnsStatusVariant(domain.data.resolutionStatus)}>{domain.data.resolutionStatus}</StatusBadge> },
            { label: "Expected IP", value: domain.data.expectedServerIp },
            { label: "Last resolved IP", value: domain.data.lastResolvedIp || "-" },
            { label: "Resolved IPv4 list", value: domain.data.lastResolvedIps.join(", ") || "-" },
            { label: "Last checked at", value: domain.data.lastCheckedAt ? new Date(domain.data.lastCheckedAt).toLocaleString() : "-" },
            { label: "Check message", value: domain.data.lastCheckMessage || "-" },
          ]}
        />
      </PageSection>

      <form
        className="grid gap-4"
        onSubmit={(e) => {
          e.preventDefault();
          e.stopPropagation();
          form.handleSubmit();
        }}
      >
        <FormCard
          title="Edit domain"
          description="Update the attached service, expected IP, and remarks."
          footer={
            <>
              <Button type="button" variant="ghost" onClick={() => navigate({ to: "/dashboard/domains" })}>
                Back
              </Button>
              <div className="flex gap-2">
                <Button type="button" variant="outline" onClick={() => checkDns.mutate()}>
                  Check DNS
                </Button>
                <form.Subscribe selector={(state) => ({ isSubmitting: state.isSubmitting })}>
                  {({ isSubmitting }) => <Button type="submit" loading={isSubmitting}>Save changes</Button>}
                </form.Subscribe>
              </div>
            </>
          }
        >
          <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)} />}</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)} />}</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>
    </div>
  );
}
