import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Shield, Lock, Key, CheckCircle, XCircle, Eye, EyeOff, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { useAuth } from '../auth/AuthContext';

export function AccountSecurity() {
  const { authState } = useAuth();
  const [showPasswordDialog, setShowPasswordDialog] = useState(false);
  const [showOldPassword, setShowOldPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const [passwordForm, setPasswordForm] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
  });

  // 密码强度检查
  const checkPasswordStrength = (password: string) => {
    const checks = {
      length: password.length >= 8,
      hasUpper: /[A-Z]/.test(password),
      hasLower: /[a-z]/.test(password),
      hasNumber: /[0-9]/.test(password),
      hasSpecial: /[!@#$%^&*(),.?":{}|<>]/.test(password),
    };

    const passedCount = Object.values(checks).filter(Boolean).length;
    
    let strength: 'weak' | 'medium' | 'strong' = 'weak';
    if (passedCount >= 4) strength = 'strong';
    else if (passedCount >= 3) strength = 'medium';

    return { checks, strength, passedCount };
  };

  const { checks, strength } = checkPasswordStrength(passwordForm.newPassword);

  const handleChangePassword = () => {
    setPasswordForm({ oldPassword: '', newPassword: '', confirmPassword: '' });
    setShowPasswordDialog(true);
  };

  const handleConfirmChangePassword = () => {
    // 验证原密码
    if (!passwordForm.oldPassword) {
      toast.error('请输入原密码');
      return;
    }

    // 验证新密码
    if (!passwordForm.newPassword) {
      toast.error('请输入新密码');
      return;
    }

    if (passwordForm.newPassword.length < 8) {
      toast.error('密码长度至少为8位');
      return;
    }

    if (strength === 'weak') {
      toast.error('密码强度过弱，请使用更复杂的密码');
      return;
    }

    // 验证确认密码
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      toast.error('两次输入的密码不一致');
      return;
    }

    // 验证新旧密码不能相同
    if (passwordForm.oldPassword === passwordForm.newPassword) {
      toast.error('新密码不能与原密码相同');
      return;
    }

    // 这里应该调用API验证原密码并修改密码
    // 为了演示，我们假设原密码是 "123456"
    if (passwordForm.oldPassword !== '123456') {
      toast.error('原密码错误');
      return;
    }

    // 修改成功
    toast.success('密码修改成功，请使用新密码重新登录');
    setShowPasswordDialog(false);
    setPasswordForm({ oldPassword: '', newPassword: '', confirmPassword: '' });
  };

  const getStrengthColor = (strength: 'weak' | 'medium' | 'strong') => {
    switch (strength) {
      case 'strong':
        return 'text-success';
      case 'medium':
        return 'text-warning';
      case 'weak':
        return 'text-error';
    }
  };

  const getStrengthBg = (strength: 'weak' | 'medium' | 'strong') => {
    switch (strength) {
      case 'strong':
        return 'bg-success-muted';
      case 'medium':
        return 'bg-warning-muted';
      case 'weak':
        return 'bg-error-muted';
    }
  };

  const getStrengthText = (strength: 'weak' | 'medium' | 'strong') => {
    switch (strength) {
      case 'strong':
        return '强';
      case 'medium':
        return '中';
      case 'weak':
        return '弱';
    }
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-info-muted to-info-muted border-info">
        <div className="flex items-start gap-3">
          <Shield className="w-6 h-6 text-info flex-shrink-0 mt-1" />
          <div className="flex-1">
            <h2 className="mb-2">账户安全</h2>
            <p className="text-sm text-muted-foreground mb-3">
              管理您的账户安全设置，包括密码修改、安全验证等，确保账户安全
            </p>
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline" className="bg-white">
                <Lock className="w-3 h-3 mr-1" />
                密码管理
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Key className="w-3 h-3 mr-1" />
                安全验证
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Shield className="w-3 h-3 mr-1" />
                隐私保护
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* 账户信息概览 */}
      <Card className="p-6">
        <h3 className="mb-4">账户信息</h3>
        <div className="grid grid-cols-2 gap-6">
          <div className="p-4 bg-muted rounded-lg">
            <div className="text-sm text-muted-foreground mb-2">用户名</div>
            <div className="font-medium">{authState.user?.username}</div>
          </div>
          <div className="p-4 bg-muted rounded-lg">
            <div className="text-sm text-muted-foreground mb-2">手机号</div>
            <div className="font-medium">{authState.user?.phone}</div>
          </div>
          <div className="p-4 bg-muted rounded-lg">
            <div className="text-sm text-muted-foreground mb-2">邮箱</div>
            <div className="font-medium">{authState.user?.email || '未设置'}</div>
          </div>
          <div className="p-4 bg-muted rounded-lg">
            <div className="text-sm text-muted-foreground mb-2">最后登录时间</div>
            <div className="font-medium text-sm">{authState.user?.lastLoginTime || '未知'}</div>
          </div>
        </div>
      </Card>

      {/* 密码管理 */}
      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="mb-1">登录密码</h3>
            <p className="text-sm text-muted-foreground">定期修改密码可以提高账户安全性</p>
          </div>
          <Button onClick={handleChangePassword} className="gap-2">
            <Key className="w-4 h-4" />
            修改密码
          </Button>
        </div>

        <div className="p-4 bg-info-muted border border-info rounded-lg">
          <div className="flex items-start gap-3">
            <Shield className="w-5 h-5 text-info flex-shrink-0 mt-0.5" />
            <div className="flex-1">
              <h4 className="text-sm font-medium text-info-muted-foreground mb-2">密码安全提示</h4>
              <ul className="text-sm text-info-muted-foreground space-y-1">
                <li>• 密码长度至少8位</li>
                <li>• 包含大小写字母、数字和特殊字符</li>
                <li>• 不要使用过于简单的密码</li>
                <li>• 定期更换密码（建议3个月更换一次）</li>
                <li>• 不要在多个平台使用相同密码</li>
              </ul>
            </div>
          </div>
        </div>
      </Card>

      {/* 安全设置 */}
      <Card className="p-6">
        <h3 className="mb-4">安全设置</h3>
        <div className="space-y-4">
          <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                <CheckCircle className="w-5 h-5 text-green-600" />
              </div>
              <div>
                <div className="font-medium">手机验证</div>
                <div className="text-sm text-muted-foreground">已绑定手机号：{authState.user?.phone}</div>
              </div>
            </div>
            <Badge className="bg-green-100 text-green-700">已启用</Badge>
          </div>

          <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                <Lock className="w-5 h-5 text-blue-600" />
              </div>
              <div>
                <div className="font-medium">登录保护</div>
                <div className="text-sm text-muted-foreground">异常登录时需要额外验证</div>
              </div>
            </div>
            <Badge className="bg-blue-100 text-blue-700">已启用</Badge>
          </div>

          <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-yellow-100 rounded-full flex items-center justify-center">
                <AlertTriangle className="w-5 h-5 text-yellow-600" />
              </div>
              <div>
                <div className="font-medium">邮箱验证</div>
                <div className="text-sm text-muted-foreground">
                  {authState.user?.email ? `已绑定邮箱：${authState.user.email}` : '未绑定邮箱'}
                </div>
              </div>
            </div>
            <Badge className={authState.user?.email ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'}>
              {authState.user?.email ? '已启用' : '未启用'}
            </Badge>
          </div>
        </div>
      </Card>

      {/* 最近登录记录 */}
      <Card className="p-6">
        <h3 className="mb-4">最近登录记录</h3>
        <div className="space-y-3">
          <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
            <div className="flex items-center gap-3">
              <CheckCircle className="w-5 h-5 text-green-600" />
              <div>
                <div className="text-sm font-medium">当前会话</div>
                <div className="text-xs text-muted-foreground">
                  {authState.user?.lastLoginDevice} · {authState.user?.lastLoginIp}
                </div>
              </div>
            </div>
            <div className="text-sm text-muted-foreground">
              {authState.user?.lastLoginTime}
            </div>
          </div>
        </div>
      </Card>

      {/* 修改密码对话框 */}
      <Dialog open={showPasswordDialog} onOpenChange={setShowPasswordDialog}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>
              <div className="flex items-center gap-2">
                <Lock className="w-5 h-5 text-blue-600" />
                修改登录密码
              </div>
            </DialogTitle>
            <DialogDescription>
              为了您的账户安全，请定期更换密码并设置复杂密码
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 原密码 */}
            <div>
              <Label>原密码 *</Label>
              <div className="relative mt-2">
                <Input
                  type={showOldPassword ? 'text' : 'password'}
                  value={passwordForm.oldPassword}
                  onChange={(e) => setPasswordForm({ ...passwordForm, oldPassword: e.target.value })}
                  placeholder="请输入原密码"
                  className="pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShowOldPassword(!showOldPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  {showOldPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>

            {/* 新密码 */}
            <div>
              <Label>新密码 *</Label>
              <div className="relative mt-2">
                <Input
                  type={showNewPassword ? 'text' : 'password'}
                  value={passwordForm.newPassword}
                  onChange={(e) => setPasswordForm({ ...passwordForm, newPassword: e.target.value })}
                  placeholder="请输入新密码（至少8位）"
                  className="pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShowNewPassword(!showNewPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  {showNewPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>

              {/* 密码强度指示 */}
              {passwordForm.newPassword && (
                <div className="mt-3 space-y-2">
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-muted-foreground">密码强度：</span>
                    <Badge className={`${getStrengthBg(strength)} ${getStrengthColor(strength)}`}>
                      {getStrengthText(strength)}
                    </Badge>
                  </div>
                  
                  <div className="space-y-1.5">
                    <div className={`flex items-center gap-2 text-sm ${checks.length ? 'text-green-600' : 'text-gray-400'}`}>
                      {checks.length ? <CheckCircle className="w-4 h-4" /> : <XCircle className="w-4 h-4" />}
                      <span>至少8个字符</span>
                    </div>
                    <div className={`flex items-center gap-2 text-sm ${checks.hasUpper ? 'text-green-600' : 'text-gray-400'}`}>
                      {checks.hasUpper ? <CheckCircle className="w-4 h-4" /> : <XCircle className="w-4 h-4" />}
                      <span>包含大写字母</span>
                    </div>
                    <div className={`flex items-center gap-2 text-sm ${checks.hasLower ? 'text-green-600' : 'text-gray-400'}`}>
                      {checks.hasLower ? <CheckCircle className="w-4 h-4" /> : <XCircle className="w-4 h-4" />}
                      <span>包含小写字母</span>
                    </div>
                    <div className={`flex items-center gap-2 text-sm ${checks.hasNumber ? 'text-green-600' : 'text-gray-400'}`}>
                      {checks.hasNumber ? <CheckCircle className="w-4 h-4" /> : <XCircle className="w-4 h-4" />}
                      <span>包含数字</span>
                    </div>
                    <div className={`flex items-center gap-2 text-sm ${checks.hasSpecial ? 'text-green-600' : 'text-gray-400'}`}>
                      {checks.hasSpecial ? <CheckCircle className="w-4 h-4" /> : <XCircle className="w-4 h-4" />}
                      <span>包含特殊字符</span>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* 确认密码 */}
            <div>
              <Label>确认新密码 *</Label>
              <div className="relative mt-2">
                <Input
                  type={showConfirmPassword ? 'text' : 'password'}
                  value={passwordForm.confirmPassword}
                  onChange={(e) => setPasswordForm({ ...passwordForm, confirmPassword: e.target.value })}
                  placeholder="请再次输入新密码"
                  className="pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  {showConfirmPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
              {passwordForm.confirmPassword && passwordForm.newPassword !== passwordForm.confirmPassword && (
                <p className="text-sm text-red-600 mt-2 flex items-center gap-1">
                  <XCircle className="w-4 h-4" />
                  两次输入的密码不一致
                </p>
              )}
            </div>

            {/* 安全提示 */}
            <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
              <div className="flex items-start gap-2">
                <AlertTriangle className="w-4 h-4 text-yellow-600 flex-shrink-0 mt-0.5" />
                <p className="text-sm text-yellow-800">
                  修改密码后需要重新登录，请确保记住新密码
                </p>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowPasswordDialog(false)}>
              取消
            </Button>
            <Button onClick={handleConfirmChangePassword}>
              确认修改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
