import { useState, useEffect } from 'react';
import { useNavigate, useLocation, Navigate } from 'react-router-dom';
import { 
  Box, 
  Button, 
  FormControl, 
  FormLabel, 
  Input, 
  InputGroup,
  InputRightElement,
  VStack, 
  Heading, 
  useToast, 
  useColorModeValue,
  Image,
  Center,
  Checkbox,
} from '@chakra-ui/react';
import { useAuth } from '../contexts/AuthContext';
import api from '../services/api';
import { getPublicSettings, PublicSettings } from '../services/settings';
import { assetUrl } from '../utils/url';

interface LocationState {
  from: {
    pathname: string;
  };
}

const AuthPage: React.FC = () => {
  // All hooks must be called at the top level, before any conditional returns
  const { isAuthenticated, adminExists, login } = useAuth();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [remember, setRemember] = useState(true);
  const [settings, setSettings] = useState<PublicSettings | null>(null);
  const navigate = useNavigate();
  const location = useLocation();
  const toast = useToast();
  const bgColor = useColorModeValue('white', 'gray.800');

  // Load public settings to display club logo
  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const s = await getPublicSettings();
        if (mounted) setSettings(s);
      } catch (_) {
        // ignore
      }
    })();
    return () => { mounted = false; };
  }, []);
  
  // If user is already authenticated, redirect to admin dashboard
  if (isAuthenticated) {
    return <Navigate to="/admin" replace />;
  }

  const from = (location.state as LocationState)?.from?.pathname || '/admin';

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);

    try {
      const response = await api.post('/auth/login', { email, password });
      const { token, user } = response.data;
      login(token, user, remember);
      toast({
        title: 'Přihlášení proběhlo úspěšně',
        status: 'success',
        duration: 3000,
        isClosable: true,
      });
      // Redirect to original destination or dashboard
      navigate(from, { replace: true });
    } catch (error: any) {
      toast({
        title: 'Přihlášení selhalo',
        description: error.response?.data?.error || error.response?.data?.message || 'Neplatný e-mail nebo heslo',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    } finally {
      setIsLoading(false);
    }
  };

  // Removed inline reset sender button; keep single link to forgot-password page/modal

  // Registration has been removed for initial setup flow; only login is shown

  return (
    <Box minH="100vh" display="flex" alignItems="center" justifyContent="center" bg="gray.50">
      <Box w="100%" maxW="md" p={8} bg={bgColor} borderRadius="lg" boxShadow="lg">
        <Center mb={4}>
          {settings?.club_logo_url ? (
            <Image src={assetUrl(settings.club_logo_url) || settings.club_logo_url} alt={settings.club_name || 'Club logo'} maxH="64px" objectFit="contain" />
          ) : (
            <Heading size="md">Přihlášení</Heading>
          )}
        </Center>
        <VStack as="form" onSubmit={handleLogin} spacing={4} align="stretch">
          <FormControl id="login-email" isRequired>
            <FormLabel>E-mailová adresa</FormLabel>
            <Input 
              type="email" 
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="Zadejte svůj e-mail"
            />
          </FormControl>
          <FormControl id="login-password" isRequired>
            <FormLabel>Heslo</FormLabel>
            <InputGroup>
              <Input 
                type={showPassword ? 'text' : 'password'} 
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Zadejte své heslo"
              />
              <InputRightElement width="4.5rem">
                <Button h="1.75rem" size="sm" onClick={() => setShowPassword((s) => !s)}>{showPassword ? 'Skrýt' : 'Zobrazit'}</Button>
              </InputRightElement>
            </InputGroup>
          </FormControl>
          <Checkbox isChecked={remember} onChange={(e) => setRemember(e.target.checked)}>Zapamatovat přihlášení</Checkbox>
          <Button 
            type="submit" 
            colorScheme="blue" 
            isLoading={isLoading} 
            loadingText="Přihlašuji..."
            mt={4}
          >
            Přihlásit se
          </Button>
          <Box display="flex" alignItems="center" justifyContent="flex-end">
            <Button variant="link" colorScheme="blue" onClick={() => navigate('/forgot-password?admin=1')}>Zapomněli jste heslo?</Button>
          </Box>
        </VStack>
      </Box>
    </Box>
  );
};

export default AuthPage;
