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 { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Alert, AlertDescription } from '../ui/alert';
import { CaptchaInput } from './CaptchaInput';
import { useAuth } from './AuthContext';
import { SmartFieldBackground } from './SmartFieldBackground';
import {
  Lock,
  User,
  Phone,
  MessageSquare,
  Eye,
  EyeOff,
  LogIn,
  Loader2,
  Shield,
  Smartphone,
  AlertCircle,
  CheckCircle,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface LoginProps {
  onRegisterClick: () => void;
}

export function Login({ onRegisterClick }: LoginProps) {
  const { login } = useAuth();
  const [loginType, setLoginType] = useState<'password' | 'phone'>('password');
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [error, setError] = useState('');

  // 密码登录表单
  const [passwordForm, setPasswordForm] = useState({
    username: '',
    password: '',
    captcha: '',
  });

  // 手机号登录表单
  const [phoneForm, setPhoneForm] = useState({
    phone: '',
    code: '',
    captcha: '',
  });

  // 发送验证码
  const handleSendCode = async () => {
    if (!phoneForm.phone) {
      toast.error('请输入手机号');
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(phoneForm.phone)) {
      toast.error('请输入正确的手机号');
      return;
    }

    setSendingCode(true);
    setError('');

    try {
      const { sendSmsCode } = await import('../../lib/authStorage');
      const result = await sendSmsCode(phoneForm.phone);
      if (result.success) {
        toast.success(result.message + '（测试验证码：123456）');
        // 开始倒计时
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        setError(result.message);
      }
    } catch (err) {
      setError('发送验证码失败，请稍后重试');
    } finally {
      setSendingCode(false);
    }
  };

  // 密码登录
  const handlePasswordLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!passwordForm.username || !passwordForm.password) {
      setError('请输入用户名和密码');
      return;
    }

    if (!passwordForm.captcha) {
      setError('请输入图形验证码');
      return;
    }

    setLoading(true);

    try {
      const { validatePasswordLogin } = await import('../../lib/authStorage');
      const result = await validatePasswordLogin(
        passwordForm.username,
        passwordForm.password,
        passwordForm.captcha
      );

      if (result.success && result.user) {
        login(result.user);
        toast.success('登录成功！');
      } else {
        setError(result.message);
        toast.error(result.message);
      }
    } catch (err) {
      setError('登录失败，请稍后重试');
      toast.error('登录失败');
    } finally {
      setLoading(false);
    }
  };

  // 手机号登录
  const handlePhoneLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!phoneForm.phone || !phoneForm.code) {
      setError('请输入手机号和验证码');
      return;
    }

    if (!phoneForm.captcha) {
      setError('请输入图形验证码');
      return;
    }

    setLoading(true);

    try {
      const { validatePhoneLogin } = await import('../../lib/authStorage');
      const result = await validatePhoneLogin(
        phoneForm.phone,
        phoneForm.code,
        phoneForm.captcha
      );

      if (result.success && result.user) {
        login(result.user);
        toast.success('登录成功！');
      } else {
        setError(result.message);
        toast.error(result.message);
      }
    } catch (err) {
      setError('登录失败，请稍后重试');
      toast.error('登录失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-4 relative overflow-hidden">
      {/* 智慧大田动态背景 */}
      <SmartFieldBackground />
      
      {/* 内容区域 */}
      <div className="w-full max-w-md relative z-10">
        {/* Logo和标题 */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-white/90 backdrop-blur-sm rounded-2xl mb-4 shadow-lg">
            <Shield className="w-8 h-8 text-success" />
          </div>
          <h1 className="text-white mb-2 drop-shadow-lg">智慧农业生产管理系统</h1>
          <p className="text-sm text-white/90 drop-shadow-md">安全、智能、高效的农业管理平台</p>
        </div>

        <Card className="p-8 shadow-2xl bg-white/95 backdrop-blur-md border-white/20">
          <Tabs value={loginType} onValueChange={(v) => setLoginType(v as 'password' | 'phone')}>
            <TabsList className="grid w-full grid-cols-2 mb-6">
              <TabsTrigger value="password" className="flex items-center gap-2">
                <Lock className="w-4 h-4" />
                密码登录
              </TabsTrigger>
              <TabsTrigger value="phone" className="flex items-center gap-2">
                <Smartphone className="w-4 h-4" />
                手机登录
              </TabsTrigger>
            </TabsList>

            {error && (
              <Alert className="mb-4 bg-error-muted border-error">
                <AlertCircle className="w-4 h-4 text-error" />
                <AlertDescription className="text-error-muted-foreground">{error}</AlertDescription>
              </Alert>
            )}

            {/* 密码登录 */}
            <TabsContent value="password">
              <form onSubmit={handlePasswordLogin} className="space-y-4">
                <div>
                  <Label>用户名</Label>
                  <div className="relative mt-2">
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                    <Input
                      type="text"
                      placeholder="请输入用户名"
                      value={passwordForm.username}
                      onChange={(e) => setPasswordForm({ ...passwordForm, username: e.target.value })}
                      className="pl-10"
                      disabled={loading}
                    />
                  </div>
                </div>

                <div>
                  <Label>密码</Label>
                  <div className="relative mt-2">
                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                    <Input
                      type={showPassword ? 'text' : 'password'}
                      placeholder="请输入密码"
                      value={passwordForm.password}
                      onChange={(e) => setPasswordForm({ ...passwordForm, password: e.target.value })}
                      className="pl-10 pr-10"
                      disabled={loading}
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                    >
                      {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                    </button>
                  </div>
                </div>

                <div>
                  <Label>图形验证码</Label>
                  <CaptchaInput
                    value={passwordForm.captcha}
                    onChange={(value) => setPasswordForm({ ...passwordForm, captcha: value })}
                    className="mt-2"
                  />
                </div>

                <Button type="submit" className="w-full bg-success hover:bg-success/90" disabled={loading}>
                  {loading ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      登录中...
                    </>
                  ) : (
                    <>
                      <LogIn className="w-4 h-4 mr-2" />
                      登录
                    </>
                  )}
                </Button>
              </form>

              <div className="mt-4 text-center">
                <p className="text-sm text-muted-foreground">
                  测试账号：admin / admin123 或 zhangsan / zhang123
                </p>
              </div>
            </TabsContent>

            {/* 手机号登录 */}
            <TabsContent value="phone">
              <form onSubmit={handlePhoneLogin} className="space-y-4">
                <div>
                  <Label>手机号</Label>
                  <div className="relative mt-2">
                    <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                    <Input
                      type="tel"
                      placeholder="请输入手机号"
                      value={phoneForm.phone}
                      onChange={(e) => setPhoneForm({ ...phoneForm, phone: e.target.value })}
                      className="pl-10"
                      maxLength={11}
                      disabled={loading}
                    />
                  </div>
                </div>

                <div>
                  <Label>短信验证码</Label>
                  <div className="flex gap-2 mt-2">
                    <div className="relative flex-1">
                      <MessageSquare className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                      <Input
                        type="text"
                        placeholder="请输入验证码"
                        value={phoneForm.code}
                        onChange={(e) => setPhoneForm({ ...phoneForm, code: e.target.value })}
                        className="pl-10"
                        maxLength={6}
                        disabled={loading}
                      />
                    </div>
                    <Button
                      type="button"
                      variant="outline"
                      onClick={handleSendCode}
                      disabled={sendingCode || countdown > 0 || loading}
                      className="min-w-[120px]"
                    >
                      {sendingCode ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : countdown > 0 ? (
                        `${countdown}秒后重试`
                      ) : (
                        '发送验证码'
                      )}
                    </Button>
                  </div>
                </div>

                <div>
                  <Label>图形验证码</Label>
                  <CaptchaInput
                    value={phoneForm.captcha}
                    onChange={(value) => setPhoneForm({ ...phoneForm, captcha: value })}
                    className="mt-2"
                  />
                </div>

                <Button type="submit" className="w-full bg-success hover:bg-success/90" disabled={loading}>
                  {loading ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      登录中...
                    </>
                  ) : (
                    <>
                      <LogIn className="w-4 h-4 mr-2" />
                      登录
                    </>
                  )}
                </Button>
              </form>

              <div className="mt-4 text-center">
                <p className="text-sm text-muted-foreground">
                  测试手机号：13800138000 或 13800138001，验证码：123456
                </p>
              </div>
            </TabsContent>
          </Tabs>

          {/* 注册入口 */}
          <div className="mt-6 pt-6 border-t text-center">
            <p className="text-sm text-muted-foreground">
              还没有账号？{' '}
              <button
                onClick={onRegisterClick}
                className="text-success hover:text-success/90 hover:underline"
              >
                立即注册
              </button>
            </p>
          </div>

          {/* 安全提示 */}
          <div className="mt-4 p-3 bg-info-muted rounded-lg">
            <div className="flex items-start gap-2">
              <Shield className="w-4 h-4 text-info flex-shrink-0 mt-0.5" />
              <div className="text-xs text-info-muted-foreground">
                <p className="mb-1">安全保障：</p>
                <ul className="space-y-0.5">
                  <li>• 登录信息加密传输</li>
                  <li>• 会话自动管理，24小时有效期</li>
                  <li>• 记录登录IP、设备信息用于安全审计</li>
                </ul>
              </div>
            </div>
          </div>
        </Card>

        {/* 页脚 */}
        <div className="mt-6 text-center text-xs text-white/80 drop-shadow-md">
          <p>© 2024 智慧农业生产管理系统. All rights reserved.</p>
        </div>
      </div>
    </div>
  );
}
