import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Eye, EyeOff, Mail, Lock } from 'lucide-react';
import { Center } from '@astryxdesign/core/Center';
import { Card } from '@astryxdesign/core/Card';
import { VStack, HStack } from '@astryxdesign/core/Layout';
import { Text } from '@astryxdesign/core/Text';
import { TextInput } from '@astryxdesign/core/TextInput';
import { CheckboxInput } from '@astryxdesign/core/CheckboxInput';
import { Button } from '@astryxdesign/core/Button';
import { Link } from '@astryxdesign/core/Link';
import { Banner } from '@astryxdesign/core/Banner';

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 [rememberMe, setRememberMe] = useState(true);
  const [loading, setLoading] = useState(false);

  const handleLogin = async () => {
    if (!auth || !pwd || loading) return;
    setLoading(true);
    setError('');
    try {
      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');
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div
      style={{
        minHeight: '100vh',
        position: 'relative',
        backgroundImage: `url(${bgImage})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        fontFamily: 'system-ui, sans-serif'
      }}
    >
      <div
        style={{
          position: 'absolute',
          inset: 0,
          background: 'linear-gradient(180deg, rgba(15,23,42,0.6) 0%, rgba(192, 18, 39, 0.8) 100%)'
        }}
      />

      <Center axis="both" style={{ position: 'relative', minHeight: '100vh', padding: '16px', boxSizing: 'border-box' }}>
        <Card
          padding={8}
          width="100%"
          maxWidth={440}
          style={{
            background: 'rgba(255, 255, 255, 0.9)',
            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)',
            boxSizing: 'border-box'
          }}
        >
          <VStack gap={4} hAlign="stretch">
            <VStack gap={1} hAlign="center">
              <div style={{ marginBottom: '8px' }}>
                <Logo />
              </div>
              <Text type="display-1" as="h2">Welcome back</Text>
              <Text type="body" color="secondary" size="sm">
                Sign in to your Doormile operations account.
              </Text>
            </VStack>

            {error && <Banner status="error" title={error} />}

            <VStack gap={3}>
              <TextInput
                label="Email"
                isRequired
                size="lg"
                type="email"
                placeholder="admin@doormile.com"
                value={auth}
                onChange={setAuth}
                onKeyDown={handleKeyDown}
                startIcon={<Mail size={16} />}
                hasAutoFocus
              />

              <div style={{ position: 'relative' }}>
                <TextInput
                  label="Password"
                  isRequired
                  size="lg"
                  type={show ? 'text' : 'password'}
                  placeholder="Enter your password"
                  value={pwd}
                  onChange={setPwd}
                  onKeyDown={handleKeyDown}
                  startIcon={<Lock size={16} />}
                />
                <button
                  type="button"
                  onClick={() => setShow((s) => !s)}
                  aria-label={show ? 'Hide password' : 'Show password'}
                  style={{
                    position: 'absolute',
                    right: '10px',
                    bottom: 0,
                    height: '36px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    color: '#64748b',
                    padding: 0,
                    zIndex: 10
                  }}
                >
                  {show ? <EyeOff size={16} /> : <Eye size={16} />}
                </button>
              </div>
            </VStack>

            <HStack hAlign="between" vAlign="center">
              <CheckboxInput
                label="Remember me"
                value={rememberMe}
                onChange={setRememberMe}
              />
              <Link href="#" size="sm" color="secondary">Forgot password?</Link>
            </HStack>

            <Button
              label="Sign In"
              variant="primary"
              size="lg"
              onClick={handleLogin}
              isLoading={loading}
              isDisabled={!auth || !pwd}
            />
          </VStack>
        </Card>
      </Center>

      <div style={{ position: 'absolute', bottom: '20px', left: 0, right: 0, textAlign: 'center', zIndex: 2 }}>
        <Text type="supporting" style={{ color: 'rgba(255, 255, 255, 0.8)' }}>
          © {new Date().getFullYear()} Doormile Technologies. All rights reserved.
        </Text>
      </div>
    </div>
  );
}
