'use client';

import React, { Suspense, useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Alert, Button, Form, Input, Spin } from 'antd';
import { AuthCard } from '../../components/auth/AuthCard';
import { useAuth } from '../../context/AuthContext';

interface LoginFormValues {
  email: string;
  password: string;
}

function LoginFormContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { user, isAuthenticated, isLoading: authLoading, login, authError, sessionExpired, clearAuthError } = useAuth();

  const [form] = Form.useForm<LoginFormValues>();
  const [submitting, setSubmitting] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [dismissedExpiry, setDismissedExpiry] = useState(false);

  const expiredFromQuery = searchParams.get('expired') === '1';
  const showExpiryAlert = !dismissedExpiry && !errorMsg && (expiredFromQuery || sessionExpired);

  useEffect(() => {
    if (!authLoading && isAuthenticated && user) {
      router.replace(user.role === 'PLATFORM_ADMIN' ? '/platform' : '/app');
    }
  }, [authLoading, isAuthenticated, user, router]);

  const handleSubmit = async (values: LoginFormValues) => {
    setSubmitting(true);
    setErrorMsg(null);
    clearAuthError();

    try {
      const signedInUser = await login(values.email, values.password);
      router.push(signedInUser.role === 'PLATFORM_ADMIN' ? '/platform' : '/app');
    } catch (err: unknown) {
      const message = err instanceof Error && err.message ? err.message : 'Sign in failed. Please check your credentials and try again.';
      setErrorMsg(message);
    } finally {
      setSubmitting(false);
    }
  };

  if (authLoading || (isAuthenticated && user)) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-page">
        <Spin size="large" />
      </div>
    );
  }

  return (
    <AuthCard title="Welcome back" subtitle="Sign in to your workspace to continue.">
      {showExpiryAlert ? (
        <Alert
          title={authError || 'Your session ended. Please sign in again.'}
          type="warning"
          showIcon
          className="mb-4"
          closable={{
            onClose: () => {
              setDismissedExpiry(true);
              clearAuthError();
            },
          }}
        />
      ) : null}

      {errorMsg ? <Alert title={errorMsg} type="error" showIcon className="mb-4" closable={{ onClose: () => setErrorMsg(null) }} /> : null}

      <Form form={form} layout="vertical" size="large" onFinish={handleSubmit}>
        <Form.Item
          label="Work email"
          name="email"
          rules={[
            { required: true, message: 'Enter your work email' },
            { type: 'email', message: 'Enter a valid email address' },
          ]}
          className="mb-4"
        >
          <Input placeholder="name@company.com" autoComplete="email" autoFocus disabled={submitting} />
        </Form.Item>

        <Form.Item label="Password" name="password" rules={[{ required: true, message: 'Enter your password' }]} className="mb-3">
          <Input.Password autoComplete="current-password" placeholder="Enter your password" disabled={submitting} />
        </Form.Item>

        <div className="mb-4 flex justify-end">
          <Link href="/forgot-password" className="text-[13px] text-primary hover:underline">
            Forgot password?
          </Link>
        </div>

        <Button type="primary" htmlType="submit" block loading={submitting}>
          {submitting ? 'Signing in…' : 'Sign in'}
        </Button>
      </Form>
    </AuthCard>
  );
}

export default function LoginPage() {
  return (
    <Suspense
      fallback={
        <div className="flex min-h-screen items-center justify-center bg-page">
          <Spin size="large" />
        </div>
      }
    >
      <LoginFormContent />
    </Suspense>
  );
}
