"use client";

import React, { useState, useEffect } 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 CategoryValueEditDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  value: TableCategoryValue;
  onUpdate: (valueId: number, updates: Partial<TableCategoryValue>) => void;
  columnLabel: string;
}

export const CategoryValueEditDialog: React.FC<
  CategoryValueEditDialogProps
> = ({ open, onOpenChange, value, onUpdate, columnLabel }) => {
  const [valueLabel, setValueLabel] = useState(value.valueLabel);
  const [description, setDescription] = useState(value.description || "");

  useEffect(() => {
    setValueLabel(value.valueLabel);
    setDescription(value.description || "");
  }, [value]);

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

    onUpdate(value.valueId!, {
      valueLabel: valueLabel.trim(),
      description: description.trim(),
    });
  };

  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} - {value.valueCode}
          </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>
  );
};

