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

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

type ServiceFormValues = {
  serverId: string;
  name: string;
  type: "web_app" | "mail" | "database" | "api" | "proxy" | "other";
  internalPort: string;
  externalPort: string;
  protocol: "http" | "https" | "tcp" | "udp" | "other";
  status: "active" | "down" | "maintenance";
  description: string;
};

function RouteComponent() {
  const { serviceId } = Route.useParams();
  const navigate = useNavigate();
  const service = useQuery(trpc.services.byId.queryOptions({ id: serviceId }));
  const servers = useQuery(trpc.servers.list.queryOptions());

  const updateService = useMutation({
    mutationFn: async (values: ServiceFormValues) =>
      trpcClient.services.update.mutate({
        id: serviceId,
        serverId: values.serverId,
        name: values.name,
        type: values.type,
        internalPort: values.internalPort ? Number(values.internalPort) : null,
        externalPort: values.externalPort ? Number(values.externalPort) : null,
        protocol: values.protocol,
        status: values.status,
        description: values.description || null,
      }),
    onSuccess: async () => {
      toast.success("Service updated");
      await queryClient.invalidateQueries();
    },
    onError: (error) => toast.error(error.message),
  });

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

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

  const defaultValues: ServiceFormValues = {
      serverId: service.data.serverId,
      name: service.data.name,
      type: service.data.type,
      internalPort: service.data.internalPort?.toString() ?? "",
      externalPort: service.data.externalPort?.toString() ?? "",
      protocol: service.data.protocol,
      status: service.data.status,
      description: service.data.description ?? "",
    };

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

  return (
    <div className="grid gap-6">
      <PageSection title={service.data.name} description="View and edit the selected service.">
        <DetailCard
          title="Service summary"
          description="Current configuration and domain relationship summary."
          rows={[
            { label: "Status", value: <StatusBadge variant={service.data.status === "active" ? "success" : service.data.status === "down" ? "destructive" : "warning"}>{service.data.status}</StatusBadge> },
            { label: "Server ID", value: service.data.serverId },
            { label: "Service type", value: service.data.type },
            { label: "Protocol", value: service.data.protocol },
            { label: "Internal port", value: service.data.internalPort ?? "-" },
            { label: "External port", value: service.data.externalPort ?? "-" },
            { label: "Related domains", value: String(service.data.summary.domains) },
          ]}
        />
      </PageSection>

      <form
        className="grid gap-4"
        onSubmit={(e) => {
          e.preventDefault();
          e.stopPropagation();
          form.handleSubmit();
        }}
      >
        <FormCard
          title="Edit service"
          description="Update ports, protocol, status, and description."
          footer={
            <>
              <Button type="button" variant="ghost" onClick={() => navigate({ to: "/dashboard/services" })}>
                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) => (
              <TextField
                label="Server ID"
                name={field.name}
                value={field.state.value}
                onBlur={field.handleBlur}
                onChange={(e) => field.handleChange(e.target.value)}
                description={`Available: ${servers.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="Service name" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
            <form.Field name="type">{(field) => <TextField label="Service type" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value as ServiceFormValues["type"])} />}</form.Field>
            <form.Field name="internalPort">{(field) => <TextField label="Internal port" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
            <form.Field name="externalPort">{(field) => <TextField label="External port" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
            <form.Field name="protocol">{(field) => <TextField label="Protocol" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value as ServiceFormValues["protocol"])} />}</form.Field>
            <form.Field name="status">{(field) => <TextField label="Status" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value as ServiceFormValues["status"])} />}</form.Field>
          </div>
          <form.Field name="description">{(field) => <TextAreaField label="Description" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
        </FormCard>
      </form>
    </div>
  );
}
