import { Form, Formik, Field } from 'formik';
import React, { useContext, useEffect, useState } from 'react';
import { applyAccessToken, axiosInstance } from '../../../axiosApi';
import { setTokens } from '../../auth/tokenStorage';
import { AuthContext } from '../../contexts/AuthContext';
import { useNavigate } from 'react-router-dom';
import { AccountContext } from '../../contexts/AccountContext';
import { AxiosResponse } from 'axios';
import { Account, AccountType } from '../../data';
import ParticleBackground from '../../components/ParticleBackground/ParticleBackground';
import SsoButtons, { OAuthProviderFlags } from '../../components/SsoButtons/SsoButtons';
import { AnalyticsEvents, identifyAccount, trackEvent } from '../../utils/analytics';
import { logInRevenueCat } from '../../utils/revenueCat';
import styled from 'styled-components';
import * as Yup from 'yup';
import hesychiaMark from '../../assets/brand/hesychia-mark.png';

// Styled Components
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: 2rem;
  color: #fff;
  text-align: center;
`;

const BrandBlock = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 1.25rem;
`;

const BrandMark = styled.img`
  width: 4rem;
  height: 4rem;
  border-radius: 50%;
`;

const BrandWordmark = styled.h1`
  margin: 0.85rem 0 0;
  font-size: 1.75rem;
  font-weight: 700;
  letter-spacing: 0.02em;
  color: #fff;
  text-align: center;
`;

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 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%;
`;

const ForgotPasswordLink = 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 SignUpLink = styled.button`
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  margin-top: 0.75rem;
  cursor: pointer;
  font-size: 0.9rem;
  transition: color 0.2s ease;

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

export type SignInValues = {
    email: string;
    password: string;
};

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

const SignIn = (): JSX.Element => {
    const { setAuthentication, setNeedsNewPassword } = useContext(AuthContext);
    const { setAccount } = useContext(AccountContext);
    const navigate = useNavigate();
    const [errorMessage, setErrorMessage] = useState<string>('');
    const [registrationEnabled, setRegistrationEnabled] = useState(false);
    const [oauthProviders, setOauthProviders] = useState<OAuthProviderFlags>({});

    useEffect(() => {
        let cancelled = false;
        (async () => {
            try {
                const response = await axiosInstance.get('/public/settings/');
                if (!cancelled) {
                    setRegistrationEnabled(Boolean(response.data?.enable_account_registration));
                    setOauthProviders({
                        google: Boolean(response.data?.oauth?.google),
                        microsoft: Boolean(response.data?.oauth?.microsoft),
                    });
                }
            } catch {
                if (!cancelled) {
                    setRegistrationEnabled(false);
                    setOauthProviders({});
                }
            }
        })();
        return () => {
            cancelled = true;
        };
    }, []);

    const handleSignIn = async ({ email, password }: SignInValues): Promise<void> => {
        try {
            const response = await axiosInstance.post('/token/obtain/', {
                username: email,
                password: password,

            })
            await setTokens(response.data.access, response.data.refresh);
            applyAccessToken(response.data.access);

            const get_user_response: AxiosResponse<AccountType> = await axiosInstance.get('/user/get/')

            const account = new Account({
                id: get_user_response.data.id,
                email: get_user_response.data.email,
                first_name: get_user_response.data.first_name,
                last_name: get_user_response.data.last_name,
                is_company_manager: get_user_response.data.is_company_manager,
                has_signed_tos: get_user_response.data.has_signed_tos,
                company: {
                    id: get_user_response.data.company?.id,
                    name: get_user_response.data.company?.name,
                    state: get_user_response.data.company?.state,
                    zipcode: get_user_response.data.company?.zipcode,
                    address: get_user_response.data.company?.address,
                }

            });
            setAccount(account);
            setAuthentication(true)
            setNeedsNewPassword(get_user_response.data.has_usable_password)
            trackEvent(AnalyticsEvents.LOGIN_SUCCESS, { method: 'password' });
            identifyAccount(account);
            void Promise.resolve(logInRevenueCat(account)).catch((err) =>
                console.warn('RevenueCat logIn', err)
            );
            if (account.has_signed_tos) {
                navigate('/');
            } else {
                navigate('/terms_of_service/')
            }

        } catch (error) {
            console.log(error)
            trackEvent(AnalyticsEvents.LOGIN_FAILED, { method: 'password' });
            setErrorMessage('Error retrieving account. Try again');
        }
    }

    return (
        <PageContainer>
            <ParticleBackground />
            <ContentWrapper>
                <GlassCard>
                    <BrandBlock>
                        <BrandMark src={hesychiaMark} alt="" />
                        <BrandWordmark>Hesychia.ai</BrandWordmark>
                    </BrandBlock>
                    <CardTitle>Sign In</CardTitle>
                    {errorMessage && <ErrorMessage>{errorMessage}</ErrorMessage>}
                    <Formik
                        initialValues={{
                            email: '',
                            password: '',
                        }}
                        onSubmit={handleSignIn}
                        validationSchema={validationSchema}
                    >
                        {(formik) => (
                            <Form style={{ width: '100%' }}>
                                <Field
                                    as={StyledInput}
                                    name="email"
                                    placeholder="Email Address"
                                    type="email"
                                />
                                <Field
                                    as={StyledInput}
                                    name="password"
                                    placeholder="Password"
                                    type="password"
                                />
                                <StyledButton type="submit" disabled={formik.isSubmitting}>
                                    Sign In
                                </StyledButton>
                                {registrationEnabled && (
                                    <SsoButtons
                                        intent="login"
                                        providers={oauthProviders}
                                        disabled={formik.isSubmitting}
                                    />
                                )}
                            </Form>
                        )}
                    </Formik>
                    <ForgotPasswordLink onClick={() => navigate('/password_reset/')}>
                        Forgot Password?
                    </ForgotPasswordLink>
                    {registrationEnabled && (
                        <SignUpLink onClick={() => navigate('/signup/')}>
                            Don't have an account? Sign up
                        </SignUpLink>
                    )}
                    <SignUpLink onClick={() => navigate('/terms_of_service/')}>
                        Terms of Service
                    </SignUpLink>
                </GlassCard>
            </ContentWrapper>
        </PageContainer>
    );
};

export default SignIn;