/**
 * filekorolheader: 部门表单对话框组件 - 部门添加/编辑表单界面
 * 功能：部门信息表单、输入验证、提交处理
 * 路径：/central-config/user/department/components/DepartmentFormDialog
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn/ui组件，TypeScript类型安全
 */

'use client';

import { useState, useCallback, useEffect } from 'react';
import { toast } from 'sonner';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Department, CreateDepartmentForm } from '../types';
import {
  createDepartment,
  updateDepartment,
  transformCreateDepartmentData,
  debounce,
  getDefaultOrderIndex,
} from './departmentCreateApi';

interface DepartmentFormDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  editingDepartment: Department | null;
  parentDepartment: Department | null;
  onSave: (formData: Partial<Department>) => void;
  refreshDepartmentTree?: () => void;
}

export function DepartmentFormDialog({
  open,
  onOpenChange,
  editingDepartment,
  parentDepartment,
  onSave,
  refreshDepartmentTree,
}: DepartmentFormDialogProps) {
  const [formData, setFormData] = useState<CreateDepartmentForm>({
    name: '',
    code: '',
    manager: '',
    phone: '',
    email: '',
    description: '',
    status: 'active',
    sort: 0,
    parentId: parentDepartment?.id || '',
    level: parentDepartment ? (parentDepartment.level || 1) + 1 : 1,
  });

  const [loading, setLoading] = useState(false);

  // 当弹窗打开状态变化时，处理表单数据
  useEffect(() => {
    if (open) {
      // 弹窗打开时，根据编辑状态初始化表单
      if (editingDepartment) {
        // 编辑模式：带入所有部门数据
        setFormData({
          name: editingDepartment.name || '',
          code: editingDepartment.code || '',
          manager: editingDepartment.manager || '',
          phone: editingDepartment.phone || '',
          email: editingDepartment.email || '',
          description: editingDepartment.description || '',
          status: editingDepartment.status || 'active',
          sort: editingDepartment.sort || 0,
          parentId: editingDepartment.parentId || '',
          level: editingDepartment.level || 1,
        });
      } else {
        // 新增模式：清空表单，使用默认值
        setFormData({
          name: '',
          code: '',
          manager: '',
          phone: '',
          email: '',
          description: '',
          status: 'active',
          sort: 0,
          parentId: parentDepartment?.id || '',
          level: parentDepartment ? (parentDepartment.level || 1) + 1 : 1,
        });
      }
    }
  }, [open, editingDepartment, parentDepartment]);

  const handleInputChange = (field: keyof CreateDepartmentForm, value: string | number) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 表单验证
  const validateForm = (): boolean => {
    if (!formData.name?.trim()) {
      toast.error('请输入部门名称');
      return false;
    }
    if (!formData.code?.trim()) {
      toast.error('请输入部门编码');
      return false;
    }
    if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      toast.error('邮箱格式不正确');
      return false;
    }
    return true;
  };

  // 创建部门的API调用函数（带防抖）
  const createDepartmentWithDebounce = useCallback(
    debounce(async (form: CreateDepartmentForm) => {
      try {
        setLoading(true);

        // 调用API创建部门
        await createDepartment(form);

        // 成功处理
        toast.success('创建一级部门成功');

        // 关闭对话框
        onOpenChange(false);

        // 刷新部门树
        if (refreshDepartmentTree) {
          refreshDepartmentTree();
        }

      } catch (error) {
        // 失败处理 - 不关闭页面
        console.error('创建部门失败:', error);
        const errorMessage = error instanceof Error ? error.message : '创建一级部门失败';
        toast.error(errorMessage);
      } finally {
        setLoading(false);
      }
    }, 1000), // 1秒防抖
    [onOpenChange, refreshDepartmentTree, parentDepartment]
  );

  const handleSubmit = async () => {
    // 表单验证
    if (!validateForm()) {
      return;
    }

    // 如果是编辑模式，使用API调用
    if (editingDepartment) {
      setLoading(true);
      try {
        // 调用更新部门API
        await updateDepartment(editingDepartment.id, formData);

        // 成功处理
        toast.success('部门更新成功');
        onOpenChange(false);

        // 刷新部门树
        if (refreshDepartmentTree) {
          refreshDepartmentTree();
        }

      } catch (error) {
        // 失败处理 - 不关闭页面
        console.error('更新部门失败:', error);
        const errorMessage = error instanceof Error ? error.message : '部门更新失败';
        toast.error(errorMessage);
      } finally {
        setLoading(false);
      }
    } else {
      // 创建模式，使用API调用（带防抖）
      createDepartmentWithDebounce(formData);
    }
  };

  const handleClose = () => {
    if (!loading) {
      onOpenChange(false);
    }
  };

  const title = editingDepartment
    ? '编辑部门'
    : parentDepartment
      ? `添加子部门（父级：${parentDepartment.name}）`
      : '添加一级部门';

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription className="sr-only">
            {editingDepartment ? '编辑部门信息' : '添加新部门'}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label htmlFor="name">部门名称 *</Label>
              <Input
                id="name"
                value={formData.name || ''}
                onChange={(e) => handleInputChange('name', e.target.value)}
                placeholder="请输入部门名称"
                disabled={loading}
              />
            </div>

            <div>
              <Label htmlFor="code">部门编码 *</Label>
              <Input
                id="code"
                value={formData.code || ''}
                onChange={(e) => handleInputChange('code', e.target.value.toUpperCase())}
                placeholder="请输入部门编码，如：TECH"
                className="font-mono"
                disabled={loading}
              />
            </div>

            <div>
              <Label htmlFor="manager">负责人</Label>
              <Input
                id="manager"
                value={formData.manager || ''}
                onChange={(e) => handleInputChange('manager', e.target.value)}
                placeholder="请输入负责人姓名"
                disabled={loading}
              />
            </div>

            <div>
              <Label htmlFor="phone">联系电话</Label>
              <Input
                id="phone"
                value={formData.phone || ''}
                onChange={(e) => handleInputChange('phone', e.target.value)}
                placeholder="请输入联系电话"
                disabled={loading}
              />
            </div>

            <div>
              <Label htmlFor="email">邮箱</Label>
              <Input
                id="email"
                type="email"
                value={formData.email || ''}
                onChange={(e) => handleInputChange('email', e.target.value)}
                placeholder="请输入邮箱"
                disabled={loading}
              />
            </div>

            <div>
              <Label htmlFor="sort">排序号 *</Label>
              <Input
                id="sort"
                type="number"
                value={formData.sort || 0}
                onChange={(e) => handleInputChange('sort', parseInt(e.target.value) || 0)}
                placeholder="数字越小越靠前"
                disabled={loading}
              />
            </div>

            <div>
              <Label htmlFor="status">状态 *</Label>
              <Select
                value={formData.status}
                onValueChange={(value: 'active' | 'inactive') => handleInputChange('status', value)}
                disabled={loading}
              >
                <SelectTrigger id="status">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="active">启用</SelectItem>
                  <SelectItem value="inactive">停用</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div>
            <Label htmlFor="description">部门描述</Label>
            <Input
              id="description"
              value={formData.description || ''}
              onChange={(e) => handleInputChange('description', e.target.value)}
              placeholder="请输入部门描述"
              disabled={loading}
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose} disabled={loading}>
            取消
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={loading || !formData.name?.trim() || !formData.code?.trim()}
            className="bg-green-600 hover:bg-green-700 dark:bg-green-600 dark:hover:bg-green-700"
          >
            {loading ? '保存中...' : '保存'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}