import { Form, Formik, Field } from 'formik';
import React, { useRef, useState } from 'react';
import { cleanAxiosInstance } from '../../../axiosApi';
import { useNavigate } from 'react-router-dom';
import ReCAPTCHA from 'react-google-recaptcha';
import ParticleBackground from '../../components/ParticleBackground/ParticleBackground';
import styled from 'styled-components';
import * as Yup from 'yup';

const PageContainer = styled.div`
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  color: #fff;
  font-family: 'Inter', sans-serif;
`;

const ContentWrapper = styled.div`
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 5;
  padding: 2rem;
`;

const GlassCard = styled.div`
  background: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 1rem;
  padding: 3rem;
  width: 100%;
  max-width: 450px;
  box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
  display: flex;
  flex-direction: column;
  align-items: center;
`;

const CardTitle = styled.h2`
  font-size: 2rem;
  margin-bottom: 1rem;
  color: #fff;
  text-align: center;
`;

const CardSubtitle = styled.p`
  color: rgba(255, 255, 255, 0.65);
  text-align: center;
  margin-bottom: 2rem;
  font-size: 0.95rem;
  line-height: 1.4;
`;

const StyledInput = styled.input`
  width: 100%;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 0.5rem;
  padding: 1rem;
  color: #fff;
  font-size: 1rem;
  outline: none;
  transition: all 0.3s ease;
  margin-bottom: 1.5rem;

  &:focus {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(100, 149, 237, 0.5);
    box-shadow: 0 0 10px rgba(100, 149, 237, 0.2);
  }

  &::placeholder {
    color: rgba(255, 255, 255, 0.5);
  }
`;

const StyledButton = styled.button`
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 0.5rem;
  color: #fff;
  padding: 1rem;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s ease;
  width: 100%;
  margin-top: 1rem;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(118, 75, 162, 0.4);
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    transform: none;
  }
`;

const BackLink = styled.button`
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  margin-top: 1.5rem;
  cursor: pointer;
  font-size: 0.9rem;
  transition: color 0.2s ease;

  &:hover {
    color: #fff;
    text-decoration: underline;
  }
`;

const ErrorMessage = styled.div`
  color: #ff6b6b;
  margin-bottom: 1rem;
  text-align: center;
  background: rgba(255, 107, 107, 0.1);
  padding: 0.5rem;
  border-radius: 0.5rem;
  width: 100%;
`;

export type EmailPasswordResetValues = {
  email: string;
};

const validationSchema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Required'),
});

const PasswordReset = (): JSX.Element => {
  const navigate = useNavigate();
  const recaptchaRef = useRef<ReCAPTCHA>(null);
  const [errorMessage, setErrorMessage] = useState('');

  const handlePasswordResetEmail = async ({
    email,
  }: EmailPasswordResetValues): Promise<void> => {
    setErrorMessage('');
    try {
      let token = '';
      if (recaptchaRef.current) {
        token = (await recaptchaRef.current.executeAsync()) || '';
        recaptchaRef.current.reset();
      }

      await cleanAxiosInstance.post('user/reset_password/', {
        email,
        recaptchaToken: token,
      });
      navigate('/password_reset_confirmation/');
    } catch {
      setErrorMessage('Unable to reset password. Please try again.');
    }
  };

  return (
    <PageContainer>
      <ParticleBackground />
      <ContentWrapper>
        <GlassCard>
          <CardTitle>Reset Password</CardTitle>
          <CardSubtitle>
            Enter your email and we will send a link to set a new password.
          </CardSubtitle>
          {errorMessage && <ErrorMessage>{errorMessage}</ErrorMessage>}
          <Formik
            initialValues={{ email: '' }}
            onSubmit={handlePasswordResetEmail}
            validationSchema={validationSchema}
          >
            {(formik) => (
              <Form style={{ width: '100%' }}>
                <Field
                  as={StyledInput}
                  name="email"
                  placeholder="Email Address"
                  type="email"
                />
                <div style={{ display: 'flex', justifyContent: 'center' }}>
                  <ReCAPTCHA
                    ref={recaptchaRef}
                    sitekey="6LfENu4qAAAAAFtPejcrP3dwBDxcRPjqi7RhytJJ"
                    size="invisible"
                    theme="dark"
                  />
                </div>
                <StyledButton type="submit" disabled={formik.isSubmitting}>
                  Reset Password
                </StyledButton>
              </Form>
            )}
          </Formik>
          <BackLink onClick={() => navigate('/signin/')}>Back to Sign In</BackLink>
        </GlassCard>
      </ContentWrapper>
    </PageContainer>
  );
};

export default PasswordReset;
