import { useState } from "react";
import { X, RefreshCw } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { PRIMARY_COLOR } from "@/lib/common";

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";

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();
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 px-4 py-6 backdrop-blur-sm"
      onClick={handleClose}
    >
      <div
        className="relative w-full max-w-md overflow-hidden rounded-lg border border-white/30 bg-white/95 shadow-2xl ring-1 ring-black/10"
        onClick={(e) => e.stopPropagation()}
      >
        <div
          className="absolute -right-20 -top-24 h-48 w-48 rounded-lg blur-3xl"
          style={{ backgroundColor: `${PRIMARY_COLOR}1A` }}
        />
        <div
          className="absolute -bottom-24 -left-16 h-48 w-48 rounded-lg blur-3xl"
          style={{ backgroundColor: `${PRIMARY_COLOR}26` }}
        />

        <div
          className="relative flex items-start justify-between border-b border-slate-100 px-6 py-5"
          style={{
            background: `linear-gradient(to right, ${PRIMARY_COLOR}0D, white, white)`,
          }}
        >
          <div>
            <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">
              Create New Group
            </p>
            <h2 className="mt-1 text-2xl font-semibold text-slate-800">
              Add Group Title
            </h2>
            <p className="mt-1 text-xs font-medium text-slate-500">
              Enter a title for the new group
            </p>
          </div>
          <button
            type="button"
            onClick={handleClose}
            className="rounded-lg border border-slate-200 bg-white/70 p-2 text-slate-400 shadow-sm transition hover:-translate-y-0.5 hover:border-red-300 hover:bg-red-50 hover:text-red-500"
            aria-label="Close modal"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        <div className="relative px-6 pb-6 pt-5">
          <div className="space-y-4">
            <div>
              <label
                htmlFor="group-title"
                className="block text-sm font-medium text-slate-700 mb-2"
              >
                Group Title
              </label>
              <Input
                id="group-title"
                type="text"
                value={newGroupTitle}
                onChange={(e) => {
                  setNewGroupTitle(e.target.value);
                  setGroupError(null);
                }}
                placeholder="Enter group title"
                className="w-full"
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    handleCreate();
                  }
                }}
                autoFocus
              />
              {groupError ? (
                <p className="mt-2 text-sm text-red-600">{groupError}</p>
              ) : null}
            </div>

            <div className="flex gap-3 pt-2">
              <Button
                onClick={handleCreate}
                disabled={savingGroup || !newGroupTitle.trim()}
                className="flex-1 text-white disabled:opacity-50"
                style={{ backgroundColor: PRIMARY_COLOR }}
              >
                {savingGroup ? (
                  <>
                    <RefreshCw className="h-4 w-4 animate-spin" />
                    Saving...
                  </>
                ) : (
                  "Create Group"
                )}
              </Button>
              <Button
                onClick={handleClose}
                variant="outline"
                className="flex-1"
                disabled={savingGroup}
              >
                Cancel
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
