import { Checkbox, Textinput } from '@/components';
import Button from '@/components/ui/Button';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { useState } from 'react';
import { Form } from 'react-bootstrap';
import { toast } from 'react-hot-toast';
import { useSignupMutation } from '@/lib/redux/services/auth.api';
import errorHandler from '@/utils/request/errorHandler';

const User = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [termsAccepted, setTermsAccepted] = useState(false);

  const router = useRouter();
  const [signup, { isLoading }] = useSignupMutation(); // ✅ use signup mutation properly

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!termsAccepted) {
      toast.error('Please accept Terms & Conditions.');
      return;
    }

    if (!email || !password || !confirmPassword) {
      toast.error('Please fill in all fields.');
      return;
    }

    if (password !== confirmPassword) {
      toast.error('Passwords do not match.');
      return;
    }

    try {
      const userType = localStorage.getItem('userType');
      if (!userType) {
        toast.error('userType not found.');
      }
      const response = await signup({ email, password, userType }).unwrap();

      if (response.success) {
        if (response.data.token) {
          localStorage.setItem('token', response.data.token);
          localStorage.setItem('email', response.data.user.email);
          localStorage.setItem('userType', response.data.user.userType);
        }
        toast.success('Signup successful!');
        router.push('/auth/otp?otpType=register');
      } else {
        toast.error(response.message || 'Something went wrong');
      }
    } catch (error: any) {
      console.error('Signup Error:', error);
      errorHandler(error)

    }
  };

  return (
    <>
      <Head>
        <title>Signup | Deliver X</title>
      </Head>

      <div className="h-100 d-flex flex-column justify-content-center align-items-center">
        <h5 className="auth-page-title">Sign Up</h5>
        <p>Please enter your details to sign up</p>

        <form onSubmit={handleSubmit} className="w-100 mb-sm-5">
          <Form.Group controlId="formEmail" className="mt-xl-4 mt-2">
            <Form.Label>Email address</Form.Label>
            <Textinput
              iconLeft={<img src="/images/icons/email.png" />}
              type="email"
              placeholder="Enter email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </Form.Group>

          <Form.Group controlId="formPassword" className="mt-xl-4 mt-2">
            <Form.Label>Password</Form.Label>
            <Textinput
              iconLeft={<img src="/images/icons/lock.png" />}
              iconRight={<img src="/images/icons/eye.png" />}
              type="password"
              placeholder="Enter Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
          </Form.Group>

          <Form.Group controlId="formConfirmPassword" className="mt-xl-4 mt-2">
            <Form.Label>Confirm Password</Form.Label>
            <Textinput
              iconLeft={<img src="/images/icons/lock.png" />}
              iconRight={<img src="/images/icons/eye.png" />}
              type="password"
              placeholder="Confirm Password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
            />
          </Form.Group>

          <div className="d-flex justify-content-between align-items-center mt-4">
            <Checkbox
              label="I accept Terms & conditions and Privacy Policy"
              defaultChecked={termsAccepted}
              onChange={(checked) => setTermsAccepted(checked)}
            />
          </div>

          <div className="d-flex justify-content-center align-items-center">
            <Button
              type="submit"
              size="md"
              className="mt-xl-5 mt-2 btn btn-feature auth-btn"
              disabled={isLoading}
            >
              {isLoading ? 'Signing Up...' : 'Sign Up'}
            </Button>
          </div>

          <div className="d-flex justify-content-center align-items-center gap-3 mt-4">
            <img src="/images/icons/google.png" alt="Google" />
            <img src="/images/icons/facebook.png" alt="Facebook" />
          </div>
        </form>

        <div className="authFooter d-flex justify-content-center align-items-center gap-3 mt-5">
          <p className="pb-0 mb-0 fw-normal">Already have an account?</p>
          <Link href="/auth/login" className="text-primary-color">
            Login
          </Link>
        </div>
      </div>
    </>
  );
};

export default User;
