'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import { useForm } from "react-hook-form";
import { useToast } from '@/context/ToastContext';
import { Modal, Button, Form, Row, Col, FloatingLabel, Stack, Spinner } from 'react-bootstrap';
import { useRecaptcha } from "@/hooks/useRecaptcha";

interface SignModalProps {
  show: boolean;
  handleClose: () => void;
  isForgot: boolean;
  setIsForgot: (value: boolean) => void;
}
type FormData = {
  email: string;
  password: string;
  otp: string;
};

const LoginModal: React.FC<SignModalProps> = ({ show, handleClose, isForgot, setIsForgot }) => {
  const router = useRouter();
  const { showToast } = useToast();
  const { getToken } = useRecaptcha();

  const [step, setStep] = useState<"email" | "otp" | "reset">("email");
  const [email, setEmail] = useState("");
  const [isSendingOtp, setIsSendingOtp] = useState(false);
  const [isVerifyingOtp, setIsVerifyingOtp] = useState(false);
  const [isResettingPassword, setIsResettingPassword] = useState(false);
  const { register,handleSubmit,formState: { errors, isSubmitting },reset,} = useForm<FormData>();

  /* ================= LOGIN ================= */
  const handleLoginSubmit = async (data: FormData) => {
    const recaptchaToken = await getToken("login_form");

    const res = await fetch("/api/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ...data,
        provider: "credentials",
        recaptchaToken
      }),
    });

    const result = await res.json();

    if (res.ok) {
      showToast(result.message, "success");
      reset();
      handleClose();
      router.push("/cms");
      window.dispatchEvent(new Event("userLoggedIn"));
    } else {
      showToast(result.error || "Login failed", "danger");
      if (result.status === 403) setIsForgot(true);
    }
  };

  /* ================= FORGOT EMAIL ================= */
  const handleForgotEmailSubmit = async ({ email }: FormData) => {
    setIsSendingOtp(true);

    const recaptchaToken = await getToken("forget_form");

    const res = await fetch("/api/auth/forget", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, recaptchaToken }),
    });

    const result = await res.json();
    setIsSendingOtp(false);

    if (res.ok) {
      showToast(result.message, "success");
      setEmail(email);
      setStep("otp");
    } else {
      showToast(result.error || "Failed to send OTP", "danger");
    }
  };

  /* ================= OTP VERIFY ================= */
  const handleOtpVerifySubmit = async ({ otp }: FormData) => {
    setIsVerifyingOtp(true);

    const recaptchaToken = await getToken("verify_otp_form");

    const res = await fetch("/api/auth/verify-otp", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        entity: email,
        otp,
        recaptchaToken
      }),
    });

    const result = await res.json();
    setIsVerifyingOtp(false);

    if (res.ok) {
      showToast(result.message, "success");
      setStep("reset");
    } else {
      showToast(result.error, "danger");
    }
  };

  /* ================= RESET PASSWORD ================= */
  const handleResetPasswordSubmit = async ({ password }: FormData) => {
    setIsResettingPassword(true);

    const recaptchaToken = await getToken("reset_password_form");

    const res = await fetch("/api/auth/reset-password", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        email,
        password,
        recaptchaToken
      }),
    });

    const result = await res.json();
    setIsResettingPassword(false);

    if (res.ok) {
      showToast(result.message, "success");
      setIsForgot(false);
      setStep("email");
      reset();
    } else {
      showToast(result.error, "danger");
    }
  };
  return (
    <Modal className="modal-signin" show={show} onHide={handleClose} centered backdrop="static" keyboard={false}>
      <Modal.Body className="p-4">
        {!isForgot ? (
          <Form noValidate onSubmit={handleSubmit(handleLoginSubmit)} id="SignForm">
            <Row className="g-4">
              <Col md={12} className="d-flex justify-content-between">
                <div>
                  <motion.h3>Sign In</motion.h3>
                  <motion.div>New user? <Link href="/register">Create an account</Link></motion.div>
                </div>          
                <motion.div whileInView={{x:[-30,0]}} transition={{duration:1.8}}>
                  <Button type="button" className="btn-close" aria-label="Close" onClick={handleClose}></Button>
                </motion.div>
              </Col>
              <Col md={12}>
                <motion.div whileInView={{y:[30,0]}} transition={{duration:1.4}}>
                  <FloatingLabel label="Email address">
                    <Form.Control type="email" {...register("email", { required: "Email is required", pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: "Invalid email format",},})} isInvalid={!!errors.email} />
                    <Form.Control.Feedback type="invalid">{errors.email?.message}</Form.Control.Feedback>
                  </FloatingLabel>
                </motion.div>
              </Col>
              <Col md={12}>
                <motion.div whileInView={{y:[30,0]}} transition={{duration:1.6}}>
                  <FloatingLabel label="Password">
                    <Form.Control type="password" {...register("password", { required: "Password is required" })} isInvalid={!!errors.password} />
                    <Form.Control.Feedback type="invalid">{errors.password?.message}</Form.Control.Feedback>
                  </FloatingLabel>
                </motion.div>
              </Col>
              <Col md={12} className="d-flex align-items-center justify-content-between">
                <motion.div whileInView={{scale:[0.2,1]}} transition={{duration:1.8}}>
                  <Button variant="link" className="p-0 text-decoration-none" onClick={() => setIsForgot(true)}>
                    Forgot password?
                  </Button>
                </motion.div>
                <motion.div whileInView={{x:[-30,0]}} transition={{duration:2}}>
                  <Button size="lg" type="submit" disabled={isSubmitting} variant="outline-danger rounded-pill px-5">
                  {isSubmitting ? (
                    <Stack gap={2} direction="horizontal">
                      <Spinner animation="grow" size="sm" variant="danger" />
                      <Spinner animation="grow" size="sm" variant="primary" />
                      <Spinner animation="grow" size="sm" variant="success" />
                      <span>Signing...</span>
                    </Stack>
                  ) : (
                    "Sign In"
                  )}
                  </Button>
                </motion.div>
              </Col>
              <Col md={12} className="text-center">
                <motion.div className="divider" whileInView={{width:["0%","100%"]}} transition={{duration:1.4}}>
                  <motion.span className="divider-text" whileInView={{opacity:[0,1]}} transition={{duration:1}}>OR</motion.span>
                </motion.div>
              </Col>
              <Col md={12} className="d-flex align-items-center justify-content-between">
                <motion.div whileInView={{x:[30,0]}} transition={{duration:1.8}}>     
                  <Button type="button" variant="light px-5 w-100 border border-2 bg-transparent">
                    <i className="bi bi-google text-danger"></i> Google
                  </Button>
                </motion.div>
                <motion.div whileInView={{x:[-30,0]}} transition={{duration:1.8}}>
                  <Button type="button" variant="light px-5 w-100 border border-2 bg-transparent">
                    <i className="bi bi-facebook text-primary"></i> Facebook
                  </Button>
                </motion.div>
              </Col>
              <Col md={12} className="mt-5">         
                <motion.div>
                  Protected by reCAPTCHA and subject to the <Link href="/privacy-policy" className="link-primary">Vensysco Privacy Policy</Link> and <Link href="/terms-of-service" className="link-primary">Terms of Service</Link>.
                </motion.div>
              </Col>
            </Row>
          </Form>
        ) : null}
        {isForgot && step === "email" && (
          <Form id="ForgotForm" onSubmit={handleSubmit(handleForgotEmailSubmit)}>
            <Row className="g-4">
              <Col md={12} className="d-flex justify-content-between">
                <motion.h3>Forgot Password</motion.h3>         
                <motion.div whileInView={{x:[-40,0]}} transition={{duration:1.4}}>
                  <Button type="button" className="btn-close" aria-label="Close" onClick={handleClose}></Button>
                </motion.div>
              </Col>
              <motion.div className="col-12" whileInView={{y:[30,0]}} transition={{duration:1.6}}>
                <FloatingLabel label="Email address" className="mb-3">
                  <Form.Control type="email" {...register("email", { required: true })} />
                </FloatingLabel>
              </motion.div>
              <Col md={12} className="d-flex align-items-center justify-content-between">
                <motion.div whileInView={{scale:[0.2,1]}} transition={{duration:1.8}}>
                  <Button variant="link" className="p-0 text-decoration-none" onClick={() => setIsForgot(false)}>
                    Sign In
                  </Button>
                </motion.div>
                <motion.div whileInView={{x:[-30,0]}} transition={{duration:2}}>    
                  <Button type="submit" variant="outline-danger rounded-pill px-5" disabled={isSendingOtp}>
                    {isSendingOtp ? (
                      <Stack gap={2} direction="horizontal">
                        <Spinner animation="grow" size="sm" variant="danger" />
                        <Spinner animation="grow" size="sm" variant="primary" />
                        <Spinner animation="grow" size="sm" variant="success" />
                        <span>Sending...</span>
                      </Stack>
                    ) : "Send OTP"}
                  </Button>
                </motion.div>
              </Col>
            </Row>
          </Form>
          )}
          {isForgot && step === "otp" && (
          <Form onSubmit={handleSubmit(handleOtpVerifySubmit)}>
            <Row className="g-4">
              <Col md={12} className="d-flex justify-content-between">
                <motion.h3>Verify your account to continue.</motion.h3>
              </Col>
              <Col md={12}>
                <FloatingLabel label="OTP">
                  <Form.Control className='text-center' type="text" {...register("otp", { required: true })} />
                </FloatingLabel>
              </Col>
              <Col md={12}>
                <motion.div whileInView={{scale:[0.2,1]}} transition={{duration:1.8}}>
                  <Button size='lg' type="submit" variant="outline-danger rounded-pill px-5 w-100" disabled={isVerifyingOtp}>
                    {isVerifyingOtp ? (
                      <Stack gap={2} direction="horizontal">
                        <Spinner animation="grow" size="sm" variant="danger" />
                        <Spinner animation="grow" size="sm" variant="primary" />
                        <Spinner animation="grow" size="sm" variant="success" />
                        <span>Verifying...</span>
                      </Stack>
                    ) : "Verify OTP"}
                  </Button>
                </motion.div>
              </Col>
            </Row>
          </Form>
        )}
        {isForgot && step === "reset" && (
        <Form onSubmit={handleSubmit(handleResetPasswordSubmit)}>
          <Row className="g-4">
              <Col md={12}>
                <motion.h3>Set New Password</motion.h3>
              </Col>
              <Col md={12}>
                <FloatingLabel label="New Password" className="mb-3">
                  <Form.Control type="password" {...register("password", {
                    required: true,
                    pattern: {
                      value: /^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$/,
                      message: "Min 8 chars, 1 uppercase, 1 number, 1 special char",
                    }
                  })} isInvalid={!!errors.password} />
                  <Form.Control.Feedback type="invalid">{errors.password?.message}</Form.Control.Feedback>
                </FloatingLabel>
              </Col>
              <Col md={12}>
                <motion.div whileInView={{scale:[0.2,1]}} transition={{duration:1.8}}>
                  <Button size='lg' type="submit" variant="outline-danger rounded-pill w-100 px-5" disabled={isResettingPassword}>
                    {isResettingPassword ? (
                      <Stack gap={2} direction="horizontal">
                        <Spinner animation="grow" size="sm" variant="danger" />
                        <Spinner animation="grow" size="sm" variant="primary" />
                        <Spinner animation="grow" size="sm" variant="success" />
                        <span>Setting...</span>
                      </Stack>
                    ) : "Set Password"}
                  </Button>
                </motion.div>
              </Col>
          </Row>
        </Form>
      )}   
      </Modal.Body>
    </Modal>
  );
};

export default LoginModal;
