'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 { Loader2 } from 'lucide-react';
import type { RankDialogProps } from './types';

/**
 * 직급 추가/수정 다이얼로그
 */
export function RankDialog({
  isOpen,
  onOpenChange,
  mode,
  rank,
  onSubmit,
  isLoading = false,
}: RankDialogProps) {
  const [name, setName] = useState('');

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

  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">
            {/* 직급명 입력 */}
            <div className="space-y-2">
              <Label htmlFor="rank-name">직급명</Label>
              <Input
                id="rank-name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="직급명을 입력하세요"
                autoFocus
              />
            </div>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isLoading}>
              취소
            </Button>
            <Button type="submit" disabled={!name.trim() || isLoading}>
              {isLoading ? (
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              ) : null}
              {submitText}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}