import { useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Box, Button, FormControl, FormLabel, Input, VStack, Heading, useToast, Image, Text, Modal, ModalOverlay, ModalContent, ModalHeader, ModalBody, ModalFooter, ModalCloseButton, useDisclosure } from '@chakra-ui/react';
import { useAuth } from '../contexts/AuthContext';
import api from '../services/api';
import { getPublicSettings } from '../services/settings';
import { assetUrl } from '../utils/url';

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

const LoginPage: React.FC = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [clubName, setClubName] = useState<string>('');
  const [clubLogoUrl, setClubLogoUrl] = useState<string>('');
  const { isOpen: isForgotOpen, onOpen: onForgotOpen, onClose: onForgotClose } = useDisclosure();
  const [forgotEmail, setForgotEmail] = useState('');
  const [isForgotSubmitting, setIsForgotSubmitting] = useState(false);
  const { login } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const toast = useToast();

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

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

    try {
      const response = await api.post('/auth/login', { email, password });
      // Assuming the API returns both token and user data in the response
      const { token, user } = response.data;
      login(token, user);
      navigate(from, { replace: true });
    } catch (error: any) {
      toast({
        title: 'Login failed',
        description: error.response?.data?.message || 'An error occurred',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleForgotOpen = () => {
    setForgotEmail(email);
    onForgotOpen();
  };

  const handleForgotSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!forgotEmail) {
      toast({ title: 'Zadejte email', status: 'warning', duration: 3000, isClosable: true });
      return;
    }
    setIsForgotSubmitting(true);
    try {
      // Use admin-specific endpoint so it can use override SMTP if configured
      await api.post('/auth/forgot-password-admin', { email: forgotEmail });
      toast({
        title: 'Odkaz odeslán',
        description: 'Pokud email existuje, poslala se zpráva s odkazem pro reset hesla.',
        status: 'success',
        duration: 5000,
        isClosable: true,
      });
      onForgotClose();
    } catch (error: any) {
      // Backend intentionally returns success even when user not found; handle unexpected errors
      toast({
        title: 'Chyba při odesílání',
        description: error.response?.data?.error || 'Zkuste to prosím znovu.',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    } finally {
      setIsForgotSubmitting(false);
    }
  };

  // Load public settings to display club identity (logo + club name)
  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const s = await getPublicSettings();
        if (!mounted) return;
        if (s?.club_name) setClubName(s.club_name);
        if (s?.club_logo_url) setClubLogoUrl(s.club_logo_url);
      } catch {}
    })();
    return () => { mounted = false; };
  }, []);

  return (
    <Box minH="100vh" display="flex" alignItems="center" justifyContent="center">
      <Box w="100%" maxW="md" p={8} borderWidth={1} borderRadius={8} boxShadow="lg">
        <VStack as="form" onSubmit={handleSubmit} spacing={4} align="stretch">
          {clubLogoUrl ? (
            <Image src={assetUrl(clubLogoUrl) || clubLogoUrl} alt={clubName || 'Klub'} boxSize="64px" objectFit="contain" mx="auto" mb={2} />
          ) : null}
          <Heading as="h2" size="lg" textAlign="center" mb={2}>
            {clubName || 'Přihlášení'}
          </Heading>
          {!clubName ? (
            <Text textAlign="center" color="gray.500" mb={2}>Sign In</Text>
          ) : null}
          
          <FormControl id="email" isRequired>
            <FormLabel>Email address</FormLabel>
            <Input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="Enter your email"
            />
          </FormControl>

          <FormControl id="password" isRequired>
            <FormLabel>Password</FormLabel>
            <Input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Enter your password"
            />
          </FormControl>

          <Text textAlign="right" fontSize="sm" color="blue.600" _hover={{ textDecoration: 'underline', cursor: 'pointer' }} onClick={handleForgotOpen}>
            Zapomněli jste heslo?
          </Text>

          <Button
            type="submit"
            colorScheme="blue"
            width="full"
            mt={4}
            isLoading={isLoading}
            loadingText="Signing in..."
          >
            Sign In
          </Button>
        </VStack>
      </Box>

      {/* Forgot Password Modal */}
      <Modal isOpen={isForgotOpen} onClose={onForgotClose} isCentered>
        <ModalOverlay />
        <ModalContent as="form" onSubmit={handleForgotSubmit}>
          <ModalHeader>Reset hesla</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <FormControl id="forgot-email" isRequired>
              <FormLabel>Zadejte svůj email</FormLabel>
              <Input
                type="email"
                value={forgotEmail}
                onChange={(e) => setForgotEmail(e.target.value)}
                placeholder="např. jan@priklad.cz"
                autoFocus
              />
            </FormControl>
            <Text mt={3} fontSize="sm" color="gray.600">
              Po odeslání vám přijde na zadaný email odkaz s tokenem pro změnu hesla.
            </Text>
          </ModalBody>
          <ModalFooter>
            <Button variant="ghost" mr={3} onClick={onForgotClose}>Zavřít</Button>
            <Button colorScheme="blue" type="submit" isLoading={isForgotSubmitting} loadingText="Odesílám...">
              Poslat odkaz
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </Box>
  );
};

export default LoginPage;
