'use client';

import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
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, User as UserIcon, Mail, Shield, Key } from 'lucide-react';
import { type User as UserType, AVAILABLE_ROLES, AVAILABLE_PERMISSIONS } from '@/lib/api/admin/users';

interface UserEditDialogProps {
  user: UserType | null;
  isOpen: boolean;
  onClose: () => void;
  onSave: (userId: string, data: { isActive: boolean; roles: string[]; permissions: string[] }) => void;
  isSaving?: boolean;
}

export function UserEditDialog({
  user,
  isOpen,
  onClose,
  onSave,
  isSaving = false,
}: UserEditDialogProps) {
  const [isActive, setIsActive] = useState(true);
  const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);

  useEffect(() => {
    if (user) {
      setIsActive(user.isActive);
      setSelectedRoles(user.roles || []);
      setSelectedPermissions(user.permissions || []);
    }
  }, [user, isOpen]);

  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 (user) {
      onSave(user.id, {
        isActive,
        roles: selectedRoles,
        permissions: selectedPermissions,
      });
    }
  };

  const formatDate = (timestamp?: number | string) => {
    if (!timestamp) return '从未';
    const numTimestamp = typeof timestamp === 'string' ? parseInt(timestamp, 10) : timestamp;
    return new Date(numTimestamp * 1000).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (!user) return null;

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <UserIcon className="w-5 h-5" />
            编辑用户
          </DialogTitle>
          <DialogDescription>
            修改用户状态、角色和权限设置
          </DialogDescription>
        </DialogHeader>

        {/* User Info Section */}
        <div className="space-y-4">
          <div className="bg-muted/50 rounded-lg p-4 space-y-3">
            <div className="flex items-center gap-3">
              <UserIcon className="w-4 h-4 text-muted-foreground" />
              <span className="font-medium">{user.username}</span>
              <Badge variant={user.isActive ? 'default' : 'secondary'}>
                {user.isActive ? '启用' : '禁用'}
              </Badge>
            </div>
            <div className="flex items-center gap-3">
              <Mail className="w-4 h-4 text-muted-foreground" />
              <span className="text-sm text-muted-foreground">{user.email}</span>
            </div>
            <div className="text-xs text-muted-foreground space-y-1">
              <div>创建于: {formatDate(user.createdAt)}</div>
              <div>最后登录: {formatDate(user.lastLogin)}</div>
            </div>
          </div>

          <Separator />

          {/* Status 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="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={isActive}
                onCheckedChange={setIsActive}
              />
            </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={onClose} disabled={isSaving}>
            取消
          </Button>
          <Button onClick={handleSave} disabled={isSaving}>
            {isSaving ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                保存中...
              </>
            ) : (
              '保存更改'
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
