import { useTranslation } from 'react-i18next';
import React, { useState } from 'react';
import { 
  Box, 
  Button, 
  Checkbox, 
  Container, 
  FormControlLabel, 
  TextField, 
  Typography, 
  Link,
  AppBar,
  Toolbar,
  Card,
  CardContent,
  Alert,
  Tabs,
  Tab,
  InputAdornment,
  IconButton,
} from '@mui/material';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import LanguageSwitcher from '../../components/LanguageSwitcher';
import { useLoginPage } from '../../hooks/login-hooks';

const Login = () => {
  const { t } = useTranslation();
  const [showLoginPassword, setShowLoginPassword] = useState(false);
  const [showRegisterPassword, setShowRegisterPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const {
    // 表单状态
    tabValue,
    setTabValue,
    error,
    loginForm,
    registerForm,
    
    // 表单操作
    handleTabChange,
    
    // 提交处理
    handleLogin,
    handleRegister,
    isSubmitting,
    
    // 验证规则
    loginValidation,
    registerValidation
  } = useLoginPage();

  return (
    <Box sx={{ minHeight: '100vh', width: '100vw', bgcolor: 'background.default', display: 'flex', flexDirection: 'column' }}>
      {/* 顶部栏使用主题主色 */}
      <AppBar position="static" color="primary" enableColorOnDark>
        <Toolbar sx={{ minHeight: 60, justifyContent: 'space-between' }}>
          <Box
            sx={{
              width: 40,
              height: 40,
              bgcolor: 'common.white',
              color: 'primary.main',
              borderRadius: '50%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontWeight: 700,
              fontSize: '1.1rem',
            }}
            aria-label="Brand"
          >
            T
          </Box>
          <LanguageSwitcher />
        </Toolbar>
      </AppBar>

      {/* 主体卡片 */}
      <Container maxWidth="sm" sx={{ flex: 1, display: 'flex', alignItems: 'center' }}>
        <Card sx={{ width: '100%' }}>
          <CardContent sx={{ p: 4 }}>
            <Typography variant="subtitle1" color="text.secondary" sx={{ mb: 1, display: 'block' }}>
              TERES AI
            </Typography>
            
            {/* 标签页 */}
            <Tabs value={tabValue} onChange={handleTabChange} sx={{ mb: 3 }}>
              <Tab label={t('login.login')} />
              <Tab label={t('login.signUp')} />
            </Tabs>

            {error && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {error}
              </Alert>
            )}

            {/* 登录表单 */}
            {tabValue === 0 && (
              <Box component="form" onSubmit={loginForm.handleSubmit(handleLogin)} noValidate>
                <Typography variant="h5" fontWeight={700} sx={{ mb: 2 }}>
                  {t('login.loginDescription')}
                </Typography>
                
                <TextField
                  fullWidth
                  id="login-email"
                  type="email"
                  placeholder={t('login.emailPlaceholder')}
                  autoComplete="email"
                  {...loginForm.register('email', loginValidation.email)}
                  error={!!loginForm.formState.errors.email}
                  helperText={loginForm.formState.errors.email?.message}
                  sx={{ mb: 2 }}
                />

                <TextField
                  fullWidth
                  id="login-password"
                  type={showLoginPassword ? 'text' : 'password'}
                  placeholder={t('login.passwordPlaceholder')}
                  autoComplete="current-password"
                  {...loginForm.register('password', loginValidation.password)}
                  error={!!loginForm.formState.errors.password}
                  helperText={loginForm.formState.errors.password?.message}
                  sx={{ mb: 2 }}
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton
                          aria-label={showLoginPassword ? 'Hide password' : 'Show password'}
                          onClick={() => setShowLoginPassword((v) => !v)}
                          onMouseDown={(e) => e.preventDefault()}
                          edge="end"
                        >
                          {showLoginPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                />

                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
                  <FormControlLabel
                    control={
                      <Checkbox
                        {...loginForm.register('rememberEmail')}
                        id="rememberEmail"
                      />
                    }
                    label={t('login.rememberMe')}
                  />
                </Box>

                <Button 
                  type="submit" 
                  variant="contained" 
                  fullWidth 
                  disabled={isSubmitting}
                  sx={{ mb: 2 }}
                >
                  {isSubmitting ? 'Processing...' : t('login.login')}
                </Button>
              </Box>
            )}

            {/* 注册表单 */}
            {tabValue === 1 && (
              <Box component="form" onSubmit={registerForm.handleSubmit(handleRegister)} noValidate>
                <Typography variant="h5" fontWeight={700} sx={{ mb: 2 }}>
                  {t('login.registerDescription')}
                </Typography>
                
                <TextField
                  fullWidth
                  id="register-nickname"
                  placeholder={t('login.nicknamePlaceholder')}
                  {...registerForm.register('nickname', registerValidation.nickname)}
                  error={!!registerForm.formState.errors.nickname}
                  helperText={registerForm.formState.errors.nickname?.message}
                  sx={{ mb: 2 }}
                />

                <TextField
                  fullWidth
                  id="register-email"
                  type="email"
                  placeholder={t('login.emailPlaceholder')}
                  autoComplete="email"
                  {...registerForm.register('email', registerValidation.email)}
                  error={!!registerForm.formState.errors.email}
                  helperText={registerForm.formState.errors.email?.message}
                  sx={{ mb: 2 }}
                />

                <TextField
                  fullWidth
                  id="register-password"
                  type={showRegisterPassword ? 'text' : 'password'}
                  placeholder={t('login.passwordPlaceholder')}
                  autoComplete="new-password"
                  {...registerForm.register('password', registerValidation.password)}
                  error={!!registerForm.formState.errors.password}
                  helperText={registerForm.formState.errors.password?.message}
                  sx={{ mb: 2 }}
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton
                          aria-label={showRegisterPassword ? 'Hide password' : 'Show password'}
                          onClick={() => setShowRegisterPassword((v) => !v)}
                          onMouseDown={(e) => e.preventDefault()}
                          edge="end"
                        >
                          {showRegisterPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                />

                <TextField
                  fullWidth
                  id="register-confirm-password"
                  type={showConfirmPassword ? 'text' : 'password'}
                  placeholder={t('confirmPassword')}
                  autoComplete="new-password"
                  {...registerForm.register('confirmPassword', registerValidation.confirmPassword)}
                  error={!!registerForm.formState.errors.confirmPassword}
                  helperText={registerForm.formState.errors.confirmPassword?.message}
                  sx={{ mb: 2 }}
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton
                          aria-label={showConfirmPassword ? 'Hide password' : 'Show password'}
                          onClick={() => setShowConfirmPassword((v) => !v)}
                          onMouseDown={(e) => e.preventDefault()}
                          edge="end"
                        >
                          {showConfirmPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                />

                <Button 
                  type="submit" 
                  variant="contained" 
                  fullWidth 
                  disabled={isSubmitting}
                  sx={{ mb: 2 }}
                >
                  {isSubmitting ? 'Processing...' : t('login.register')}
                </Button>
              </Box>
            )}

            <Box sx={{ mt: 2, textAlign: 'center' }}>
              <Box mt={0.5}>
                {tabValue === 0 ? (
                  <>
                    {t('login.signInTip')} <Link href="#" onClick={() => setTabValue(1)}>{t('login.signUp')}</Link>.
                  </>
                ) : (
                  <>
                    {t('login.signUpTip')} <Link href="#" onClick={() => setTabValue(0)}>{t('login.login')}</Link>.
                  </>
                )}
              </Box>
            </Box>
          </CardContent>
        </Card>
      </Container>

      {/* 页脚 */}
      <Box
        sx={{
          borderTop: '1px solid',
          borderColor: 'divider',
          height: 50,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          px: 2,
          color: 'text.secondary',
          bgcolor: 'background.paper',
        }}
      >
        <Box>© Deutsche Telekom AG</Box>
        <Box sx={{ display: 'flex', gap: 2 }}>
          <Link href="#" color="inherit">Imprint</Link>
          <Link href="#" color="inherit">Data privacy</Link>
        </Box>
      </Box>
    </Box>
  );
};

export default Login;