import { useEffect, useState } from 'react';
import { Box, Button, FormControl, FormLabel, Input, VStack, Heading, useToast, Text } from '@chakra-ui/react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import api from '../services/api';

const ResetPasswordPage: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const token = searchParams.get('token') || '';
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const toast = useToast();

  useEffect(() => {
    if (!token) {
      toast({ title: 'Chybí token', description: 'Odkaz pro reset je neplatný.', status: 'error' });
    }
  }, [token, toast]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password.length < 8) {
      toast({ title: 'Slabé heslo', description: 'Heslo musí mít alespoň 8 znaků.', status: 'warning' });
      return;
    }
    if (password !== confirm) {
      toast({ title: 'Nesoulad hesel', description: 'Hesla se neshodují.', status: 'warning' });
      return;
    }
    setIsLoading(true);
    try {
      await api.post('/auth/reset-password', { token, new_password: password });
      toast({ title: 'Hotovo', description: 'Heslo bylo změněno. Přihlaste se novým heslem.', status: 'success' });
      navigate('/login');
    } catch (error: any) {
      toast({ title: 'Chyba', description: error.response?.data?.error || 'Reset hesla se nezdařil.', status: 'error' });
    } finally {
      setIsLoading(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">
          <Heading as="h2" size="lg" textAlign="center">Nastavit nové heslo</Heading>
          {!token && (
            <Text textAlign="center" color="red.500">Chybí token v URL. Zkontrolujte odkaz v e-mailu.</Text>
          )}
          <FormControl id="password" isRequired>
            <FormLabel>Nové heslo</FormLabel>
            <Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="••••••••" />
          </FormControl>
          <FormControl id="confirm" isRequired>
            <FormLabel>Potvrzení hesla</FormLabel>
            <Input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} placeholder="••••••••" />
          </FormControl>
          <Button type="submit" colorScheme="blue" isLoading={isLoading} isDisabled={!token}>Změnit heslo</Button>
        </VStack>
      </Box>
    </Box>
  );
};

export default ResetPasswordPage;
