import { Button, Input, Typography, Form, Card, App } from 'antd';
import { LockOutlined, UserOutlined, MailOutlined, SafetyOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import jwtAxios, { setAuthToken } from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';
import { BANNER_URL, LOGO_URL } from '../../config/env';
import { useAppDispatch } from '../../redux/hooks';
import { initializeAuth, loginUser } from '../../redux/slices/authSlice';

const { Text } = Typography;

type View = 'login' | 'forgot-email' | 'forgot-otp' | 'forgot-reset';

export default function LoginPage() {
  const { message } = App.useApp();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const [loading, setLoading] = useState(false);
  const [view, setView] = useState<View>('login');

  const [loginForm] = Form.useForm();
  const [emailForm] = Form.useForm();
  const [otpForm] = Form.useForm();
  const [resetForm] = Form.useForm();

  const [resetEmail, setResetEmail] = useState('');
  const [verifiedOtp, setVerifiedOtp] = useState('');

  const [resendTimer, setResendTimer] = useState(0);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const banner = BANNER_URL;

  const handleApiError = (err: any, targetForm?: any) => {
    const status = err.response?.status;
    const responseData = err.response?.data;

    if (status === 422 && responseData?.errors && targetForm) {
      targetForm.setFields(
        Object.entries(responseData.errors).map(([name, error]) => ({
          name,
          errors: [String(error)],
        }))
      );
      message.error(responseData?.message || 'Please fix the highlighted fields');
    } else {
      message.error(responseData?.message || 'Something went wrong');
    }
  };

  type LoginFormValues = {
    email: string;
    password: string;
    rememberMe?: boolean;
  };

  const handleLogin = async (values: LoginFormValues) => {
    setLoading(true);
    try {
      const resultAction = await dispatch(
        loginUser({ email: values.email, password: values.password })
      );

      if (loginUser.fulfilled.match(resultAction)) {
        const token = resultAction.payload.accessToken;
        if (token) {
          setAuthToken(token);
        }
        dispatch(initializeAuth());
        message.success('Login successful');
        navigate('/dashboard', { replace: true });
      } else {
        const errorMsg = (resultAction.payload as string) || 'Login failed';
        message.error(errorMsg);
      }
    } catch (err: any) {
      message.error(err.message || 'Login failed');
    } finally {
      setLoading(false);
    }
  };

  const startResendTimer = (expiresAt?: string) => {
    let seconds = 60;
    if (expiresAt) {
      const diff = Math.floor((new Date(expiresAt).getTime() - Date.now()) / 1000);
      seconds = diff > 0 ? Math.min(diff, 60) : 60;
    }
    setResendTimer(seconds);
    if (timerRef.current) clearInterval(timerRef.current);
    timerRef.current = setInterval(() => {
      setResendTimer((prev) => {
        if (prev <= 1) {
          if (timerRef.current) clearInterval(timerRef.current);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  useEffect(() => {
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, []);

  const handleSendOtp = async (values: { email: string }) => {
    setLoading(true);
    try {
      const res = await jwtAxios.post(ENDPOINTS.FORGOT_PASSWORD_SEND_OTP, {
        email: values.email,
      });

      const otpData = res.data?.otpData;
      message.success(res.data?.message || 'OTP sent successfully');

      setResetEmail(values.email);
      otpForm.resetFields();
      startResendTimer(otpData?.expiresAt);
      setView('forgot-otp');
    } catch (err: any) {
      handleApiError(err, emailForm);
    } finally {
      setLoading(false);
    }
  };

  const handleResendOtp = async () => {
    if (resendTimer > 0) return;
    setLoading(true);
    try {
      const res = await jwtAxios.post(ENDPOINTS.FORGOT_PASSWORD_SEND_OTP, {
        email: resetEmail,
      });
      const otpData = res.data?.otpData;
      message.success(res.data?.message || 'OTP resent');
      startResendTimer(otpData?.expiresAt);
    } catch (err: any) {
      handleApiError(err);
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyOtp = async (values: { otp: string }) => {
    setLoading(true);
    try {
      const res = await jwtAxios.post(ENDPOINTS.FORGOT_PASSWORD_VERIFY_OTP, {
        email: resetEmail,
        otp: values.otp,
      });

      message.success(res.data?.message || 'OTP verified successfully');
      setVerifiedOtp(values.otp);
      resetForm.resetFields();
      setView('forgot-reset');
    } catch (err: any) {
      handleApiError(err, otpForm);
    } finally {
      setLoading(false);
    }
  };

  const handleResetPassword = async (values: { password: string; confirmPassword: string }) => {
    setLoading(true);
    try {
      const res = await jwtAxios.post(ENDPOINTS.FORGOT_PASSWORD_RESET, {
        email: resetEmail,
        otp: verifiedOtp,
        password: values.password,
      });

      message.success(res.data?.message || 'Password reset successfully');

      loginForm.resetFields();
      emailForm.resetFields();
      otpForm.resetFields();
      resetForm.resetFields();
      setResetEmail('');
      setVerifiedOtp('');
      setView('login');
    } catch (err: any) {
      const msg = err.response?.data?.message;
      if (msg === 'OTP has expired' || msg === 'Max attempts reached try with new OTP' || msg === 'Invalid OTP') {
        message.error(`${msg}. Please verify your OTP again.`);
        setView('forgot-otp');
      } else {
        handleApiError(err, resetForm);
      }
    } finally {
      setLoading(false);
    }
  };

  const backToLogin = () => {
    setResetEmail('');
    setVerifiedOtp('');
    setResendTimer(0);
    if (timerRef.current) clearInterval(timerRef.current);
    emailForm.resetFields();
    otpForm.resetFields();
    resetForm.resetFields();
    setView('login');
  };

  return (
    // 1. Strictly 100% of viewport height — never grows taller than the screen
    <div className="h-screen flex bg-white overflow-hidden">
      {/* 2. Left side stays fixed at full height, never scrolls */}
      <div className="hidden lg:flex lg:w-1/2 h-full bg-linear-to-b from-green-100 to-green-50">
        <img
          src={banner}
          alt="Vegetables"
          className="w-full h-full object-cover"
        />
      </div>

      {/* 3. Only this column scrolls if its content is taller than the screen */}
      <div className="w-full lg:w-1/2 h-full overflow-y-auto flex items-center justify-center px-4 sm:px-8 py-8">
        <div className="w-full max-w-md">
          <Card className="p-6 shadow-lg rounded-lg">
            {/* Header */}
            <div className="text-center mb-8">
              <img
                src={LOGO_URL}
                alt="Logo"
                className="w-32.5 h-auto object-cover mx-auto mb-2"
              />
              {view === 'login' && (
                <Text className="text-gray-400! text-base!">
                  Fill the credentials below to log into AVS Enterprise
                </Text>
              )}
              {view === 'forgot-email' && (
                <Text className="text-gray-400! text-base!">
                  Enter your registered email to receive an OTP
                </Text>
              )}
              {view === 'forgot-otp' && (
                <Text className="text-gray-400! text-base!">
                  Enter the 6-digit OTP sent to <strong>{resetEmail}</strong>
                </Text>
              )}
              {view === 'forgot-reset' && (
                <Text className="text-gray-400! text-base!">
                  Set a new password for your account
                </Text>
              )}
            </div>

            {/* ---------------- LOGIN ---------------- */}
            {view === 'login' && (
              <Form form={loginForm} layout="vertical" onFinish={handleLogin} className="space-y-4">
                <Form.Item
                  label={<span className="font-medium! text-gray-700!">User ID</span>}
                  name="email"
                  rules={[
                    { required: true, message: 'Please enter your email' },
                    { type: 'email', message: 'Please enter a valid email' },
                  ]}
                >
                  <Input
                    prefix={<UserOutlined />}
                    placeholder="Enter your email"
                    size="large"
                    className="rounded-lg"
                  />
                </Form.Item>

                <Form.Item
                  label={<span className="font-medium! text-gray-700!">Password</span>}
                  name="password"
                  rules={[{ required: true, message: 'Please enter your password' }]}
                >
                  <Input.Password
                    prefix={<LockOutlined />}
                    placeholder="Enter your password"
                    size="large"
                    className="rounded-lg"
                  />
                </Form.Item>

                <Form.Item className="mb-4!">
                  <Button type="primary" htmlType="submit" block size="large" loading={loading}>
                    {loading ? 'Signing in...' : 'Log in'}
                  </Button>
                </Form.Item>

                <div className="text-center">
                  <button
                    type="button"
                    onClick={() => setView('forgot-email')}
                    className="text-red-600 text-sm! font-medium! hover:text-red-700! bg-transparent border-0! cursor-pointer!"
                  >
                    Forgot your password?
                  </button>
                </div>
              </Form>
            )}

            {/* ---------------- STEP 1: EMAIL ---------------- */}
            {view === 'forgot-email' && (
              <Form form={emailForm} layout="vertical" onFinish={handleSendOtp} className="space-y-4">
                <Form.Item
                  label={<span className="font-medium! text-gray-700!">Email</span>}
                  name="email"
                  rules={[
                    { required: true, message: 'Please enter your email' },
                    { type: 'email', message: 'Please enter a valid email' },
                  ]}
                >
                  <Input
                    prefix={<MailOutlined />}
                    placeholder="Enter your registered email"
                    size="large"
                    className="rounded-lg"
                  />
                </Form.Item>

                <Form.Item className="mb-4!">
                  <Button type="primary" htmlType="submit" block size="large" loading={loading}>
                    {loading ? 'Sending OTP...' : 'Send OTP'}
                  </Button>
                </Form.Item>

                <div className="text-center">
                  <button
                    type="button"
                    onClick={backToLogin}
                    className="text-gray-600 text-sm font-medium hover:text-gray-800 bg-transparent border-0 cursor-pointer inline-flex items-center gap-1"
                  >
                    <ArrowLeftOutlined /> Back to login
                  </button>
                </div>
              </Form>
            )}

            {/* ---------------- STEP 2: OTP ---------------- */}
            {view === 'forgot-otp' && (
              <Form form={otpForm} layout="vertical" onFinish={handleVerifyOtp} className="space-y-4">
                <Form.Item
                  label={<span className="font-medium! text-gray-700!">OTP</span>}
                  name="otp"
                  rules={[
                    { required: true, message: 'Please enter the OTP' },
                    { pattern: /^[0-9]{6}$/, message: 'OTP must be 6 digits' },
                  ]}
                >
                  <Input
                    prefix={<SafetyOutlined />}
                    placeholder="Enter 6-digit OTP"
                    size="large"
                    className="rounded-lg"
                    maxLength={6}
                  />
                </Form.Item>

                <Form.Item className="mb-4!">
                  <Button type="primary" htmlType="submit" block size="large" loading={loading}>
                    {loading ? 'Verifying...' : 'Verify OTP'}
                  </Button>
                </Form.Item>

                <div className="flex items-center justify-between text-sm">
                  <button
                    type="button"
                    onClick={backToLogin}
                    className="text-gray-600 font-medium hover:text-gray-800 bg-transparent border-0 cursor-pointer inline-flex items-center gap-1"
                  >
                    <ArrowLeftOutlined /> Back to login
                  </button>

                  <button
                    type="button"
                    onClick={handleResendOtp}
                    disabled={resendTimer > 0 || loading}
                    className={`bg-transparent border-0 font-medium ${resendTimer > 0
                      ? 'text-gray-400 cursor-not-allowed'
                      : 'text-red-600 hover:text-red-700 cursor-pointer'
                      }`}
                  >
                    {resendTimer > 0 ? `Resend OTP (${resendTimer}s)` : 'Resend OTP'}
                  </button>
                </div>
              </Form>
            )}

            {/* ---------------- STEP 3: RESET PASSWORD ---------------- */}
            {view === 'forgot-reset' && (
              <Form form={resetForm} layout="vertical" onFinish={handleResetPassword} className="space-y-4">
                <Form.Item
                  label={<span className="font-medium! text-gray-700!">New Password</span>}
                  name="password"
                  rules={[
                    { required: true, message: 'Please enter a new password' },
                    { min: 6, message: 'Password must be at least 6 characters' },
                  ]}
                >
                  <Input.Password
                    prefix={<LockOutlined />}
                    placeholder="Enter new password"
                    size="large"
                    className="rounded-lg"
                    autoComplete="new-password"
                  />
                </Form.Item>

                <Form.Item
                  label={<span className="font-medium! text-gray-700!">Confirm Password</span>}
                  name="confirmPassword"
                  dependencies={['password']}
                  rules={[
                    { required: true, message: 'Please confirm your new password' },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('Passwords do not match'));
                      },
                    }),
                  ]}
                >
                  <Input.Password
                    prefix={<LockOutlined />}
                    placeholder="Re-enter new password"
                    size="large"
                    className="rounded-lg"
                    autoComplete="new-password"
                  />
                </Form.Item>

                <Form.Item className="mb-4!">
                  <Button type="primary" htmlType="submit" block size="large" loading={loading}>
                    {loading ? 'Resetting...' : 'Reset Password'}
                  </Button>
                </Form.Item>

                <div className="text-center">
                  <button
                    type="button"
                    onClick={backToLogin}
                    className="text-gray-600 text-sm font-medium hover:text-gray-800 bg-transparent border-0 cursor-pointer inline-flex items-center gap-1"
                  >
                    <ArrowLeftOutlined /> Back to login
                  </button>
                </div>
              </Form>
            )}

            {/* Footer */}
            <div className="text-center mt-8">
              <Text type="secondary" className="text-xs! text-gray-500!">
                © 2026 AVS Enterprise Created by <a href="https://techcmantix.com/" target="_blank" rel="noopener noreferrer">Techcmantix pvt ltd</a>
              </Text>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}