'use client';

import { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { toast } from 'sonner';

interface ColumnDialogProps {
  isColumnDialogOpen: boolean;
  setIsColumnDialogOpen: (open: boolean) => void;
  editingColumnId: string | null;
  setEditingColumnId: (id: string | null) => void;
  columnName: string;
  setColumnName: (name: string) => void;
  columnKey: string;
  setColumnKey: (key: string) => void;
  textboxColumns: Array<{ id: string; name: string; key: string }>;
  setTextboxColumns: React.Dispatch<React.SetStateAction<Array<{ id: string; name: string; key: string }>>>;
}

export function ColumnDialog({
  isColumnDialogOpen,
  setIsColumnDialogOpen,
  editingColumnId,
  setEditingColumnId,
  columnName,
  setColumnName,
  columnKey,
  setColumnKey,
  textboxColumns,
  setTextboxColumns,
}: ColumnDialogProps) {
  const [isSubmitted, setIsSubmitted] = useState(false);

  // 유효성 검사
  const isNameEmpty = !columnName.trim();
  const isKeyEmpty = !columnKey.trim();

  const handleClose = () => {
    setIsColumnDialogOpen(false);
    setEditingColumnId(null);
    setColumnName('');
    setColumnKey('');
    setIsSubmitted(false);
  };

  const handleSubmit = () => {
    setIsSubmitted(true);
    if (isNameEmpty || isKeyEmpty) {
      return;
    }

    if (editingColumnId) {
      // 수정
      setTextboxColumns(prev => prev.map(col =>
        col.id === editingColumnId
          ? { ...col, name: columnName, key: columnKey }
          : col
      ));
      toast.success('컬럼이 수정되었습니다');
    } else {
      // 추가
      setTextboxColumns(prev => [...prev, {
        id: `col-${Date.now()}`,
        name: columnName,
        key: columnKey
      }]);
      toast.success('컬럼이 추가되었습니다');
    }

    handleClose();
    setIsSubmitted(false);
  };

  return (
    <Dialog open={isColumnDialogOpen} onOpenChange={(open) => {
      if (!open) handleClose();
      else setIsColumnDialogOpen(open);
    }}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{editingColumnId ? '컬럼 수정' : '컬럼 추가'}</DialogTitle>
          <DialogDescription>
            텍스트박스에 추가할 컬럼 정보를 입력하세요
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div>
            <Label>컬럼명 *</Label>
            <Input
              value={columnName}
              onChange={(e) => setColumnName(e.target.value)}
              placeholder="예: 가로"
              className={isSubmitted && isNameEmpty ? 'border-red-500 focus-visible:ring-red-500' : ''}
            />
            {isSubmitted && isNameEmpty && (
              <p className="text-xs text-red-500 mt-1">컬럼명을 입력해주세요</p>
            )}
          </div>
          <div>
            <Label>컬럼 키 *</Label>
            <Input
              value={columnKey}
              onChange={(e) => setColumnKey(e.target.value)}
              placeholder="예: width"
              className={isSubmitted && isKeyEmpty ? 'border-red-500 focus-visible:ring-red-500' : ''}
            />
            {isSubmitted && isKeyEmpty && (
              <p className="text-xs text-red-500 mt-1">컬럼 키를 입력해주세요</p>
            )}
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={handleClose}>취소</Button>
          <Button onClick={handleSubmit}>
            {editingColumnId ? '수정' : '추가'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}