import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Grid,
  Card,
  Stack,
  Typography,
  TextField,
  InputAdornment,
  IconButton,
  Button,
  Checkbox,
  FormControlLabel,
  Link
} from '@mui/material';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';

import Logo from '@/components/Logo';
import bgImage from '../../assets/mid-mile-approach.jpg';

import { loginAdmin } from '@/utils/apiClient';

export default function Login() {
  const navigate = useNavigate();
  const [show, setShow] = useState(false);
  const [auth, setAuth] = useState('');
  const [pwd, setPwd] = useState('');
  const [error, setError] = useState('');

  const handleLogin = async () => {
    try {
      setError('');
      const data = await loginAdmin(auth, pwd);
      localStorage.setItem('logged_in', 'true');
      localStorage.setItem('auth_token', data.token);
      localStorage.setItem('user', JSON.stringify(data.user));
      navigate('/dashboard');
    } catch (err) {
      setError(err.message || 'Invalid email or password');
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') handleLogin();
  };

  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundImage: `url(${bgImage})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        position: 'relative',
        '&::before': {
          content: '""',
          position: 'absolute',
          inset: 0,
          background: 'linear-gradient(180deg, rgba(15,23,42,0.6) 0%, rgba(192, 18, 39, 0.8) 100%)',
          zIndex: 1
        }
      }}
    >
      <Card
        sx={{
          position: 'relative',
          zIndex: 2,
          width: '100%',
          maxWidth: 440,
          p: { xs: 4, sm: 5 },
          m: 2,
          background: 'rgba(255, 255, 255, 0.85)',
          backdropFilter: 'blur(24px)',
          WebkitBackdropFilter: 'blur(24px)',
          border: '1px solid rgba(255, 255, 255, 0.5)',
          boxShadow: '0 24px 48px rgba(0,0,0,0.2)',
          borderRadius: 4,
        }}
      >
        <Box sx={{ mb: 4, display: 'flex', justifyContent: 'center' }}><Logo /></Box>
        <Typography variant="h3" sx={{ fontWeight: 800, textAlign: 'center', letterSpacing: '-0.5px', color: '#1e293b' }}>Welcome back</Typography>
        <Typography variant="body1" sx={{ mt: 1, mb: 4, textAlign: 'center', color: '#475569' }}>
          Sign in to your Doormile operations account.
        </Typography>

        <Stack spacing={2.5}>
          <Box>
            <Typography variant="subtitle2" sx={{ mb: 0.75, color: '#334155', fontWeight: 600 }}>Email</Typography>
            <TextField
              fullWidth
              placeholder="Enter your email address"
              value={auth}
              onChange={(e) => setAuth(e.target.value)}
              onKeyDown={handleKeyDown}
              sx={{
                '& .MuiOutlinedInput-root': {
                  bgcolor: 'rgba(255,255,255,0.6)',
                  borderRadius: 2,
                  transition: 'all 0.2s ease',
                  '&:hover': { bgcolor: 'rgba(255,255,255,0.9)' },
                  '&.Mui-focused': { bgcolor: '#fff', boxShadow: '0 4px 12px rgba(0,0,0,0.05)' }
                }
              }}
            />
          </Box>
          <Box>
            <Typography variant="subtitle2" sx={{ mb: 0.75, color: '#334155', fontWeight: 600 }}>Password</Typography>
            <TextField
              fullWidth
              type={show ? 'text' : 'password'}
              placeholder="Enter your password"
              value={pwd}
              onChange={(e) => setPwd(e.target.value)}
              onKeyDown={handleKeyDown}
              sx={{
                '& .MuiOutlinedInput-root': {
                  bgcolor: 'rgba(255,255,255,0.6)',
                  borderRadius: 2,
                  transition: 'all 0.2s ease',
                  '&:hover': { bgcolor: 'rgba(255,255,255,0.9)' },
                  '&.Mui-focused': { bgcolor: '#fff', boxShadow: '0 4px 12px rgba(0,0,0,0.05)' }
                }
              }}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton onClick={() => setShow((s) => !s)} edge="end" size="small">
                      {show ? <VisibilityOff fontSize="small" sx={{ color: '#94a3b8' }} /> : <Visibility fontSize="small" sx={{ color: '#94a3b8' }} />}
                    </IconButton>
                  </InputAdornment>
                )
              }}
            />
          </Box>
          <Stack direction="row" justifyContent="space-between" alignItems="center">
            <FormControlLabel control={<Checkbox defaultChecked size="small" sx={{ color: '#cbd5e1', '&.Mui-checked': { color: 'primary.main' } }} />} label={<Typography variant="body2" sx={{ color: '#475569', fontWeight: 500 }}>Remember me</Typography>} />
            <Link href="#" underline="hover" variant="body2" color="primary" sx={{ fontWeight: 600 }}>Forgot password?</Link>
          </Stack>

          {error && <Typography variant="body2" color="error" textAlign="center" sx={{ fontWeight: 600 }}>{error}</Typography>}

          <Button
            fullWidth
            size="large"
            variant="contained"
            onClick={handleLogin}
            sx={{
              mt: 2,
              py: 1.5,
              borderRadius: 2,
              fontSize: '1.05rem',
              fontWeight: 700,
              textTransform: 'none',
              boxShadow: '0 8px 16px rgba(192, 18, 39, 0.25)',
              '&:hover': {
                boxShadow: '0 12px 20px rgba(192, 18, 39, 0.35)',
              },
              transition: 'box-shadow 0.2s ease'
            }}
          >
            Sign In
          </Button>
        </Stack>
      </Card>

      <Box sx={{ position: 'absolute', bottom: 20, zIndex: 2 }}>
        <Typography variant="caption" sx={{ color: 'rgba(255,255,255,0.8)', fontSize: '0.8rem' }}>
          © {new Date().getFullYear()} Doormile Technologies. All rights reserved.
        </Typography>
      </Box>
    </Box>
  );
}
