'use client';

import { useEffect } from 'react';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
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 { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import type { DepartmentDialogProps, DepartmentFormData } from './types';

const departmentFormSchema = z.object({
  code: z.string().min(1, '부서 코드를 입력하세요').max(50, '50자 이내로 입력하세요'),
  name: z.string().min(1, '부서명을 입력하세요').max(100, '100자 이내로 입력하세요'),
  description: z.string().max(500, '500자 이내로 입력하세요'),
  sortOrder: z.number().min(0, '0 이상 입력하세요'),
  isActive: z.boolean(),
});

type FormData = z.infer<typeof departmentFormSchema>;

/**
 * 부서 추가/수정 다이얼로그
 */
export function DepartmentDialog({
  isOpen,
  onOpenChange,
  mode,
  parentDepartment,
  department,
  onSubmit,
}: DepartmentDialogProps) {
  const {
    register,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(departmentFormSchema),
    defaultValues: {
      code: '',
      name: '',
      description: '',
      sortOrder: 0,
      isActive: true,
    },
  });

  const isActive = watch('isActive');

  // 다이얼로그 열릴 때 초기값 설정
  useEffect(() => {
    if (isOpen) {
      if (mode === 'edit' && department) {
        reset({
          code: department.code || '',
          name: department.name,
          description: department.description || '',
          sortOrder: department.sortOrder,
          isActive: department.isActive,
        });
      } else {
        reset({
          code: '',
          name: '',
          description: '',
          sortOrder: 0,
          isActive: true,
        });
      }
    }
  }, [isOpen, mode, department, reset]);

  const onFormSubmit = (data: FormData) => {
    onSubmit({
      code: data.code,
      name: data.name,
      description: data.description || '',
      sortOrder: data.sortOrder,
      isActive: data.isActive,
    } as DepartmentFormData);
  };

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

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

        <form onSubmit={handleSubmit(onFormSubmit)}>
          <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-code">
                부서 코드 <span className="text-destructive">*</span>
              </Label>
              <Input
                id="department-code"
                {...register('code')}
                placeholder="예: DEV, SALES, HR"
                autoFocus
              />
              {errors.code && (
                <p className="text-sm text-destructive">{errors.code.message}</p>
              )}
            </div>

            {/* 부서명 */}
            <div className="space-y-2">
              <Label htmlFor="department-name">
                부서명 <span className="text-destructive">*</span>
              </Label>
              <Input
                id="department-name"
                {...register('name')}
                placeholder="부서명을 입력하세요"
              />
              {errors.name && (
                <p className="text-sm text-destructive">{errors.name.message}</p>
              )}
            </div>

            {/* 설명 */}
            <div className="space-y-2">
              <Label htmlFor="department-description">설명</Label>
              <Textarea
                id="department-description"
                {...register('description')}
                placeholder="부서 설명을 입력하세요"
                rows={3}
              />
              {errors.description && (
                <p className="text-sm text-destructive">{errors.description.message}</p>
              )}
            </div>

            {/* 정렬순서 + 활성상태 (가로 배치) */}
            <div className="flex items-start gap-6">
              <div className="space-y-2 flex-1">
                <Label htmlFor="department-sort-order">정렬순서</Label>
                <Input
                  id="department-sort-order"
                  type="number"
                  {...register('sortOrder')}
                  min={0}
                />
                {errors.sortOrder && (
                  <p className="text-sm text-destructive">{errors.sortOrder.message}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label>활성 상태</Label>
                <div className="flex items-center gap-2 h-9">
                  <Switch
                    checked={isActive}
                    onCheckedChange={(checked) => setValue('isActive', checked)}
                  />
                  <span className="text-sm text-muted-foreground">
                    {isActive ? '활성' : '비활성'}
                  </span>
                </div>
              </div>
            </div>
          </div>

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