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

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

type ServerFormValues = {
  name: string;
  primaryIpAddress: string;
  secondaryIpAddress: string;
  operatingSystem: string;
  location: string;
  provider: string;
  description: string;
  status: "active" | "maintenance" | "inactive";
};

const serverStatusOptions = [
  { value: "active", label: "Active" },
  { value: "maintenance", label: "Maintenance" },
  { value: "inactive", label: "Inactive" },
] as const;

function RouteComponent() {
  const { serverId } = Route.useParams();
  const navigate = useNavigate();
  const server = useQuery(trpc.servers.byId.queryOptions({ id: serverId }));
  const notes = useQuery(trpc.notes.list.queryOptions({ serverId }));

  const updateServer = useMutation({
    mutationFn: async (values: ServerFormValues) =>
      trpcClient.servers.update.mutate({
        id: serverId,
        ...values,
        secondaryIpAddress: values.secondaryIpAddress || null,
        operatingSystem: values.operatingSystem || null,
        location: values.location || null,
        provider: values.provider || null,
        description: values.description || null,
      }),
    onSuccess: async () => {
      toast.success("Server updated");
      await queryClient.invalidateQueries();
    },
    onError: (error) => toast.error(error.message),
  });

  const defaultValues: ServerFormValues = {
      name: "",
      primaryIpAddress: "",
      secondaryIpAddress: "",
      operatingSystem: "",
      location: "",
      provider: "",
      description: "",
      status: "active",
    };

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

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

    form.reset({
      name: server.data.name,
      primaryIpAddress: server.data.primaryIpAddress,
      secondaryIpAddress: server.data.secondaryIpAddress ?? "",
      operatingSystem: server.data.operatingSystem ?? "",
      location: server.data.location ?? "",
      provider: server.data.provider ?? "",
      description: server.data.description ?? "",
      status: server.data.status,
    });
  }, [server.data, form]);

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

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

  return (
    <div className="grid gap-6">
      <PageSection title={server.data.name} description="View and edit the selected server.">
        <DetailCard
          title="Server summary"
          description="Relationship and status summary for this server."
          rows={[
            { label: "Status", value: <StatusBadge variant={server.data.status === "active" ? "success" : server.data.status === "maintenance" ? "warning" : "neutral"}>{server.data.status}</StatusBadge> },
            { label: "Primary IP", value: server.data.primaryIpAddress },
            { label: "Secondary IP", value: server.data.secondaryIpAddress || "-" },
            { label: "Operating system", value: server.data.operatingSystem || "-" },
            { label: "Location", value: server.data.location || "-" },
            { label: "Provider", value: server.data.provider || "-" },
            { label: "Services", value: String(server.data.summary.services) },
            { label: "Notes", value: String(server.data.summary.notes) },
          ]}
        />
      </PageSection>

      {notes.isLoading ? (
        <QueryStateCard title="Loading server notes" description="Fetching notes attached to this server." />
      ) : notes.isError || !notes.data ? (
        <QueryStateCard title="Server notes unavailable" description="The notes for this server could not be loaded." />
      ) : (
        <PageSection
          title="Server notes"
          description="Notes and internal documentation attached to this server."
          action={
            <Link to="/dashboard/notes/new">
              <Button variant="outline">New note</Button>
            </Link>
          }
        >
          <ResourceListCard
            title="Attached notes"
            description="Review server-specific documentation without leaving this detail page."
            columns={[
              {
                key: "title",
                header: "Title",
                render: (item: (typeof notes.data)[number]) => (
                  <div className="grid gap-1">
                    <Link to="/dashboard/notes/$noteId" params={{ noteId: item.id }} className="font-medium hover:underline">
                      {item.title}
                    </Link>
                    <span className="text-xs text-muted-foreground line-clamp-2">{item.content}</span>
                  </div>
                ),
              },
              {
                key: "category",
                header: "Category",
                render: (item: (typeof notes.data)[number]) => item.category || "-",
              },
              {
                key: "updatedAt",
                header: "Updated",
                render: (item: (typeof notes.data)[number]) => new Date(item.updatedAt).toLocaleString(),
              },
            ]}
            items={notes.data}
            emptyTitle="No notes for this server"
            emptyDescription="Add a note to document maintenance, incidents, or internal server context."
          />
        </PageSection>
      )}

      <form
        className="grid gap-4"
        onSubmit={(e) => {
          e.preventDefault();
          e.stopPropagation();
          form.handleSubmit();
        }}
      >
        <FormCard
          title="Edit server"
          description="Update server information and keep the dashboard records current."
          footer={
            <>
              <Button type="button" variant="ghost" onClick={() => navigate({ to: "/dashboard/servers" })}>
                Back
              </Button>
              <form.Subscribe selector={(state) => ({ isSubmitting: state.isSubmitting })}>
                {({ isSubmitting }) => <Button type="submit" loading={isSubmitting}>Save changes</Button>}
              </form.Subscribe>
            </>
          }
        >
          <div className="grid gap-4 md:grid-cols-2">
            <form.Field name="name">{(field) => <TextField label="Server name" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
            <form.Field name="primaryIpAddress">{(field) => <TextField label="Primary IP address" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
            <form.Field name="secondaryIpAddress">{(field) => <TextField label="Secondary IP address" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
            <form.Field name="operatingSystem">{(field) => <TextField label="Operating system" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
            <form.Field name="location">{(field) => <TextField label="Location" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</form.Field>
            <form.Field name="provider">{(field) => <TextField label="Provider" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />}</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 ServerFormValues["status"])} placeholder="Select server status" options={[...serverStatusOptions]} />}</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>
  );
}
