"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { signIn } from "next-auth/react";
import { motion } from "framer-motion";
import HeaderTop from "@/components/HeaderTop";
import HeaderSticky from "@/components/HeaderSticky";
import { useToast } from '@/context/ToastContext';
import { Container, Card, Row, Col, Button, Form, FloatingLabel, Stack, Spinner } from "react-bootstrap";
import { useRecaptcha } from "@/hooks/useRecaptcha";

type FormData = {
  name: string;
  email: string;
  mobile: string;
  password: string;
};

export default function RegisterForm() {
  const { showToast } = useToast();
  const { getToken } = useRecaptcha();
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<FormData>();

  const [step, setStep] = useState<"register" | "verify">("register");
  const [User, setUser] = useState<FormData | null>(null);
  const [otp, setOtp] = useState("");
  const [resendAttempts, setResendAttempts] = useState(0);
  const [timer, setTimer] = useState(0);
  const [verifying, setVerifying] = useState(false);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (timer > 0) {
      interval = setInterval(() => setTimer((prev) => prev - 1), 1000);
    }
    return () => clearInterval(interval);
  }, [timer]);

  const onSubmit = async (data: FormData) => {
    const recaptchaToken = await getToken("register_form");
    const res = await fetch("/api/auth/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...data, provider: "credentials", recaptchaToken }),
    });

    const result = await res.json();

    if (res.ok) {
      setUser(data);
      setStep("verify");
      setTimer(120); // 2 min countdown
      showToast(result.message, "success");
    } else {
      showToast(result.error || "Something went wrong, Please try again later", "danger");
    }
  };

  const handleVerify = async () => {
    setVerifying(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({ 
        type: 0,
        entity: User?.email,
        otp,
        recaptchaToken
      }),
    });
    const result = await res.json();
    setVerifying(false);

    if (res.ok) {
      showToast("Account verified successfully! Kindly Login", "success");
      setStep("register");
      reset();
    } else {
      console.error("OTP verification failed:", result);
      showToast("Account verification failed, Expired or Invalid OTP.", "danger");
    }
  };

  const handleResend = async () => {
    if (resendAttempts >= 3) return;
    const recaptchaToken = await getToken("send_otp_form");
    const res = await fetch("/api/auth/send-otp", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ 
        name: User?.name,
        email: User?.email,
        mobile: User?.mobile,
        recaptchaToken
       }),
    });

    if (res.ok) {
      setResendAttempts((prev) => prev + 1);
      setTimer(120);
      showToast("Account Verification OTP has been resent", "success");
    } else {
      showToast("Failed to resend OTP", "danger");
    }
  };

  return (
    <section className="section-register overflow-visible">
      <Container className="min-vh-120 py-3 py-md-5 d-flex flex-column position-relative">
          <HeaderTop />
          <HeaderSticky />
          <Row className='my-auto w-100 justify-content-between'>
            <Col md={12} xl={5}>
              <motion.h1 className="display-3 fw-bold mb-3" whileInView={{y:[-30,0]}} transition={{duration:1.8}} viewport={{once: true, amount: 0.5}}>
                {step === "register" ? "Sign up to get started with Vensysco." : "Verify your account to continue."}
              </motion.h1>                    
            </Col>
            <Col xl={5} className="position-relative">
              <div className="register-form">                      
                <motion.div className="card rounded-4 shadow" whileInView={{y:[100,0]}} transition={{duration:2}} viewport={{once:true,amount:0.5}}>
                  <Card.Body className="p-5">
                    {step === "register" ? (
                    <Form noValidate onSubmit={handleSubmit(onSubmit)}>
                      <Row className="g-3">
                        <Col md={12}>
                          <motion.h3>Sign Up</motion.h3>
                        </Col>
                        <Col md={12} className="hstack gap-2">
                          <motion.div className="w-100" whileInView={{x:[-30,0]}} transition={{duration:1.6}} viewport={{once:true,amount:0.5}}>
                            <Button type="button" variant="primary w-100 d-flex align-items-center" onClick={() => signIn("google")}>
                              <i className="bi bi-google me-2"></i>
                              <span className="mx-auto">Sign up with Google</span>
                            </Button>
                          </motion.div>
                          <motion.div whileInView={{x:[30,0]}} transition={{duration:1.8}} viewport={{once:true,amount:0.5}}>
                            <Button type="button" variant="light w-100 border border-2 bg-transparent" onClick={() => signIn("facebook")}>
                              <i className="bi bi-facebook text-primary me-2"></i>
                              <span className="mx-auto d-none">Sign up with Facebook</span>
                            </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.8}}>
                              OR
                            </motion.span>
                          </motion.div>
                        </Col>
                        <Col md={12}>
                          <motion.div whileInView={{y:[30,0]}} transition={{duration:1.8}} viewport={{once:true,amount:0.5}}>
                            <FloatingLabel label="Full Name">
                              <Form.Control type="text" {...register("name", { required: "Full name is required", pattern: { value: /^[a-zA-Z]+ [a-zA-Z]+$/, message: "Enter first and last name", }, })} isInvalid={!!errors.name} />
                              <Form.Control.Feedback type="invalid">{errors.name?.message}</Form.Control.Feedback>
                            </FloatingLabel>
                          </motion.div>
                        </Col>
                        <Col md={12}>
                          <motion.div whileInView={{y:[30,0]}} transition={{duration:1.8}} viewport={{once:true,amount:0.5}}>
                            <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.8}} viewport={{once:true,amount:0.5}}>
                            <FloatingLabel label="Mobile">
                              <Form.Control type="tel" {...register("mobile", { required: "Mobile number is required", pattern: { value: /^[6-9]\d{9}$/, message: "Enter a valid 10-digit Indian mobile number", }, })} isInvalid={!!errors.mobile} />
                              <Form.Control.Feedback type="invalid">{errors.mobile?.message}</Form.Control.Feedback>
                            </FloatingLabel>
                          </motion.div>
                        </Col>
                        <Col md={12}>
                          <motion.div whileInView={{y:[30,0]}} transition={{duration:1.8}} viewport={{once:true,amount:0.5}}>
                            <FloatingLabel label="Password">
                              <Form.Control type="password" {...register("password", { required: "Password is required", pattern: { value: /^(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,}$/, message: "Min 8 chars, 1 uppercase, 1 number, 1 special", }, })} isInvalid={!!errors.password} />
                              <Form.Control.Feedback type="invalid">{errors.password?.message}</Form.Control.Feedback>
                            </FloatingLabel>
                          </motion.div>
                        </Col>
                        <Col md={12}>
                          <motion.button className="btn btn-lg btn-outline-danger rounded-pill w-100" type="submit" disabled={isSubmitting} whileInView={{scale:[0.2,1]}} transition={{duration:2}} viewport={{once:true,amount:0.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>Registering...</span>
                              </Stack>
                            ) : (
                              "Sign up"
                            )}
                          </motion.button>
                        </Col>
                        <Col md={12}>
                          <Form.Check type="checkbox" defaultChecked label="By clicking Create account, I agree to the Terms of Use and Privacy Policy." />
                        </Col>
                        <Col md={12}>
                          <motion.div>
                            Protected by reCAPTCHA and subject to the{" "}
                            <Link href="/privacy-policy" className="link-primary">Privacy Policy</Link> and{" "}
                            <Link href="/terms-conditions" className="link-primary">Terms of Service</Link>.
                          </motion.div>
                        </Col>
                      </Row>
                    </Form>
                    ) : (
                    <Form onSubmit={(e) => { e.preventDefault(); handleVerify(); }}>
                      <Row className="g-3">
                        <Col md={12}>
                          <motion.h3>Account Verification</motion.h3>
                        </Col>                      
                        <Col md={12}>
                          <FloatingLabel label="Enter OTP">
                            <Form.Control className="rounded-pill text-center" type="text" inputMode="numeric" maxLength={6} pattern="\d{6}" required value={otp} onChange={(e) => setOtp(e.target.value)} />
                          </FloatingLabel>                        
                        </Col>
                        <Col md={12}>
                          <Button size="lg" variant="outline-danger" className="w-100 rounded-pill" type="submit" disabled={verifying || otp.length !== 6}>
                            {verifying ? (
                              <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>
                        </Col>
                        <Col md={12} className="text-center">
                          {timer > 0 ? (
                            <small className="text-secondary">Resend available in <strong className="text-danger">{timer}s</strong></small>
                          ) : resendAttempts < 3 ? (
                            <Button size="lg" variant="danger" className="w-100 rounded-pill" onClick={handleResend}>
                              Resend OTP ({3 - resendAttempts} attempts left)
                            </Button>
                          ) : (
                            <span className="text-danger">Max resend attempts reached</span>
                          )}
                        </Col>
                      </Row>
                    </Form>
                  )}
                  </Card.Body>
                </motion.div>
              </div>
            </Col>                 
          </Row>
          <motion.div className="text-center text-lg-start mt-4" whileInView={{y:[30,0]}} transition={{duration:1.8}} viewport={{once: true, amount: 0.5}}>
            Having troubles? <Button variant="link" className="p-0 link-light text-decoration-none">Get Help</Button>
          </motion.div>
      </Container>
    </section>
  );
}
