'use client';

import { 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 { toast } from '@/lib/toast';
import { Eye, EyeOff, AlertCircle } from 'lucide-react';
import { resetUserPassword } from '@/services/api/organization';
import { ApiClientError } from '@/lib/api-client';
import { useTranslation } from '@/hooks/useTranslation';

interface ResetPasswordDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  userId: string;
  userName: string;
}

export function ResetPasswordDialog({ open, onOpenChange, userId, userName }: ResetPasswordDialogProps) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  // 密码强度检测
  const checkPasswordStrength = (password: string) => {
    let strength = 0;
    if (password.length >= 8) strength++;
    if (/[a-z]/.test(password)) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/[0-9]/.test(password)) strength++;
    
    if (strength <= 2) return { level: 'weak', color: 'text-red-500' };
    if (strength === 3) return { level: 'medium', color: 'text-yellow-500' };
    return { level: 'strong', color: 'text-green-500' };
  };

  const passwordStrength = checkPasswordStrength(newPassword);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

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

    if (newPassword !== confirmPassword) {
      toast.error('两次密码输入不一致');
      return;
    }

    // 验证密码强度
    const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
    if (!regex.test(newPassword)) {
      toast.error('密码强度不足');
      return;
    }

    try {
      setLoading(true);
      await resetUserPassword(userId, newPassword);
      toast.success('密码重置成功');
      handleClose();
    } catch (error) {
      console.error('Failed to reset password:', error);
      if (error instanceof ApiClientError) {
        toast.error(`${'重置失败'}: ${error.message}`);
      } else {
        toast.error('重置密码失败');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    setNewPassword('');
    setConfirmPassword('');
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>
            {'重置密码'} - {userName}
          </DialogTitle>
          <DialogDescription>
            {'请为用户设置新密码'}
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4 pt-4">
          {/* 新密码 */}
          <div className="space-y-2">
            <Label htmlFor="newPassword">
              {'新密码'} *
            </Label>
            <div className="relative">
              <Input
                id="newPassword"
                type={showNewPassword ? 'text' : 'password'}
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                required
                className="pr-10"
              />
              <button
                type="button"
                onClick={() => setShowNewPassword(!showNewPassword)}
                className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
              >
                {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
            
            {/* 密码强度指示器 */}
            {newPassword && (
              <div className="flex items-center gap-2 text-sm">
                <span className="text-gray-600">{'密码强度'}:</span>
                <span className={passwordStrength.color}>
                  {passwordStrength.level === 'weak' 
                    ? ('弱')
                    : passwordStrength.level === 'medium' 
                    ? ('中')
                    : ('强')}
                </span>
              </div>
            )}
          </div>

          {/* 确认新密码 */}
          <div className="space-y-2">
            <Label htmlFor="confirmPassword">
              {'确认新密码'} *
            </Label>
            <div className="relative">
              <Input
                id="confirmPassword"
                type={showConfirmPassword ? 'text' : 'password'}
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                required
                className="pr-10"
              />
              <button
                type="button"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
              >
                {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
            
            {/* 密码匹配提示 */}
            {confirmPassword && newPassword !== confirmPassword && (
              <div className="flex items-center gap-2 text-sm text-red-600">
                <AlertCircle className="h-4 w-4" />
                {'两次密码输入不一致'}
              </div>
            )}
          </div>

          {/* 密码规则提示 */}
          <div className="rounded-lg border border-blue-200 bg-blue-50 p-3">
            <div className="text-sm font-medium text-blue-900 mb-2">
              {'密码规则'}:
            </div>
            <ul className="text-sm text-blue-700 space-y-1">
              <li className="flex items-center gap-2">
                <span className={newPassword.length >= 8 ? 'text-green-600' : ''}>
                  {newPassword.length >= 8 ? '✓' : '•'} {'至少8个字符'}
                </span>
              </li>
              <li className="flex items-center gap-2">
                <span className={/[A-Z]/.test(newPassword) ? 'text-green-600' : ''}>
                  {/[A-Z]/.test(newPassword) ? '✓' : '•'} {'至少一个大写字母'}
                </span>
              </li>
              <li className="flex items-center gap-2">
                <span className={/[a-z]/.test(newPassword) ? 'text-green-600' : ''}>
                  {/[a-z]/.test(newPassword) ? '✓' : '•'} {'至少一个小写字母'}
                </span>
              </li>
              <li className="flex items-center gap-2">
                <span className={/[0-9]/.test(newPassword) ? 'text-green-600' : ''}>
                  {/[0-9]/.test(newPassword) ? '✓' : '•'} {'至少一个数字'}
                </span>
              </li>
            </ul>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={handleClose} disabled={loading}>
              {'取消'}
            </Button>
            <Button type="submit" disabled={loading}>
              {loading 
                ? ('重置中...') 
                : ('确认重置')}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
