"use client";

import React, { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { TableCategoryValue } from "@/types/tableCategoryValue";

interface CategoryValueAddDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onAdd: (value: TableCategoryValue) => void;
  columnLabel: string;
}

export const CategoryValueAddDialog: React.FC<
  CategoryValueAddDialogProps
> = ({ open, onOpenChange, onAdd, columnLabel }) => {
  const [valueLabel, setValueLabel] = useState("");
  const [description, setDescription] = useState("");

  // 라벨에서 코드 자동 생성
  const generateCode = (label: string): string => {
    // 한글을 영문으로 변환하거나, 영문/숫자만 추출하여 대문자로
    const cleaned = label
      .replace(/[^a-zA-Z0-9가-힣\s]/g, "") // 특수문자 제거
      .trim()
      .toUpperCase();
    
    // 영문이 있으면 영문만, 없으면 타임스탬프 기반
    const englishOnly = cleaned.replace(/[^A-Z0-9\s]/g, "").replace(/\s+/g, "_");
    
    if (englishOnly.length > 0) {
      return englishOnly.substring(0, 20); // 최대 20자
    }
    
    // 영문이 없으면 CATEGORY_TIMESTAMP 형식
    return `CATEGORY_${Date.now().toString().slice(-6)}`;
  };

  const handleSubmit = () => {
    if (!valueLabel.trim()) {
      return;
    }

    const valueCode = generateCode(valueLabel);

    onAdd({
      tableName: "",
      columnName: "",
      valueCode,
      valueLabel: valueLabel.trim(),
      description: description.trim(),
      color: "#3b82f6",
      isDefault: false,
    });

    // 초기화
    setValueLabel("");
    setDescription("");
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="text-base sm:text-lg">
            새 카테고리 값 추가
          </DialogTitle>
          <DialogDescription className="text-xs sm:text-sm">
            {columnLabel}에 새로운 값을 추가합니다
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-3 sm:space-y-4">
          <Input
            id="valueLabel"
            placeholder="이름 (예: 개발, 긴급, 진행중)"
            value={valueLabel}
            onChange={(e) => setValueLabel(e.target.value)}
            className="h-8 text-xs sm:h-10 sm:text-sm"
            autoFocus
          />

          <Textarea
            id="description"
            placeholder="설명 (선택사항)"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            className="text-xs sm:text-sm"
            rows={3}
          />
        </div>

        <DialogFooter className="gap-2 sm:gap-0">
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
          >
            취소
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={!valueLabel.trim()}
            className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
          >
            추가
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

