import {
    Box,
    Button,
    Container,
    TextField,
    Typography,
    InputAdornment,
    IconButton,
    LinearProgress,
} from '@mui/material'
import Visibility from '@mui/icons-material/Visibility'
import VisibilityOff from '@mui/icons-material/VisibilityOff'
import { useEffect, useState } from 'react'
import api from '../lib/api'

export default function MePage() {
    const [email, setEmail] = useState('')
    const [currentPassword, setCurrentPassword] = useState('')
    const [newPassword, setNewPassword] = useState('')
    const [confirmPassword, setConfirmPassword] = useState('')

    const [passwordError, setPasswordError] = useState('')
    const [message, setMessage] = useState<string | null>(null)
    const [showPassword, setShowPassword] = useState(false)

    const [strengthScore, setStrengthScore] = useState(0)
    const [strengthLabel, setStrengthLabel] = useState<'약함' | '보통' | '강함' | ''>('')

    useEffect(() => {
        api.get('/users/me')
            .then(res => setEmail(res.data.email || ''))
            .catch(() => setMessage('내 정보를 불러오는데 실패했습니다.'))
    }, [])

    const analyzePassword = (pw: string) => {
        let score = 0
        if (/[a-z]/.test(pw)) score++
        if (/[A-Z]/.test(pw)) score++
        if (/\d/.test(pw)) score++
        if (/[^A-Za-z0-9]/.test(pw)) score++
        if (pw.length >= 10) score++

        setStrengthScore(score)

        if (score <= 2) setStrengthLabel('약함')
        else if (score <= 4) setStrengthLabel('보통')
        else setStrengthLabel('강함')
    }

    const validatePassword = (pw: string) => {
        const regex = /^(?=.*[A-Za-z])(?=.*\d).{6,20}$/
        return regex.test(pw)
    }

    const handleSubmit = async () => {
        setPasswordError('')
        setMessage(null)

        if (!validatePassword(newPassword)) {
            setPasswordError('비밀번호는 영문자+숫자를 포함한 6~20자여야 합니다.')
            return
        }

        if (newPassword !== confirmPassword) {
            setPasswordError('비밀번호가 일치하지 않습니다.')
            return
        }

        try {
            await api.put('/users/me/password', {
                current_password: currentPassword,
                new_password: newPassword
            })
            setMessage('비밀번호가 성공적으로 변경되었습니다.')
            setCurrentPassword('')
            setNewPassword('')
            setConfirmPassword('')
            setStrengthScore(0)
            setStrengthLabel('')
        } catch {
            setMessage('비밀번호 변경에 실패했습니다.')
        }
    }

    return (
        <Container maxWidth="sm" sx={{ mt: 4 }}>
            <Typography variant="h5" gutterBottom>내 정보</Typography>

            <TextField
                label="이메일"
                value={email ?? ''}
                fullWidth
                disabled
                margin="normal"
            />

            <TextField
                label="현재 비밀번호"
                type="password"
                fullWidth
                value={currentPassword}
                onChange={(e) => setCurrentPassword(e.target.value)}
                margin="normal"
            />

            <TextField
                label="새 비밀번호"
                type={showPassword ? 'text' : 'password'}
                fullWidth
                value={newPassword}
                onChange={(e) => {
                    const pw = e.target.value
                    setNewPassword(pw)
                    analyzePassword(pw)
                }}
                margin="normal"
                helperText="영문자+숫자 포함 6~20자, 특수문자 허용"
                InputProps={{
                    endAdornment: (
                        <InputAdornment position="end">
                            <IconButton onClick={() => setShowPassword(!showPassword)} edge="end">
                                {showPassword ? <VisibilityOff /> : <Visibility />}
                            </IconButton>
                        </InputAdornment>
                    ),
                }}
                error={!!passwordError}
            />

            {strengthLabel && (
                <Box>
                    <Typography variant="body2" gutterBottom>
                        비밀번호 강도: {strengthLabel}
                    </Typography>
                    <LinearProgress
                        variant="determinate"
                        value={(strengthScore / 5) * 100}
                        sx={{
                            height: 10,
                            borderRadius: 5,
                            backgroundColor: '#555',
                            '& .MuiLinearProgress-bar': {
                                backgroundColor:
                                    strengthLabel === '강함' ? '#4caf50' :
                                        strengthLabel === '보통' ? '#ff9800' :
                                            '#f44336',
                            },
                        }}
                    />
                </Box>
            )}

            <TextField
                label="새 비밀번호 확인"
                type="password"
                fullWidth
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                margin="normal"
            />

            <Button
                variant="contained"
                color="primary"
                onClick={handleSubmit}
                sx={{ mt: 2 }}
                fullWidth
                disabled={!!passwordError}
            >
                비밀번호 변경
            </Button>

            {(message || passwordError) && (
                <Typography variant="body2" color="error" sx={{ mt: 2 }}>
                    {message || passwordError}
                </Typography>
            )}
        </Container>
    )
}
