import { Alert, AlertTitle, alpha, Box, Button, CircularProgress, Collapse, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, InputAdornment, Slide, Stack, TextField, Tooltip, Typography, useMediaQuery, useTheme } from '@mui/material'
import React, { SetStateAction, useRef } from 'react';
import Iconify from '../Iconify';
import UltimaLogo from '../../assets/icons/UltimaLogoNew.png';
import { AnimatePresence, motion } from 'framer-motion';
import ProvidersButton from './ProvidersButton';
import { signUp } from '@/functions/auth/signUp';
import shakeScreen from '@/functions/system/shakeScreen';
import notificationIcon from '../../assets/icons/UltimaLogoNew.png';
import { ipcRenderer } from 'electron';
import { useNavigate } from 'react-router';
import { useSession } from '@/contexts/AuthContext';

const SignUp = ({
    page,
    handleChangePage,
    setCanChangePage
}: {
    page: 'signin' | 'signup' | 'providers';
    handleChangePage: (page: 'signin' | 'signup' | 'providers') => void;
    setCanChangePage: React.Dispatch<SetStateAction<boolean>>;
}) => {
    const { user, status, refreshSession } = useSession();
    const navigate = useNavigate();
    const theme = useTheme();
    const [hidePassword, setHidePassword] = React.useState(true);

    const [username, setUsername] = React.useState('');
    const [displayName, setDisplayName] = React.useState('');
    const [email, setEmail] = React.useState('');
    const [password, setPassword] = React.useState('');

    const [usernameError, setUsernameError] = React.useState(false);
    const [displayNameError, setDisplayNameError] = React.useState(false);
    const [emailError, setEmailError] = React.useState(false);
    const [passwordError, setPasswordError] = React.useState(false);

    const [callState, setCallState] = React.useState<null | 'loading' | 'success' | 'error'>(null);

    const [ppDialog, setPpDialog] = React.useState<boolean>(false);
    const [generatedPP, setGeneratedPP] = React.useState<null | string>(null);
    const [registeredUserID, setRegisteredUserID] = React.useState<null | string>(null);

    const [isPassphraseSaved, setIsPassphraseSaved] = React.useState(false);
    const [areKeysSaved, setAreKeysSaved] = React.useState(false);

    const usernameRef = useRef<HTMLInputElement>(null);
    const displayNameRef = useRef<HTMLInputElement>(null);
    const emailRef = useRef<HTMLInputElement>(null);
    const passwordRef = useRef<HTMLInputElement>(null);

    const handleSignUp = async () => {
        if (!username || !displayName || !email || !password) {
            if (!username) setUsernameError(true);
            if (!displayName) setDisplayNameError(true);
            if (!email) setEmailError(true);
            if (!password) setPasswordError(true);
            shakeScreen();
            setTimeout(() => {
                setUsernameError(false);
                setDisplayNameError(false);
                setEmailError(false);
                setPasswordError(false);
            }, 1500);
            return;
        }

        setCallState('loading');
        setCanChangePage(false);

        try {
            const { data: signUpRes }: {
                data: {
                    d: {
                        userId: string,
                        accessToken: string,
                        refreshToken: string,
                        epk: string,
                        passphrase: string,
                    }
                }
            } = await signUp({
                username,
                settings: {
                    displayName
                },
                email,
                password,
            });
            // AFTER SUCCESS - SAVE

            if(signUpRes.d.passphrase && signUpRes.d.userId && signUpRes.d.epk) {

                await ipcRenderer.invoke('save-keys', {
                    userId: signUpRes.d.userId,
                    epk: signUpRes.d.epk,
                    passphrase: signUpRes.d.passphrase,
                }).then((res) => {
                    console.log('Keys saved:', res);
                    setGeneratedPP(signUpRes.d.passphrase);
                    setRegisteredUserID(signUpRes.d.userId);
                    setPpDialog(true);
                    setAreKeysSaved(true);
                }).catch((error: any) => {
                    console.error('Error saving keys:', error);
                    setCallState('error');
                    setAreKeysSaved(false);
                    throw 'Could not save keys.';
                });
            } else {
                await ipcRenderer.invoke('clear-keys');
                throw 'Passphrase or ID not found.';
            }
        } catch (error) {
            console.error(error);
            setCallState('error');
            await ipcRenderer.invoke('clear-keys');
            if (error?.response?.data) {
                new Notification('Error signing up.', { body: error?.response?.data?.data || error?.response?.data?.message || error, icon: notificationIcon });
            }

            setTimeout(() => {
                setCallState(null);
            }, 1500)
        } finally {
            setTimeout(() => {
                setUsernameError(false);
                setDisplayNameError(false);
                setEmailError(false);
                setPasswordError(false);
            }, 1500);
        }
    };

    const handleDialogContinue = async () => {
        await refreshSession();
        console.log("refreshing session...")

        console.log("user", user)
        if (user && status === 'authenticated') {
            setTimeout(() => {
                navigate('/');
            }, 500)
        }
    }

    const handleSaveToTxt = async () => {
        if (generatedPP && registeredUserID) {
            try {
                const result = await ipcRenderer.invoke('save-txt-file', {
                    name: `ultima-${registeredUserID}-passphrase`,
                    content: generatedPP,
                    title: 'Save your passphrase to a secure location!',
                });

                if (result.success) {
                    new Notification('Passphrase saved!', { body: 'Your passphrase has been saved to your computer.', icon: notificationIcon });
                    setIsPassphraseSaved(true);
                } else {
                    console.log('File save was canceled');
                }
            } catch (error) {
                console.error('Error saving passphrase:', error);
                new Notification('Error saving passphrase!', { body: 'An error occurred while saving your passphrase.', icon: notificationIcon });
            }
        } else {
            new Notification('Passphrase error.', { body: 'No passphrase was generated or ID not found.', icon: notificationIcon });
        }
    };

    const handleKeyPress = (event: React.KeyboardEvent<HTMLDivElement>, nextRef?: React.RefObject<HTMLInputElement>) => {
        if (event.key === 'Enter') {
            event.preventDefault();
            if (nextRef && nextRef.current) {
                nextRef.current.focus();
            } else {
                handleSignUp();
            }
        }
    };

    const handlePageChange = (page: 'signin' | 'signup' | 'providers') => {
        if (callState === 'loading' || ppDialog || generatedPP) return;
        handleChangePage(page);
        setCallState(null);
        setRegisteredUserID(null);
        setGeneratedPP(null);
    }

    const isSmall = useMediaQuery('(max-height: 700px)');

    return (
        <Slide direction="down" in={page == 'signup'} mountOnEnter unmountOnExit style={{
            position: page === 'signup' ? 'static' : 'absolute'
        }}>
            <Stack direction='column' sx={{
                gap: isSmall ? 1 : 2,
                width: 1,
                mx: 10,
                overflow: 'visible',
                userSelect: 'none'
            }}>
                {/* <Dialog
                    maxWidth='sm'
                    open={true}
                    sx={{
                        '& .MuiDialog-paper': {
                            userSelect: 'none'
                        }
                    }}
                >
                    <DialogTitle component={Stack} direction='column' sx={{
                        color: 'white',
                        textAlign: 'center',
                        alignItems: 'center',
                        fontWeight: 600
                    }}>
                        <Iconify
                            style={{
                                color: theme.palette.primary.light,
                                filter: `
                            drop-shadow(0px 13px 29px ${theme.palette.primary.main}),
                            drop-shadow(0px 13px 40px ${theme.palette.primary.dark}),
                            drop-shadow(0px 13px 50px ${theme.palette.primary.dark});
                            `
                            }}
                            icon="fluent:heart-circle-hint-20-filled"
                            size={60}
                        />
                        <Typography variant="h6">Welcome to the team!</Typography>
                    </DialogTitle>
                    <DialogContent sx={{}}>
                        
                    </DialogContent>
                </Dialog> */}
                <Dialog
                    maxWidth='sm'
                    open={ppDialog}
                    sx={{
                        '& .MuiDialog-paper': {
                            userSelect: 'none'
                        }
                    }}
                >
                    <DialogTitle component={Stack} direction='column' sx={{
                        color: 'white',
                        textAlign: 'center',
                        alignItems: 'center',
                        fontWeight: 600
                    }}>
                        <Iconify icon="solar:shield-check-bold" size={60} />
                        <Typography variant="h6">We value your privacy.</Typography>
                    </DialogTitle>
                    <DialogContent sx={{
                        display: 'flex',
                        flexDirection: 'column',
                        textAlign: 'center',
                        alignItems: 'center',
                        justifyContent: 'center',
                    }}>
                        <Typography variant="body2" color="textSecondary" mb={1}>
                            Security and privacy is really important these days,<br />
                            so we have generated a passphrase for you to access your account.
                        </Typography>
                        <Box sx={{
                            my: 1,
                            display: 'flex',
                            gap: 0.5,
                            p: 0.5,
                            borderRadius: (theme) => theme.shape.borderRadius,
                            border: (theme) => `1px dashed ${theme.palette.divider}`
                        }}>
                            {generatedPP && generatedPP.split('').map((char, index) => (
                                <Box
                                    key={index}
                                    sx={{
                                        py: 1,
                                        width: 25,
                                        border: '1px dashed',
                                        borderColor: (theme) => theme.palette.divider,
                                        borderRadius: 1,
                                        textAlign: 'center',
                                        userSelect: 'text',
                                        bgcolor: 'background.default',
                                        color: 'text.primary',
                                        fontWeight: 'bold',
                                        fontSize: '1.2rem',
                                    }}
                                >
                                    {char}
                                </Box>
                            ))}
                        </Box>
                        <Button variant="text" onClick={handleSaveToTxt} disableRipple sx={{
                            py: 0,
                        }}>
                            Download to computer
                        </Button>
                        <Alert severity="error" color="warning" sx={{ textAlign: 'left', mt: 1 }}>
                            <AlertTitle>Don&apos;t take this lightly.</AlertTitle>
                            Please save it in a secure location in your computer.
                        </Alert>
                    </DialogContent>
                    <DialogActions sx={{
                        p: 3,
                        pt: 1,
                        justifyContent: 'space-between'
                    }}>
                        <Button variant="text" disableRipple color="info">
                            How it works?
                        </Button>
                        <Tooltip followCursor title={!isPassphraseSaved && 'Please, download passphrase to your device.'}>
                            <span>
                                <Button variant="contained" disabled={!isPassphraseSaved} onClick={handleDialogContinue}>
                                    Okay, continue
                                </Button>
                            </span>
                        </Tooltip>
                    </DialogActions>
                </Dialog>
                {!isSmall && (
                    <img src={UltimaLogo} alt="Ultima" draggable={false} style={{
                        width: 100,
                        height: 100,
                        userSelect: 'none'
                    }} />
                )}
                <Typography sx={{
                    fontWeight: 550,
                    fontSize: 18,
                    color: 'white',
                    textTransform: 'uppercase'
                }}>
                    Start your journey
                </Typography>
                <Typography variant="h2" sx={{
                    fontWeight: 550,
                }}>
                    Create new account<Typography component="span" variant="h2" sx={{ color: 'primary.light', fontWeight: 600, textShadow: (theme) => `0 0 12px ${theme.palette.primary.light}` }}>.</Typography>
                </Typography>
                <Typography sx={{ color: 'text.secondary', fontSize: 15 }} variant="body1">
                    Already a member? <Typography component="span" onClick={() => handlePageChange('signin')} sx={{ color: 'primary.light', cursor: 'pointer', fontSize: 15, fontWeight: 550 }}>Sign In</Typography>
                </Typography>

                <form>
                    <Stack direction='column' sx={{ gap: 2, width: 1, maxWidth: 500, }}>
                        <Stack direction='row' gap={2} width={1}>
                            <TextField
                                size={isSmall ? 'small' : 'medium'}
                                fullWidth
                                label="Username"
                                variant='filled'
                                color='primary'
                                placeholder="johndoe"
                                value={username}
                                onChange={(e) => setUsername(e.target.value)}
                                error={usernameError || callState === 'error'}
                                sx={{
                                    '& .MuiFilledInput-root': {
                                        borderColor: usernameError || callState === 'error' ? 'error.main' : callState === 'success' ? 'success.main' : 'primary.main',
                                        color: usernameError || callState === 'error' ? 'error.main' : callState === 'success' ? 'success.main' : 'inherit',
                                    }
                                }}
                                slotProps={{
                                    input: {
                                        startAdornment: <Typography sx={{ pt: 1.8, color: 'text.secondary' }}>@</Typography>,
                                        endAdornment: <Iconify size={24} icon="tabler:at" />,
                                        inputRef: usernameRef,
                                        onKeyPress: (e) => handleKeyPress(e, displayNameRef)
                                    }
                                }}
                            />

                            <TextField
                                size={isSmall ? 'small' : 'medium'}
                                fullWidth
                                label="Display Name"
                                variant='filled'
                                color='primary'
                                placeholder="John Doe"
                                value={displayName}
                                onChange={(e) => setDisplayName(e.target.value)}
                                error={displayNameError || callState === 'error'}
                                sx={{
                                    '& .MuiFilledInput-root': {
                                        borderColor: displayNameError || callState === 'error' ? 'error.main' : callState === 'success' ? 'success.main' : 'primary.main',
                                        color: displayNameError || callState === 'error' ? 'error.main' : callState === 'success' ? 'success.main' : 'inherit',
                                    }
                                }}
                                slotProps={{
                                    input: {
                                        endAdornment: <Iconify size={24} icon="solar:user-id-bold" />,
                                        inputRef: displayNameRef,
                                        onKeyPress: (e) => handleKeyPress(e, emailRef)
                                    }
                                }}
                            />
                        </Stack>
                        <TextField
                            label="Email"
                            size={isSmall ? 'small' : 'medium'}
                            variant='filled'
                            color='primary'
                            placeholder="johndoe@gmail.com"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            error={emailError || callState === 'error'}
                            sx={{
                                '& .MuiFilledInput-root': {
                                    borderColor: emailError || callState === 'error' ? 'error.main' : callState === 'success' ? 'success.main' : 'primary.main',
                                    color: emailError || callState === 'error' ? 'error.main' : callState === 'success' ? 'success.main' : 'inherit',
                                }
                            }}
                            slotProps={{
                                input: {
                                    endAdornment: <Iconify size={24} icon="majesticons:mail" />,
                                    inputRef: emailRef,
                                    onKeyPress: (e) => handleKeyPress(e, passwordRef)
                                }
                            }}
                        />
                        <TextField
                            label="Password"
                            size={isSmall ? 'small' : 'medium'}
                            variant='filled'
                            color='primary'
                            placeholder='********'
                            type={hidePassword ? 'password' : 'text'}
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            error={passwordError || callState === 'error'}
                            sx={{
                                '& .MuiFilledInput-root': {
                                    borderColor: passwordError || callState === 'error' ? 'error.main' : callState === 'success' ? 'success.main' : 'primary.main',
                                    color: passwordError || callState === 'error' ? 'error.main' : callState === 'success' ? 'success.main' : 'inherit',
                                }
                            }}
                            slotProps={{
                                input: {
                                    endAdornment: (
                                        <InputAdornment position="end" sx={{ color: 'inherit' }}>
                                            <IconButton disableRipple onClick={() => setHidePassword((prev) => !prev)} sx={{
                                                p: 0,
                                                color: 'inherit',
                                                pt: 0.5
                                            }}>
                                                <Iconify size={22} icon={hidePassword ? 'solar:eye-closed-bold' : 'solar:eye-bold'} />
                                            </IconButton>
                                        </InputAdornment>
                                    ),
                                    inputRef: passwordRef,
                                    onKeyPress: (e) => handleKeyPress(e)
                                }
                            }}
                        />
                        <Stack direction='row' gap={2} sx={{ justifyContent: 'space-between', mt: isSmall ? 2 : 4 }}>
                            <ProvidersButton {...{ handlePageChange }} />
                            <Button
                                onClick={() => { !callState && handleSignUp() }}
                                variant='contained'
                                color={(usernameError || displayNameError || emailError || passwordError) ? 'error' : (callState === 'success' ? 'success' : (callState === 'error' ? 'error' : 'primary'))}
                                fullWidth
                                disableRipple={!!callState}
                                sx={{
                                    height: isSmall ? 36 : 52,
                                    color: 'white',
                                    boxShadow: (theme) => `0 8px 16px 0 ${alpha(theme.palette.primary.main, 0.24)}`,
                                    cursor: !callState ? 'pointer' : 'not-allowed'
                                }}
                            >
                                {callState === 'loading' ? (
                                    <CircularProgress size={24} color="inherit" />
                                ) : callState === 'success' ? (
                                    <Iconify size={24} icon="solar:check-circle-bold" />
                                ) : callState === 'error' ? (
                                    <Iconify size={24} icon="solar:close-circle-bold" />
                                ) : (
                                    'Create an Account'
                                )}
                            </Button>
                        </Stack>
                    </Stack>
                </form>
            </Stack>
        </Slide>
    )
}

export default SignUp;