import { useEffect, useState } from 'react';
import { useNavigate, useLocation, Link, useSearchParams } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import { resolvePostLoginPath } from '@/lib/dashboardNavigation';
import {
  INSTITUTIONAL_EMAIL_HINT,
  validateInstitutionalEmail,
} from '@/auth/institutionalEmail';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Separator } from '@/components/ui/separator';
import { LogIn, AlertCircle } from 'lucide-react';

/**
 * Login-only entry; registration with OTP lives under `/register` and `/admin/register`.
 */
export function LoginRegisterCard() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  useEffect(() => {
    if (searchParams.get('mode') === 'register') {
      navigate('/register', { replace: true });
    }
  }, [searchParams, navigate]);

  const [loginEmail, setLoginEmail] = useState('');
  const [loginPassword, setLoginPassword] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const { login } = useAuth();
  const location = useLocation();
  const fromPathname = (location.state as { from?: { pathname: string } })?.from?.pathname;

  const loginEmailTrimmed = loginEmail.trim();
  const loginPasswordFilled = loginPassword.trim().length > 0;
  const canSubmitLogin = loginEmailTrimmed.length > 0 && loginPasswordFilled;

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setIsLoading(true);
    try {
      const email = loginEmailTrimmed.toLowerCase();
      if (!loginEmailTrimmed) {
        setError('Vui lòng nhập email.');
        return;
      }
      if (!loginPasswordFilled) {
        setError('Vui lòng nhập mật khẩu.');
        return;
      }
      if (!validateInstitutionalEmail(email)) {
        setError('Vui lòng dùng email UMP hoặc UMC (đuôi @ump.edu.vn / @umc.edu.vn).');
        return;
      }
      const result = await login(email, loginPassword);
      if (result.success && result.activeRole) {
        navigate(resolvePostLoginPath(result.activeRole, fromPathname), { replace: true });
        return;
      }
      setError(result.error || 'Đăng nhập thất bại.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-background p-4">
      <div className="w-full max-w-xl">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-foreground">Tài khoản</h1>
          <p className="text-muted-foreground mt-2">Đăng nhập với email UMP hoặc UMC</p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <LogIn className="h-5 w-5" />
              Truy cập hệ thống
            </CardTitle>
            <CardDescription>
              <p className="text-xs text-muted-foreground">{INSTITUTIONAL_EMAIL_HINT}</p>
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleLogin} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="login-email">Tài Khoản</Label>
                <Input
                  id="login-email"
                  type="email"
                  autoComplete="username"
                  placeholder="Email UMP / UMC"
                  value={loginEmail}
                  onChange={(e) => setLoginEmail(e.target.value)}
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="login-password">Mật khẩu</Label>
                <Input
                  id="login-password"
                  type="password"
                  autoComplete="current-password"
                  placeholder="password"
                  value={loginPassword}
                  onChange={(e) => setLoginPassword(e.target.value)}
                  required
                />
              </div>

              {error && (
                <Alert variant="destructive">
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>{error}</AlertDescription>
                </Alert>
              )}

              <div className="flex flex-col items-center gap-3">
                <Button type="submit" disabled={isLoading || !canSubmitLogin}>
                  {isLoading ? 'Đang xử lý...' : 'Đăng nhập'}
                </Button>
                <Link
                  to="/forgot-password"
                  className="text-sm text-muted-foreground hover:text-foreground underline-offset-4 hover:underline"
                >
                  Quên mật khẩu?
                </Link>
              </div>
            </form>

            <Separator className="my-6" />

            <div className="flex gap-2 text-center justify-center text-sm">
              <span className="text-muted-foreground">Chưa có tài khoản?</span>
              <div className="flex flex-col sm:flex-row gap-2 justify-center">
                <Button variant="outline" asChild>
                  <Link to="/admin/register">Đăng ký - Quản trị</Link>
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        <Separator className="my-6" />

        <div className="text-center space-y-2">
          <Link to="/" className="text-sm text-muted-foreground hover:text-foreground block">
            ← Quay về trang chủ
          </Link>
        </div>
      </div>
    </div>
  );
}
