'use client';

import React, { useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} 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 { Checkbox } from '@/components/ui/checkbox';
import { Separator } from '@/components/ui/separator';
import { Loader2, UserPlus, Shield, Key, Mail, Lock } from 'lucide-react';
import { AVAILABLE_ROLES, AVAILABLE_PERMISSIONS } from '@/lib/api/admin/users';

interface UserCreateDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (data: {
    username: string;
    email: string;
    password: string;
    isActive: boolean;
    isSuperuser: boolean;
    roles: string[];
    permissions: string[];
  }) => void;
  isSaving?: boolean;
}

export function UserCreateDialog({
  isOpen,
  onClose,
  onSave,
  isSaving = false,
}: UserCreateDialogProps) {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    isActive: true,
    isSuperuser: false,
  });
  const [selectedRoles, setSelectedRoles] = useState<string[]>(['user']);
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    if (!formData.username.trim()) {
      newErrors.username = '用户名不能为空';
    } else if (formData.username.length < 3) {
      newErrors.username = '用户名至少需要3个字符';
    }

    if (!formData.email.trim()) {
      newErrors.email = '邮箱不能为空';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = '请输入有效的邮箱地址';
    }

    if (!formData.password) {
      newErrors.password = '密码不能为空';
    } else if (formData.password.length < 6) {
      newErrors.password = '密码至少需要6个字符';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleRoleToggle = (roleId: string) => {
    setSelectedRoles((prev) =>
      prev.includes(roleId)
        ? prev.filter((r) => r !== roleId)
        : [...prev, roleId]
    );
  };

  const handlePermissionToggle = (permissionId: string) => {
    setSelectedPermissions((prev) =>
      prev.includes(permissionId)
        ? prev.filter((p) => p !== permissionId)
        : [...prev, permissionId]
    );
  };

  const handleSave = () => {
    if (!validateForm()) return;

    onSave({
      username: formData.username.trim(),
      email: formData.email.trim(),
      password: formData.password,
      isActive: formData.isActive,
      isSuperuser: formData.isSuperuser,
      roles: selectedRoles,
      permissions: selectedPermissions,
    });
  };

  const handleClose = () => {
    if (!isSaving) {
      setFormData({
        username: '',
        email: '',
        password: '',
        isActive: true,
        isSuperuser: false,
      });
      setSelectedRoles(['user']);
      setSelectedPermissions([]);
      setErrors({});
      onClose();
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <UserPlus className="w-5 h-5" />
            新建用户
          </DialogTitle>
          <DialogDescription>
            创建新用户账号并设置基本信息、角色和权限
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* Basic Info Section */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Shield className="w-4 h-4" />
              <Label className="text-base font-medium">基本信息</Label>
            </div>

            <div className="grid grid-cols-1 gap-4">
              <div className="space-y-2">
                <Label htmlFor="username" className="flex items-center gap-2">
                  <span>用户名</span>
                  <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="username"
                  placeholder="输入用户名"
                  value={formData.username}
                  onChange={(e) =>
                    setFormData((prev) => ({ ...prev, username: e.target.value }))
                  }
                  disabled={isSaving}
                  className={errors.username ? 'border-destructive' : ''}
                />
                {errors.username && (
                  <p className="text-sm text-destructive">{errors.username}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="email" className="flex items-center gap-2">
                  <Mail className="w-4 h-4" />
                  <span>邮箱</span>
                  <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="email"
                  type="email"
                  placeholder="输入邮箱地址"
                  value={formData.email}
                  onChange={(e) =>
                    setFormData((prev) => ({ ...prev, email: e.target.value }))
                  }
                  disabled={isSaving}
                  className={errors.email ? 'border-destructive' : ''}
                />
                {errors.email && (
                  <p className="text-sm text-destructive">{errors.email}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="password" className="flex items-center gap-2">
                  <Lock className="w-4 h-4" />
                  <span>密码</span>
                  <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="password"
                  type="password"
                  placeholder="设置密码（至少6个字符）"
                  value={formData.password}
                  onChange={(e) =>
                    setFormData((prev) => ({ ...prev, password: e.target.value }))
                  }
                  disabled={isSaving}
                  className={errors.password ? 'border-destructive' : ''}
                />
                {errors.password && (
                  <p className="text-sm text-destructive">{errors.password}</p>
                )}
              </div>
            </div>
          </div>

          <Separator />

          {/* Status Section */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Shield className="w-4 h-4" />
              <Label className="text-base font-medium">账户状态</Label>
            </div>

            <div className="space-y-4">
              <div className="flex items-center justify-between rounded-lg border p-4">
                <div className="space-y-0.5">
                  <Label htmlFor="user-active">启用账户</Label>
                  <p className="text-sm text-muted-foreground">
                    创建后立即启用该账户
                  </p>
                </div>
                <Switch
                  id="user-active"
                  checked={formData.isActive}
                  onCheckedChange={(checked) =>
                    setFormData((prev) => ({ ...prev, isActive: checked }))
                  }
                  disabled={isSaving}
                />
              </div>

              <div className="flex items-center justify-between rounded-lg border p-4">
                <div className="space-y-0.5">
                  <Label htmlFor="user-superuser">超级用户</Label>
                  <p className="text-sm text-muted-foreground">
                    授予该用户所有系统权限
                  </p>
                </div>
                <Switch
                  id="user-superuser"
                  checked={formData.isSuperuser}
                  onCheckedChange={(checked) =>
                    setFormData((prev) => ({ ...prev, isSuperuser: checked }))
                  }
                  disabled={isSaving}
                />
              </div>
            </div>
          </div>

          <Separator />

          {/* Roles Section */}
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Shield className="w-4 h-4" />
              <Label className="text-base font-medium">角色</Label>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {AVAILABLE_ROLES.map((role) => (
                <div
                  key={role.id}
                  className={`flex items-start space-x-3 rounded-lg border p-3 cursor-pointer transition-colors ${
                    selectedRoles.includes(role.id)
                      ? 'border-primary bg-primary/5'
                      : 'hover:bg-muted/50'
                  }`}
                  onClick={() => handleRoleToggle(role.id)}
                >
                  <Checkbox
                    checked={selectedRoles.includes(role.id)}
                    onCheckedChange={() => handleRoleToggle(role.id)}
                  />
                  <div className="space-y-1">
                    <Label className="font-medium cursor-pointer">
                      {role.name}
                    </Label>
                    <p className="text-xs text-muted-foreground">
                      {role.description}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <Separator />

          {/* Permissions Section */}
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Key className="w-4 h-4" />
              <Label className="text-base font-medium">权限</Label>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {AVAILABLE_PERMISSIONS.map((permission) => (
                <div
                  key={permission.id}
                  className={`flex items-start space-x-3 rounded-lg border p-3 cursor-pointer transition-colors ${
                    selectedPermissions.includes(permission.id)
                      ? 'border-primary bg-primary/5'
                      : 'hover:bg-muted/50'
                  }`}
                  onClick={() => handlePermissionToggle(permission.id)}
                >
                  <Checkbox
                    checked={selectedPermissions.includes(permission.id)}
                    onCheckedChange={() => handlePermissionToggle(permission.id)}
                  />
                  <div className="space-y-1">
                    <Label className="font-medium cursor-pointer">
                      {permission.name}
                    </Label>
                    <p className="text-xs text-muted-foreground">
                      {permission.description}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose} disabled={isSaving}>
            取消
          </Button>
          <Button onClick={handleSave} disabled={isSaving}>
            {isSaving ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                创建中...
              </>
            ) : (
              '创建用户'
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
