import React, { useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  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 { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/components/ui/use-toast';
import { createUser, updateUser } from '../service';
import type { UserResponse, UserRequest } from '../types';
import type { DepartmentResponse } from '../../Department/types';

interface EditModalProps {
  open: boolean;
  record?: UserResponse;
  departments: DepartmentResponse[];
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}

/**
 * 用户编辑弹窗
 */
const EditModal: React.FC<EditModalProps> = ({
  open,
  record,
  departments,
  onOpenChange,
  onSuccess,
}) => {
  const { toast } = useToast();
  const [formData, setFormData] = React.useState<Partial<UserRequest>>({
    enabled: true,
  });

  useEffect(() => {
    if (open) {
      if (record) {
        setFormData({
          username: record.username,
          nickname: record.nickname,
          email: record.email,
          phone: record.phone,
          departmentId: record.departmentId,
          enabled: record.enabled,
        });
      } else {
        setFormData({ enabled: true });
      }
    }
  }, [open, record]);

  const handleSubmit = async () => {
    try {
      // 验证
      if (!formData.username?.trim()) {
        toast({
          title: '提示',
          description: '请输入用户名',
          variant: 'destructive'
        });
        return;
      }

      if (!record && !formData.password) {
        toast({
          title: '提示',
          description: '请输入密码',
          variant: 'destructive'
        });
        return;
      }

      if (!record && formData.password && formData.password.length < 6) {
        toast({
          title: '提示',
          description: '密码长度不能小于6位',
          variant: 'destructive'
        });
        return;
      }

      if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
        toast({
          title: '提示',
          description: '请输入正确的邮箱格式',
          variant: 'destructive'
        });
        return;
      }

      if (record) {
        await updateUser(record.id, formData as UserRequest);
        toast({
          title: '更新成功',
          description: `用户 "${formData.username}" 已更新`,
        });
      } else {
        await createUser(formData as UserRequest);
        toast({
          title: '创建成功',
          description: `用户 "${formData.username}" 已创建`,
        });
      }

      onSuccess();
      onOpenChange(false);
    } catch (error) {
      console.error('保存失败:', error);
      toast({
        title: '保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  // 扁平化部门列表
  const flattenDepartments = (depts: DepartmentResponse[]): DepartmentResponse[] => {
    const result: DepartmentResponse[] = [];
    const traverse = (dept: DepartmentResponse, level: number = 0) => {
      result.push({ ...dept, name: '　'.repeat(level) + dept.name });
      if (dept.children) {
        dept.children.forEach(child => traverse(child, level + 1));
      }
    };
    depts.forEach(dept => traverse(dept));
    return result;
  };

  const flatDepartments = flattenDepartments(departments);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>{record ? '编辑用户' : '新增用户'}</DialogTitle>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid gap-2">
            <Label htmlFor="username">用户名 *</Label>
            <Input
              id="username"
              value={formData.username || ''}
              onChange={(e) => setFormData({ ...formData, username: e.target.value })}
              placeholder="请输入用户名"
              disabled={!!record}
            />
          </div>

          {!record && (
            <div className="grid gap-2">
              <Label htmlFor="password">密码 *</Label>
              <Input
                id="password"
                type="password"
                value={formData.password || ''}
                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                placeholder="请输入密码（至少6位）"
              />
            </div>
          )}

          <div className="grid gap-2">
            <Label htmlFor="nickname">昵称</Label>
            <Input
              id="nickname"
              value={formData.nickname || ''}
              onChange={(e) => setFormData({ ...formData, nickname: e.target.value })}
              placeholder="请输入昵称"
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="email">邮箱</Label>
            <Input
              id="email"
              type="email"
              value={formData.email || ''}
              onChange={(e) => setFormData({ ...formData, email: e.target.value })}
              placeholder="请输入邮箱"
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="phone">手机号</Label>
            <Input
              id="phone"
              value={formData.phone || ''}
              onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
              placeholder="请输入手机号"
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="department">所属部门</Label>
            <Select
              value={formData.departmentId?.toString() || undefined}
              onValueChange={(value) => setFormData({ ...formData, departmentId: Number(value) })}
            >
              <SelectTrigger>
                <SelectValue placeholder="请选择所属部门" />
              </SelectTrigger>
              <SelectContent>
                {flatDepartments.map(dept => (
                  <SelectItem key={dept.id} value={dept.id.toString()}>
                    {dept.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="flex items-center justify-between">
            <Label htmlFor="enabled">启用状态</Label>
            <Switch
              id="enabled"
              checked={formData.enabled}
              onCheckedChange={(checked) => setFormData({ ...formData, enabled: checked })}
            />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSubmit}>确定</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default EditModal;

