"use client";

import { useState } from "react";
import { Loader2 } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { ModalShell } from "@/components/ui/ModalShell";

export interface CreateGroupModalProps {
  isOpen: boolean;
  onClose: () => void;
  onCreate: (title: string) => Promise<void>;
}

const GROUP_TITLE_REQUIRED_MSG = "Group title is required";
const CREATE_GROUP_FAILED_MSG = "Failed to create group";

/**
 * Create-group dialog, rebuilt on `ModalShell`.
 *
 * Gains the dialog accessibility (focus trap, Escape, scroll lock, aria) it had
 * none of, and drops the two blurred blobs plus the gradient header wash. The
 * submit button also no longer paints its background with an inline style — it
 * is a plain primary `Button`, so it follows the theme.
 *
 * Behaviour is unchanged: Enter submits, the title is trimmed, errors surface
 * inline, and closing resets the field.
 */
export function CreateGroupModal({ isOpen, onClose, onCreate }: CreateGroupModalProps) {
  const [newGroupTitle, setNewGroupTitle] = useState("");
  const [savingGroup, setSavingGroup] = useState(false);
  const [groupError, setGroupError] = useState<string | null>(null);

  const handleCreate = async () => {
    if (!newGroupTitle.trim()) {
      setGroupError(GROUP_TITLE_REQUIRED_MSG);
      return;
    }

    setSavingGroup(true);
    setGroupError(null);

    try {
      await onCreate(newGroupTitle.trim());
      setNewGroupTitle("");
      setGroupError(null);
    } catch (error) {
      setGroupError(error instanceof Error ? error.message : CREATE_GROUP_FAILED_MSG);
    } finally {
      setSavingGroup(false);
    }
  };

  const handleClose = () => {
    setNewGroupTitle("");
    setGroupError(null);
    onClose();
  };

  return (
    <ModalShell
      isOpen={isOpen}
      onClose={handleClose}
      size="sm"
      eyebrow="Create new group"
      title="Add group title"
      description="Groups let you organise asset definitions on the board."
      footer={
        <>
          <Button variant="outline" onClick={handleClose} disabled={savingGroup}>
            Cancel
          </Button>
          <Button onClick={handleCreate} disabled={savingGroup || !newGroupTitle.trim()}>
            {savingGroup && <Loader2 className="size-4 animate-spin" aria-hidden />}
            {savingGroup ? "Saving…" : "Create group"}
          </Button>
        </>
      }
    >
      <div className="flex flex-col gap-2">
        <Label htmlFor="group-title">Group title</Label>
        <Input
          id="group-title"
          type="text"
          value={newGroupTitle}
          onChange={(e) => {
            setNewGroupTitle(e.target.value);
            setGroupError(null);
          }}
          placeholder="e.g. Fixed income"
          aria-invalid={Boolean(groupError)}
          aria-describedby={groupError ? "group-title-error" : undefined}
          onKeyDown={(e) => {
            if (e.key === "Enter") handleCreate();
          }}
          autoFocus
        />
        {groupError && (
          <p id="group-title-error" role="alert" className="text-xs font-medium text-destructive">
            {groupError}
          </p>
        )}
      </div>
    </ModalShell>
  );
}
