import { alpha, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, InputAdornment, Slide, Stack, TextField, Typography, useMediaQuery } from '@mui/material';
import React, { useState, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Iconify from '../Iconify';
import shakeScreen from '@/functions/system/shakeScreen';
import notificationIcon from '../../assets/icons/UltimaLogoNew.png';
import UltimaLogo from '../../assets/icons/UltimaLogoNew.png';
import ProvidersButton from './ProvidersButton';
import { signIn } from '@/functions/auth/signIn';
import { useNavigate } from 'react-router';
import { ipcRenderer } from 'electron';
import { saveSession } from '@/functions/auth/saveSession';

const SignIn = ({
    page,
    handleChangePage
}: {
    page: 'signin' | 'signup' | 'providers';
    handleChangePage: (page: 'signin' | 'signup' | 'providers') => void;
}) => {
    const navigate = useNavigate();
    const [hidePassword, setHidePassword] = useState(true);
    const isSmall = useMediaQuery('(max-height: 700px)');

    const [credentials, setCredentials] = useState('');
    const [password, setPassword] = useState('');

    const [crError, setCrError] = useState(false);
    const [passwordError, setPasswordError] = useState(false);

    const [ppDialog, setPPDialog] = useState(false);
    const [pp, setPP] = useState('');
    const [userId, setUserId] = useState<string | null>(null);
    const epkRef = useRef<string | null>(null);

    const [sessionData, setSessionData] = useState<any>(null);

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

    const handleSignIn = async () => {
        if (!credentials || !password) {
            if (!credentials) setCrError(true);
            if (!password) setPasswordError(true);
            shakeScreen();
            setTimeout(() => {
                setCrError(false);
                setPasswordError(false);
            }, 1500);
            return;
        }

        setCallState('loading');

        try {
            const { data } = await signIn({
                provider: 'credentials',
                data: {
                    credentials,
                    password
                }
            });

            console.log("data", data);

            setUserId(data.d.userId);
            setSessionData(data.d);
            epkRef.current = data.d.epk;

            const { exists } = await ipcRenderer.invoke('check-keys', data.d.userId);

            if (exists) {
                setCallState('success');
                setTimeout(() => {
                    navigate('/');
                }, 500);
            } else {
                setPPDialog(true);
            }
        } catch (error) {
            setCallState('error');
            console.error('Error signing in:', error);
            if (error?.response?.data) {
                new Notification('Error signing in.', { body: error?.response?.data?.data, icon: notificationIcon });
            }
        } finally {
            setTimeout(() => {
                setCallState(null);
                setCrError(false);
                setPasswordError(false);
            }, 1500);
        }
    };

    const handlePageChange = (page: 'signin' | 'signup' | 'providers') => {
        if (callState === 'loading') return;
        handleChangePage(page);
        setCallState(null);
    };
    // ^(?:(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)?/[a-z0-9-._~])|[a-z0-9-~])[a-z0-9-._~]*$

    const handleFinishSign = async () => {
        if (pp.length !== 6) return;

        try {
            const { success, error } = await ipcRenderer.invoke('save-keys', {
                userId,
                epk: epkRef.current,
                passphrase: pp
            });

            if (success) {
                saveSession(sessionData);
                navigate('/');
            } else if(error) {
                throw error;
            }
        } catch (error) {
            console.error('Error saving keys:', error);
        }
    };

    return (
        <Slide direction="up" in={page == 'signin'} mountOnEnter unmountOnExit style={{
            position: page === 'signin' ? 'static' : 'absolute'
        }}>
            <Stack direction='column' sx={{
                gap: 2,
                maxWidth: 500,
                width: 1,
                m: 10,
                userSelect: 'none'
            }}>
                <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">This device is new on your account.</Typography>
                    </DialogTitle>
                    <DialogContent sx={{
                        display: 'flex',
                        flexDirection: 'column',
                        textAlign: 'center',
                        alignItems: 'center',
                        justifyContent: 'center',
                    }}>
                        <Typography variant="body2" color="textSecondary" mb={1}>
                            By our security policy, new devices must confirm their identity<br />
                            using generated passphrase, for privacy, encryption and security.
                        </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}`
                        }}>
                            <TextField
                                value={pp}
                                onChange={(e) => {
                                    const value = e.target.value;
                                    if (/^\d*$/.test(value) && value.length <= 6) {
                                        setPP(value);
                                    }
                                }}
                                placeholder="Enter passphrase"
                                inputProps={{ maxLength: 6 }}
                                sx={{
                                    '& .MuiInputBase-input': {
                                        textAlign: 'center',
                                        fontWeight: 'bold',
                                        fontSize: '1.2rem',
                                        letterSpacing: '0.5rem'
                                    }
                                }}
                            />
                        </Box>
                    </DialogContent>
                    <DialogActions sx={{
                        p: 3,
                        pt: 1,
                        justifyContent: 'space-between'
                    }}>
                        <Button variant="text" disableRipple color="info">
                            I forgot my passphrase
                        </Button>
                        <Button variant="contained" disabled={pp.length !== 6} onClick={handleFinishSign}>
                            Continue
                        </Button>
                    </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'
                }}>
                    Ready to dive in?
                </Typography>
                <Typography variant="h2" sx={{
                    fontWeight: 550,
                }}>
                    Welcome Back<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">
                    Don't have an account? <Typography onClick={() => handlePageChange('signup')} component="span" sx={{ color: 'primary.light', cursor: 'pointer', fontSize: 15, fontWeight: 550 }}>Sign Up</Typography>
                </Typography>

                <form>
                    <Stack direction='column' sx={{ gap: 2, width: 1, maxWidth: 500, }}>
                        <TextField
                            label="Email or Username"
                            variant='filled'
                            size={isSmall ? 'small' : 'medium'}
                            color='primary'
                            value={credentials}
                            onChange={(e) => setCredentials(e.target.value)}
                            placeholder="johndoe@gmail.com"
                            error={crError || callState === 'error'}
                            sx={{
                                '& .MuiFilledInput-root': {
                                    borderColor: crError || callState === 'error' ? 'error.main' : callState === 'success' ? 'success.main' : 'primary.main',
                                    color: crError || callState === 'error' ? 'error.main' : callState === 'success' ? 'success.main' : 'inherit',
                                }
                            }}
                            slotProps={{
                                input: {
                                    endAdornment: (
                                        <InputAdornment position="end" sx={{ color: 'inherit' }}>
                                            <Iconify size={24} icon="solar:user-id-bold" />
                                        </InputAdornment>
                                    )
                                }
                            }}
                        />
                        <TextField
                            label="Password"
                            variant='filled'
                            color='primary'
                            size={isSmall ? 'small' : 'medium'}
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            placeholder='********'
                            type={hidePassword ? 'password' : 'text'}
                            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>
                                    )
                                }
                            }}
                        />
                        <Stack direction='row' gap={2} sx={{ justifyContent: 'space-between', mt: isSmall ? 2 : 4 }}>
                            <ProvidersButton {...{ handlePageChange }} />
                            <Button
                                onClick={() => { !callState && handleSignIn() }}
                                variant='contained'
                                color={(crError || 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" />
                                ) : (
                                    'Sign In'
                                )}
                            </Button>
                        </Stack>
                    </Stack>
                </form>
            </Stack>
        </Slide>
    );
};

export default SignIn;