import { useState } from 'react';
import { useNavigate, useLocation, Link } from 'react-router-dom';

import { useAuth } from './AuthProvider';
import { detailFromApiError } from '../api/client';
import {
  INSTITUTIONAL_EMAIL_HINT,
  validateInstitutionalEmail,
} from './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 card — visual port of fe0/src/auth/LoginRegisterCard.tsx.
 *
 * The markup/className tree is preserved verbatim so the screen looks identical to fe0.
 * Behavior is simplified to a working email+password login against the shared
 * `useAuth().login` kernel (see the porting notes in the implementer report):
 *   - `login()` resolves to the user (and throws on failure) instead of fe0's
 *     `{ success, activeRole, error }` shape, so success navigates to `/` and
 *     failures surface via `detailFromApiError`.
 *   - fe0's role-based post-login routing (`resolvePostLoginPath`) is dropped —
 *     the app shells route everyone to `/`.
 *   - The forgot-password / home links are real `<Link>`s to the `/forgot-password`
 *     and `/` routes the app shells now mount. The register link is app-specific:
 *     each shell passes `registerPath`/`registerLabel` (frontend_user → `/register`,
 *     frontend_admin → `/admin/register`); when omitted the button stays disabled.
 */
export interface LoginRegisterCardProps {
  /** Route the "Đăng ký" button links to. When omitted the button is rendered disabled. */
  registerPath?: string;
  /** Label for the register button (defaults to "Đăng ký - Quản trị" to match fe0). */
  registerLabel?: string;
}

export function LoginRegisterCard({ registerPath, registerLabel = 'Đăng ký - Quản trị' }: LoginRegisterCardProps = {}) {
  const navigate = useNavigate();

  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;
      }
      await login(email, loginPassword);
      const target = fromPathname && fromPathname !== '/login' ? fromPathname : '/';
      navigate(target, { replace: true });
    } catch (err) {
      setError(detailFromApiError(err, 'Đă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">
                {registerPath ? (
                  <Button variant="outline" asChild>
                    <Link to={registerPath}>{registerLabel}</Link>
                  </Button>
                ) : (
                  <Button variant="outline" disabled>
                    {registerLabel}
                  </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>
  );
}
