import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Loader from 'components/Loader';
import logo from 'assets/images/doormile-logo.png';

import { useDispatch } from 'react-redux';
import { OpenToast } from 'components/third-party/OpenToast';
import { setLoginUser } from 'store/reducers/loginUserSlice';
import { markSessionStart } from 'utils/session';
import { loginAdmin } from 'pages/api/doormileApi';
import { DT } from 'themes/dt/tokens';

// Astryx design system — see themes/astryx.js for the Doormile brand theme
// and CLAUDE.md's <!-- ASTRYX:START --> block for the CLI workflow.
// NOTE: custom CSS (xstyle/stylex.create()) isn't wired up yet — see the
// comment in config-overrides.js. Everything below uses Astryx component
// props only; the brand gradient panel and the two logo images are plain
// native elements with inline `style` for that reason.
import { AppShell } from '@astryxdesign/core/AppShell';
import { Theme } from '@astryxdesign/core/theme';
import { HStack } from '@astryxdesign/core/HStack';
import { VStack } from '@astryxdesign/core/VStack';
import { Center } from '@astryxdesign/core/Center';
import { Card } from '@astryxdesign/core/Card';
import { Heading } from '@astryxdesign/core/Heading';
import { Text } from '@astryxdesign/core/Text';
import { TextInput } from '@astryxdesign/core/TextInput';
import { Button } from '@astryxdesign/core/Button';
import { Link } from '@astryxdesign/core/Link';
import { Divider } from '@astryxdesign/core/Divider';
import { doormileTheme } from 'themes/astryx';

const brandPanelStyle = {
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'center',
  position: 'relative',
  overflow: 'hidden',
  width: '46%',
  height: '100vh',
  color: '#fff',
  padding: 48,
  background: `linear-gradient(150deg, ${DT.brand} 0%, #D25463 100%)`
};

const logoLockupStyle = { position: 'absolute', top: 48, left: 48, maxHeight: 60 };

const bulletDotStyle = {
  width: 22,
  height: 22,
  borderRadius: '50%',
  backgroundColor: 'rgba(255, 255, 255, 0.18)',
  display: 'inline-flex',
  alignItems: 'center',
  justifyContent: 'center',
  fontSize: 13,
  fontWeight: 700,
  flexShrink: 0
};

// doormile-logo.png is a white asset; recolour to brand red for this
// white-background card (the brand-panel logo stays white as-is).
const formLogoStyle = {
  maxHeight: 48,
  filter: 'brightness(0) saturate(100%) invert(15%) sepia(93%) saturate(5437%) hue-rotate(346deg) brightness(81%) contrast(92%)'
};

const BULLETS = ['Real-time fleet visibility', 'AI-optimised dispatch routes', 'Tenant, pricing & invoice control'];

const Login = () => {
  const dispatch = useDispatch();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  useEffect(() => {
    // 'authname' is the AUTH_PRESENCE_KEY (utils/session.js) — App.js and the
    // inactivity/cross-tab logout machinery all key off it, unrelated to which
    // backend actually authenticated the session.
    if (localStorage.getItem('authname')) {
      navigate('/doormile/dispatch');
    }
  }, []);

  const opentoast = (message, variant = 'error') => OpenToast(message, variant, 2000);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email || !password) {
      opentoast('Enter your email and password');
      return;
    }

    setLoading(true);
    try {
      const res = await loginAdmin(email, password);
      if (res.success) {
        const user = res.user || {};
        // Compatibility keys: existing pages/api.js read userid/roleid/tenantid
        // straight from localStorage rather than through a context. 'authname'
        // stays the AUTH_PRESENCE_KEY so the rest of the session contract
        // (useInactivityLogout, cross-tab logout, App.js gate) needs no changes.
        localStorage.setItem('authname', user.email || user.name || email);
        localStorage.setItem('firstname', user.name || '');
        localStorage.setItem('userid', user.id ?? '');
        localStorage.setItem('roleid', user.role ?? '');
        localStorage.setItem('tenantid', user.tenantid ?? '');
        dispatch(setLoginUser(user));
        markSessionStart();
        opentoast('Login successful', 'success');
        navigate('/doormile/dispatch');
      } else {
        opentoast(res.message || 'Login failed');
      }
    } catch (err) {
      opentoast(err?.message || 'Login failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Theme theme={doormileTheme} mode="light">
      <AppShell contentPadding={0}>
        {loading && <Loader />}
        <HStack gap={0} height="100vh" wrap="nowrap">
          {/* ---- Left brand panel (plain element: see the note at the top of
              this file about custom styling not going through Astryx yet) ---- */}
          <div style={brandPanelStyle}>
            <img src={logo} alt="Doormile" style={logoLockupStyle} />

            <VStack gap={2} maxWidth={430}>
              <Heading level={1} color="inherit">
                Operate your dispatch, end to end.
              </Heading>
              <Text type="large" color="inherit">
                Orders, AI route optimisation, live rider tracking and billing — all in the Doormile Express operator console.
              </Text>

              <VStack gap={1.5} padding={0}>
                {BULLETS.map((t) => (
                  <HStack key={t} gap={1.25} vAlign="center">
                    <span style={bulletDotStyle}>✓</span>
                    <Text color="inherit">{t}</Text>
                  </HStack>
                ))}
              </VStack>
            </VStack>
          </div>

          {/* ---- Right form panel ---- */}
          <Center axis="both" width="54%" height="100vh">
            <VStack width="100%" maxWidth={440} gap={4} padding={3}>
              <Card padding={8} elevation="med">
                <VStack gap={6} padding={0}>
                  <VStack gap={1.5} hAlign="center" padding={0}>
                    <img src={logo} alt="Doormile" style={formLogoStyle} />
                    <Heading level={2}>Welcome back</Heading>
                    <Text type="supporting">Sign in to the Doormile Express console</Text>
                  </VStack>

                  <Divider />

                  <form noValidate onSubmit={handleSubmit}>
                    <VStack gap={4} padding={0}>
                      <TextInput
                        hasAutoFocus
                        label="E-mail Address"
                        type="email"
                        size="lg"
                        isRequired
                        value={email}
                        onChange={(value) => setEmail(value.toLocaleLowerCase())}
                      />
                      <TextInput
                        label="Password"
                        type="password"
                        size="lg"
                        isRequired
                        value={password}
                        onChange={(value) => setPassword(value)}
                      />
                      <Button label="Sign in" type="submit" variant="primary" size="lg" width="100%" />
                    </VStack>
                  </form>
                </VStack>
              </Card>

              {/* footer */}
              <HStack justify="center" wrap="wrap" gap={2}>
                <Link href="https://nearle.in" target="_blank" isExternalLink type="supporting">
                  &copy; All rights reserved
                </Link>
                <Link href="https://nearle.in/terms" target="_blank" isExternalLink type="supporting">
                  Terms and Conditions
                </Link>
                <Link href="https://nearle.in/privacy" target="_blank" isExternalLink type="supporting">
                  Privacy Policy
                </Link>
              </HStack>
            </VStack>
          </Center>
        </HStack>
      </AppShell>
    </Theme>
  );
};

export default Login;
