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/services_/new")({
  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;
};

const serviceTypeOptions = [
  { value: "web_app", label: "Web app" },
  { value: "mail", label: "Mail" },
  { value: "database", label: "Database" },
  { value: "api", label: "API" },
  { value: "proxy", label: "Proxy" },
  { value: "other", label: "Other" },
] as const;

const serviceProtocolOptions = [
  { value: "http", label: "HTTP" },
  { value: "https", label: "HTTPS" },
  { value: "tcp", label: "TCP" },
  { value: "udp", label: "UDP" },
  { value: "other", label: "Other" },
] as const;

const serviceStatusOptions = [
  { value: "active", label: "Active" },
  { value: "down", label: "Down" },
  { value: "maintenance", label: "Maintenance" },
] as const;

function RouteComponent() {
  const navigate = useNavigate();
  const servers = useQuery(trpc.servers.list.queryOptions());
  const createService = useMutation({
    mutationFn: async (values: ServiceFormValues) =>
      trpcClient.services.create.mutate({
        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 (created) => {
      toast.success("Service created");
      await queryClient.invalidateQueries();
      navigate({ to: "/dashboard/services/$serviceId", params: { serviceId: created.id } });
    },
    onError: (error) => toast.error(error.message),
  });

  const defaultValues: ServiceFormValues = {
      serverId: "",
      name: "",
      type: "web_app",
      internalPort: "",
      externalPort: "",
      protocol: "http",
      status: "active",
      description: "",
    };

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

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

  if (servers.isError || !servers.data) {
    return <QueryStateCard title="Server options unavailable" description="Add or load servers before creating a service." />;
  }

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

  return (
    <PageSection title="Add service" description="Create a new service under an existing server.">
      <form
        className="grid gap-4"
        onSubmit={(e) => {
          e.preventDefault();
          e.stopPropagation();
          form.handleSubmit();
        }}
      >
        <FormCard
          title="Service details"
          description="A service must belong to a server."
          footer={
            <>
              <Button type="button" variant="ghost" onClick={() => navigate({ to: "/dashboard/services" })}>
                Cancel
              </Button>
              <form.Subscribe selector={(state) => ({ isSubmitting: state.isSubmitting })}>
                {({ isSubmitting }) => <Button type="submit" loading={isSubmitting}>Save service</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 that owns this service."
                placeholder="Select a server"
                options={serverOptions}
              />
            )}
          </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) => <SelectField label="Service type" name={field.name} value={field.state.value} onBlur={field.handleBlur} onValueChange={(value) => field.handleChange(value as ServiceFormValues["type"])} placeholder="Select service type" options={[...serviceTypeOptions]} />}</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) => <SelectField label="Protocol" name={field.name} value={field.state.value} onBlur={field.handleBlur} onValueChange={(value) => field.handleChange(value as ServiceFormValues["protocol"])} placeholder="Select protocol" options={[...serviceProtocolOptions]} />}</form.Field>
            <form.Field name="status">{(field) => <SelectField label="Status" name={field.name} value={field.state.value} onBlur={field.handleBlur} onValueChange={(value) => field.handleChange(value as ServiceFormValues["status"])} placeholder="Select service status" options={[...serviceStatusOptions]} />}</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>
    </PageSection>
  );
}
