"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
  ResizableDialog,
  ResizableDialogContent,
  ResizableDialogHeader,
  ResizableDialogTitle,
  ResizableDialogDescription,
  ResizableDialogFooter,
} from "@/components/ui/resizable-dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Loader2, AlertCircle } from "lucide-react";

interface YardLayoutCreateModalProps {
  isOpen: boolean;
  onClose: () => void;
  onCreate: (name: string) => Promise<void>;
}

export default function YardLayoutCreateModal({ isOpen, onClose, onCreate }: YardLayoutCreateModalProps) {
  const [name, setName] = useState("");
  const [isCreating, setIsCreating] = useState(false);
  const [error, setError] = useState("");

  // 생성 실행
  const handleCreate = async () => {
    if (!name.trim()) {
      setError("야드 이름을 입력하세요");
      return;
    }

    setIsCreating(true);
    setError("");

    try {
      await onCreate(name.trim());
      setName("");
    } catch (error: any) {
      console.error("야드 생성 실패:", error);
      setError(error.message || "야드 생성에 실패했습니다");
    } finally {
      setIsCreating(false);
    }
  };

  // 모달 닫기
  const handleClose = () => {
    if (isCreating) return;
    setName("");
    setError("");
    onClose();
  };

  // Enter 키 처리
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleCreate();
    }
  };

  return (
    <ResizableDialog open={isOpen} onOpenChange={handleClose}>
      <ResizableDialogContent className="sm:max-w-[500px]" onPointerDown={(e) => e.stopPropagation()}>
        <ResizableDialogHeader>
          <div className="flex items-center gap-2">
            <ResizableDialogTitle>새 야드 생성</ResizableDialogTitle>
            <ResizableDialogDescription>야드 이름을 입력하세요</ResizableDialogDescription>
          </div>
        </ResizableDialogHeader>

        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="yard-name">
              야드 이름 <span className="text-destructive">*</span>
            </Label>
            <Input
              id="yard-name"
              value={name}
              onChange={(e) => {
                setName(e.target.value);
                setError("");
              }}
              onKeyDown={handleKeyDown}
              placeholder="예: A구역, 1번 야드"
              disabled={isCreating}
              autoFocus
            />
          </div>

          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}
        </div>

        <ResizableDialogFooter>
          <Button variant="outline" onClick={handleClose} disabled={isCreating}>
            취소
          </Button>
          <Button onClick={handleCreate} disabled={!name.trim() || isCreating}>
            {isCreating ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                생성 중...
              </>
            ) : (
              "생성"
            )}
          </Button>
        </ResizableDialogFooter>
      </ResizableDialogContent>
    </ResizableDialog>
  );
}
