"use client";

import { Plus } from "lucide-react";
import { invoke } from "@tauri-apps/api/core";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { AnimatePresence, motion } from "motion/react";
import { Field, FieldGroup, FieldLabel } from "./ui/field";
import { Label } from "./ui/label";
import { Input } from "./ui/input";
import { Textarea } from "./ui/textarea";
import { Checkbox } from "./ui/checkbox";
import { useState, SubmitEvent } from "react";
import { useQueryClient } from "@tanstack/react-query";

export default function PlusButton() {
  const [differentAddr, setDifferentAddr] = useState(false);
  const [open, setOpen] = useState(false);
  const queryclient = useQueryClient();

  // 1. Properly set default values inside the initial state
  const [name, setName] = useState("Kubernetes");
  const [address, setAddress] = useState("192.168.1.10");
  const [description, setDescription] = useState<string>("");
  const [sshAddr, setSSHAddr] = useState<string>("192.168.1.10");

  const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
    e.preventDefault();

    console.log("Form submission triggered");

    if (!name.trim() || !address.trim()) return;

    let tmp_description: string | undefined = undefined;
    let tmp_ssh: string | undefined = undefined;

    if (description.trim()) tmp_description = description.trim();
    if (differentAddr && sshAddr.trim()) tmp_ssh = sshAddr.trim();

    try {
      let app = await invoke("new_app", {
        name: name.trim(),
        address: address.trim(),
        description: tmp_description,
        sshAddress: tmp_ssh,
      });

      console.log("Tauri response:", app);

      setOpen(false);

      queryclient.invalidateQueries({
        queryKey: ["apps"],
      });
    } catch (err) {
      console.error("Failed to invoke new_app:", err);
    }
  };

  return (
    <Dialog onOpenChange={(e) => setOpen(e.valueOf())} open={open}>
      <DialogTrigger asChild>
        <motion.button
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          transition={{ type: "spring", stiffness: 300, damping: 20 }}
          className="absolute right-3 bottom-3 bg-emerald-700 p-2 rounded-full"
        >
          <Plus className="w-8 h-8 text-white" />
        </motion.button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-sm">
        <form onSubmit={handleSubmit}>
          <DialogHeader>
            <DialogTitle>Create Service</DialogTitle>
            <DialogDescription>
              Create a new service. Click save when you're finished.
            </DialogDescription>
          </DialogHeader>
          <FieldGroup>
            <Field>
              <Label htmlFor="name">Service Name</Label>
              <Input
                id="name"
                name="name"
                value={name}
                // Removed trimming on change to allow spaces while typing
                onChange={(e) => setName(e.target.value)}
              />
            </Field>
            <Field>
              <Label htmlFor="address">IP Address</Label>
              <Input
                id="address"
                name="address"
                value={address}
                onChange={(e) => setAddress(e.target.value)}
              />
            </Field>
            <Field>
              <Label htmlFor="description">
                Description{" "}
                <span className="text-sm text-black/25">(Optional)</span>
              </Label>
              <Textarea
                id="description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                name="description"
              />
            </Field>
            <Field orientation="horizontal">
              <Checkbox
                checked={differentAddr}
                onCheckedChange={(checked: boolean | "indeterminate") =>
                  setDifferentAddr(checked === true)
                }
                id="toggle-ssh"
                name="toggle-ssh"
              />
              <FieldLabel htmlFor="toggle-ssh">
                Use Different URL for SSH
              </FieldLabel>
            </Field>
            <AnimatePresence>
              {differentAddr && (
                <motion.div
                  key={"ssh-addr-field"}
                  initial={{ opacity: 0, y: -8 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -8 }}
                  transition={{ duration: 0.3 }}
                >
                  <Field>
                    <Label htmlFor="ssh-addr">SSH Address</Label>
                    <Input
                      id="ssh-addr"
                      name="ssh-addr"
                      value={sshAddr}
                      onChange={(e) => setSSHAddr(e.target.value)}
                    />
                  </Field>
                </motion.div>
              )}
            </AnimatePresence>
          </FieldGroup>
          <DialogFooter>
            <DialogClose asChild>
              <Button type="button" variant="outline">
                Cancel
              </Button>
            </DialogClose>
            <Button type="submit">Save changes</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
