'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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import type { PermissionDialogProps } from './types';

/**
 * 권한 추가/수정 다이얼로그
 */
export function PermissionDialog({
  isOpen,
  onOpenChange,
  mode,
  permission,
  onSubmit
}: PermissionDialogProps) {
  const [name, setName] = useState('');
  const [status, setStatus] = useState<'active' | 'hidden'>('active');

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

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

  const dialogTitle = mode === 'add' ? '권한 등록' : '권한 수정';
  const submitText = mode === 'add' ? '등록' : '수정';

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

        <form onSubmit={handleSubmit}>
          <div className="space-y-4 py-4">
            {/* 권한명 입력 */}
            <div className="space-y-2">
              <Label htmlFor="permission-name">권한명</Label>
              <Input
                id="permission-name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="권한명을 입력하세요"
                autoFocus
              />
            </div>

            {/* 상태 선택 */}
            <div className="space-y-2">
              <Label htmlFor="permission-status">상태</Label>
              <Select value={status} onValueChange={(value: 'active' | 'hidden') => setStatus(value)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="active">공개</SelectItem>
                  <SelectItem value="hidden">숨김</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

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