'use client';

import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import type { DepartmentDialogProps } from './types';

/**
 * 부서 추가/수정 다이얼로그
 */
export function DepartmentDialog({
  isOpen,
  onOpenChange,
  mode,
  parentDepartment,
  department,
  onSubmit
}: DepartmentDialogProps) {
  const [name, setName] = useState('');

  // 다이얼로그 열릴 때 초기값 설정
  useEffect(() => {
    if (isOpen) {
      if (mode === 'edit' && department) {
        setName(department.name);
      } else {
        setName('');
      }
    }
  }, [isOpen, mode, department]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (name.trim()) {
      onSubmit(name.trim());
      setName('');
    }
  };

  const title = mode === 'add' ? '부서 추가' : '부서 수정';
  const submitText = mode === 'add' ? '등록' : '수정';

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit}>
          <div className="space-y-4 py-4">
            {/* 부모 부서 표시 (추가 모드일 때) */}
            {mode === 'add' && parentDepartment && (
              <div className="text-sm text-muted-foreground">
                상위 부서: <span className="font-medium">{parentDepartment.name}</span>
              </div>
            )}

            {/* 부서명 입력 */}
            <div className="space-y-2">
              <Label htmlFor="department-name">부서명</Label>
              <Input
                id="department-name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="부서명을 입력하세요"
                autoFocus
              />
            </div>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              취소
            </Button>
            <Button type="submit" disabled={!name.trim()}>
              {submitText}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}