'use client';

import React, { useState, 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 { Card } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Employee, Role, EmployeeFormData } from '../types';
import { fetchEmployeeDetail } from './employeeApi';

interface EmployeeFormDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  editingEmployee: Employee | null;
  formData: EmployeeFormData;
  onFormDataChange: (data: EmployeeFormData) => void;
  onSave: () => void;
  roles: Role[];
  creating?: boolean;
  updating?: boolean;
  onClearForm?: () => void;
}

export function EmployeeFormDialog({
  open,
  onOpenChange,
  editingEmployee,
  formData,
  onFormDataChange,
  onSave,
  roles,
  creating = false,
  updating = false,
  onClearForm
}: EmployeeFormDialogProps) {
  const [loadingDetail, setLoadingDetail] = useState(false);

  // 当编辑员工时，根据ID获取用户详情
  useEffect(() => {
    if (open && editingEmployee && editingEmployee.id) {
      loadEmployeeDetail(editingEmployee.id);
    }
  }, [open, editingEmployee]);

  const loadEmployeeDetail = async (userId: string) => {
    setLoadingDetail(true);
    try {
      const employeeDetail = await fetchEmployeeDetail(userId);

      // 将API数据转换为表单数据格式
      const formDetailData: EmployeeFormData = {
        username: employeeDetail.username,
        name: employeeDetail.displayName || employeeDetail.fullName || employeeDetail.username,
        phone: employeeDetail.phone || '',
        email: employeeDetail.email || '',
        department: employeeDetail.departmentName || '',
        position: '', // API返回中没有position字段
        enterpriseId: employeeDetail.tenantId,
        enterpriseName: employeeDetail.companyName || '',
        status: employeeDetail.isActive ? 'active' : 'inactive',
        roleIds: [], // 需要单独获取角色信息
        idCard: '', // API返回中没有idCard字段
        address: '', // API返回中没有address字段
        auditStatus: 'approved', // 默认值
        isSuperuser: employeeDetail.isSuperuser,
      };

      // 更新表单数据
      onFormDataChange(formDetailData);
    } catch (error) {
      console.error('获取员工详情失败:', error);
      toast.error('接口调用失败，请稍后重试');
    } finally {
      setLoadingDetail(false);
    }
  };
  return (
    <Dialog open={open} onOpenChange={(isOpen) => {
      if (!isOpen && onClearForm) {
        onClearForm();
      }
      onOpenChange(isOpen);
    }}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>
            {editingEmployee ? (
              <div className="flex items-center gap-2">
                编辑员工
                {loadingDetail && (
                  <div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
                )}
              </div>
            ) : (
              '添加员工'
            )}
          </DialogTitle>
          <DialogDescription className="sr-only">
            {editingEmployee ? '编辑员工信息' : '添加新员工'}
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4 max-h-96 overflow-y-auto">
          {/* 基本信息 */}
          <div>
            <h4 className="mb-3 text-green-800">基本信息</h4>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="username">用户名 *</Label>
                <Input
                  id="username"
                  value={formData.username || ''}
                  onChange={(e) => onFormDataChange({ ...formData, username: e.target.value })}
                  placeholder="登录用户名"
                  disabled={editingEmployee && loadingDetail}
                />
              </div>
              <div>
                <Label htmlFor="name">姓名 *</Label>
                <Input
                  id="name"
                  value={formData.name || ''}
                  onChange={(e) => onFormDataChange({ ...formData, name: e.target.value })}
                  placeholder="真实姓名"
                  disabled={editingEmployee && loadingDetail}
                />
              </div>
              <div>
                <Label htmlFor="phone">手机号 *</Label>
                <Input
                  id="phone"
                  value={formData.phone || ''}
                  onChange={(e) => onFormDataChange({ ...formData, phone: e.target.value })}
                  placeholder="11位手机号码"
                  disabled={editingEmployee && loadingDetail}
                />
              </div>
              <div>
                <Label htmlFor="email">邮箱</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email || ''}
                  onChange={(e) => onFormDataChange({ ...formData, email: e.target.value })}
                  placeholder="电子邮箱"
                  disabled={editingEmployee && loadingDetail}
                />
              </div>
            </div>
          </div>

          {/* 工作信息 */}
          <div>
            <h4 className="mb-3 text-green-800">工作信息</h4>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="department">部门</Label>
                <Input
                  id="department"
                  value={formData.department || ''}
                  onChange={(e) => onFormDataChange({ ...formData, department: e.target.value })}
                  placeholder="所属部门"
                  disabled={editingEmployee && loadingDetail}
                />
              </div>
            </div>
          </div>

          {/* 角色选择 */}
          <div>
            <Label>角色配置 *</Label>
            <Card className="mt-2 p-4 bg-gray-50">
              <div className="grid grid-cols-2 gap-3">
                {roles
                  .filter(role => role.status === 'active')
                  .map((role) => (
                    <div key={role.id} className="flex items-start gap-2">
                      <Checkbox
                        id={`role-${role.id}`}
                        checked={formData.roleIds?.includes(role.id) || false}
                        onCheckedChange={(checked) => {
                          if (checked) {
                            onFormDataChange({
                              ...formData,
                              roleIds: [...(formData.roleIds || []), role.id],
                            });
                          } else {
                            onFormDataChange({
                              ...formData,
                              roleIds: (formData.roleIds || []).filter(id => id !== role.id),
                            });
                          }
                        }}
                      />
                      <div className="flex-1">
                        <Label htmlFor={`role-${role.id}`} className="cursor-pointer text-foreground">
                          {role.name}
                        </Label>
                        {role.description && (
                          <p className="text-xs text-muted-foreground mt-0.5">
                            {role.description}
                          </p>
                        )}
                      </div>
                    </div>
                  ))}
              </div>
              {roles.filter(r => r.status === 'active').length === 0 && (
                <p className="text-sm text-muted-foreground text-center py-2">
                  暂无可用角色，请先在角色管理中创建角色
                </p>
              )}
            </Card>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={creating || updating || loadingDetail}>
            取消
          </Button>
          <Button onClick={onSave} disabled={creating || updating || loadingDetail}>
            {creating ? '创建中...' : updating ? '更新中...' : loadingDetail ? '加载中...' : '保存'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}