import { useState, type FormEvent } from "react";
import { useNavigate } from "react-router";
import { useQueryClient } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";

import { client } from "@/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";

export function CreateWorkspaceDialog({
  children,
}: {
  children: React.ReactNode;
}) {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [open, setOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError("");
    setSubmitting(true);

    const form = new FormData(event.currentTarget);
    const name = form.get("name") as string;
    const description = (form.get("description") as string) || null;

    if (!name.trim()) {
      setError("Workspace name is required.");
      setSubmitting(false);
      return;
    }

    try {
      await client.workspaceCreateWorkspace({
        name: name.trim(),
        description,
      });
      await queryClient.invalidateQueries({ queryKey: ["workspace", "my"] });
      setOpen(false);
      navigate(`/${name.trim()}/repos`);
    } catch (requestError) {
      setError(
        requestError instanceof Error
          ? requestError.message
          : "Failed to create workspace. Please try again."
      );
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger render={children as React.ReactElement} />
      <DialogContent className="sm:max-w-md p-6">
        <DialogHeader>
          <DialogTitle className="text-lg font-semibold text-foreground">
            Create a new workspace
          </DialogTitle>
          <DialogDescription className="text-sm text-muted-foreground">
            Workspaces organize your projects, repositories, and team collaboration.
          </DialogDescription>
        </DialogHeader>

        <form
          className="mt-6 space-y-5"
          onSubmit={(event) => void handleSubmit(event)}
        >
          <div className="space-y-2">
            <Label className="text-sm font-semibold text-foreground" htmlFor="wk-name">
              Name
            </Label>
            <Input
              autoComplete="off"
              className="h-11 rounded-xl border-input bg-background text-sm"
              id="wk-name"
              name="name"
              placeholder="e.g. my-project"
              required
              autoFocus
            />
            <p className="text-xs text-muted-foreground/70">
              This will be used as your workspace URL. Use lowercase letters, numbers, and hyphens.
            </p>
          </div>

          <div className="space-y-2">
            <Label className="text-sm font-semibold text-foreground" htmlFor="wk-description">
              Description
            </Label>
            <Textarea
              autoComplete="off"
              className="min-h-24 rounded-xl border-input bg-background text-sm"
              id="wk-description"
              name="description"
              placeholder="What is this workspace about?"
            />
          </div>

          {error && (
            <p aria-live="polite" className="rounded-xl bg-destructive/10 px-4 py-3 text-sm font-medium text-destructive">
              {error}
            </p>
          )}

          <DialogFooter className="-mx-6 -mb-6 rounded-b-xl border-t border-border bg-muted/30 px-6 py-4 sm:flex-row sm:justify-end">
            <Button
              className="h-10 rounded-xl px-5 text-sm"
              disabled={submitting}
              type="submit"
            >
              {submitting ? <Loader2 className="size-5 animate-spin" /> : "Create workspace"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}