import { useState, useEffect } from 'react';
import {
  Box,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  Button,
  useDisclosure,
  useToast,
  Badge,
  IconButton,
  Menu,
  MenuButton,
  MenuList,
  MenuItem,
  useColorModeValue,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
  FormControl,
  FormLabel,
  Input,
  Select,
  VStack,
  HStack,
  Text,
  Switch,
  FormHelperText,
  Heading,
  Spinner,
  Alert,
  AlertIcon,
  AlertTitle,
  AlertDescription,
} from '@chakra-ui/react';
import { AddIcon, DeleteIcon, EditIcon, HamburgerIcon } from '@chakra-ui/icons';
import { useAuth } from '../../contexts/AuthContext';
import api from '../../services/api';
import AdminLayout from '../../layouts/AdminLayout';

interface User {
  id: string;
  email: string;
  name: string;
  role: 'admin' | 'editor';
  isActive: boolean;
  createdAt: string;
}

const UsersAdminPage = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { isOpen, onOpen, onClose } = useDisclosure();
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    password: '',
  currentPassword: '',
    role: 'editor' as 'admin' | 'editor',
    isActive: true,
  });
  const toast = useToast();
  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  const { user: authUser } = useAuth();

  const fetchUsers = async () => {
    try {
      const response = await api.get('/admin/users');
      setUsers(response.data);
    } catch (error) {
      console.error('Error fetching users:', error);
      toast({
        title: 'Error',
        description: 'Failed to fetch users',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name === 'isActive' ? (e.target as HTMLInputElement).checked : value
    }));
  };

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

    try {
      if (selectedUser) {
        // Update existing user
        // If editing an admin account, require current password confirmation
        const payload: any = {
          name: formData.name,
          email: formData.email,
          role: formData.role,
          isActive: formData.isActive,
        };
        if (selectedUser.role === 'admin') {
          if (!formData.currentPassword) {
            throw new Error('Pro úpravu administrátorského účtu zadejte prosím současné heslo.');
          }
          payload.current_password = formData.currentPassword;
        }
        await api.put(`/admin/users/${selectedUser.id}`, payload);
        toast({
          title: 'Success',
          description: 'User updated successfully',
          status: 'success',
          duration: 3000,
          isClosable: true,
        });
      } else {
        // Create new user
        await api.post('/admin/users', formData);
        toast({
          title: 'Success',
          description: 'User created successfully',
          status: 'success',
          duration: 3000,
          isClosable: true,
        });
      }
      onClose();
      fetchUsers();
      resetForm();
    } catch (error: any) {
      console.error('Error saving user:', error);
      toast({
        title: 'Error',
        description: error.response?.data?.error || error.response?.data?.message || 'Failed to save user',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async (userId: string) => {
    const u = users.find(x => x.id === userId);
    if (u?.role === 'admin') {
      toast({ title: 'Zakázáno', description: 'Admin uživatele nelze smazat.', status: 'warning' });
      return;
    }
    if (authUser && String(authUser.id) === String(userId)) {
      toast({ title: 'Zakázáno', description: 'Nemůžete smazat sám sebe.', status: 'warning' });
      return;
    }
    if (window.confirm('Are you sure you want to delete this user?')) {
      try {
        await api.delete(`/admin/users/${userId}`);
        toast({
          title: 'Success',
          description: 'User deleted successfully',
          status: 'success',
          duration: 3000,
          isClosable: true,
        });
        fetchUsers();
      } catch (error: any) {
        console.error('Error deleting user:', error);
        toast({
          title: 'Error',
          description: error.response?.data?.error || error.response?.data?.message || 'Failed to delete user',
          status: 'error',
          duration: 5000,
          isClosable: true,
        });
      }
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      email: '',
      password: '',
      currentPassword: '',
      role: 'editor',
      isActive: true,
    });
    setSelectedUser(null);
  };

  const openEditModal = (user: User) => {
    setSelectedUser(user);
    setFormData({
      name: user.name,
      email: user.email,
      password: '',
  currentPassword: '',
      role: user.role,
      isActive: user.isActive,
    });
    onOpen();
  };

  const openCreateModal = () => {
    resetForm();
    onOpen();
  };

  return (
    <AdminLayout>
      <Box>
        <HStack justify="space-between" mb={4}>
          <Heading size="lg">Správa uživatelů</Heading>
          <Button leftIcon={<AddIcon />} colorScheme="blue" onClick={openCreateModal}>
            Přidat uživatele
          </Button>
        </HStack>
        <Text color="gray.500" mb={6}>
          Správa uživatelských účtů a jejich oprávnění. <strong>Editor</strong> může vytvářet a upravovat články a aktivity. <strong>Admin</strong> má přístup ke všem funkcím.
        </Text>

        <Box bg={bgColor} borderRadius="md" boxShadow="sm" overflowX="auto">
        <Table variant="simple">
          <Thead>
            <Tr>
              <Th>Name</Th>
              <Th>Email</Th>
              <Th>Role</Th>
              <Th>Status</Th>
              <Th>Created</Th>
              <Th>Actions</Th>
            </Tr>
          </Thead>
          <Tbody>
            {users.map((user) => (
              <Tr key={user.id}>
                <Td>{user.name}</Td>
                <Td>{user.email}</Td>
                <Td>
                  <Badge colorScheme={user.role === 'admin' ? 'purple' : 'blue'}>
                    {user.role === 'admin' ? 'Admin' : 'Editor'}
                  </Badge>
                </Td>
                <Td>
                  <Badge colorScheme={user.isActive ? 'green' : 'red'}>
                    {user.isActive ? 'Active' : 'Inactive'}
                  </Badge>
                </Td>
                <Td>{new Date(user.createdAt).toLocaleDateString()}</Td>
                <Td>
                  <Menu>
                    <MenuButton
                      as={IconButton}
                      aria-label="Options"
                      icon={<HamburgerIcon />}
                      size="sm"
                      variant="ghost"
                    />
                    <MenuList>
                      <MenuItem
                        icon={<EditIcon />}
                        onClick={() => openEditModal(user)}
                      >
                        Edit
                      </MenuItem>
                        <MenuItem onClick={async () => {
                          try {
                            await api.post(`/admin/users/${user.id}/reset-password`);
                            toast({ title: 'Hotovo', description: 'Instrukce pro obnovení hesla byly odeslány.', status: 'success' });
                          } catch (e: any) {
                            const errorMsg = e?.response?.data?.message || e?.response?.data?.error || e?.message || 'Nelze odeslat reset hesla';
                            const errorDetails = e?.response?.data?.details;
                            toast({ 
                              title: 'Chyba při odesílání resetu hesla', 
                              description: errorDetails ? `${errorMsg}\n\n${errorDetails}` : errorMsg,
                              status: 'error',
                              duration: 10000,
                              isClosable: true,
                            });
                          }
                        }}>
                          Odeslat reset hesla
                        </MenuItem>
                      {user.role !== 'admin' && String(authUser?.id) !== String(user.id) && (
                        <MenuItem
                          icon={<DeleteIcon />}
                          color="red.500"
                          onClick={() => handleDelete(user.id)}
                        >
                          Delete
                        </MenuItem>
                      )}
                    </MenuList>
                  </Menu>
                </Td>
              </Tr>
            ))}
          </Tbody>
        </Table>
      </Box>

      {/* Add/Edit User Modal */}
      <Modal isOpen={isOpen} onClose={onClose} size="lg">
        <ModalOverlay />
        <ModalContent as="form" onSubmit={handleSubmit}>
          <ModalHeader>
            {selectedUser ? 'Edit User' : 'Add New User'}
          </ModalHeader>
          <ModalCloseButton />
          <ModalBody pb={6}>
            <VStack spacing={4}>
              <FormControl isRequired>
                <FormLabel>Full Name</FormLabel>
                <Input
                  name="name"
                  value={formData.name}
                  onChange={handleInputChange}
                  placeholder="Enter full name"
                />
              </FormControl>

              <FormControl isRequired>
                <FormLabel>Email</FormLabel>
                <Input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleInputChange}
                  placeholder="Enter email"
                />
              </FormControl>

              {!selectedUser && (
                <FormControl isRequired={!selectedUser}>
                  <FormLabel>Password</FormLabel>
                  <Input
                    type="password"
                    name="password"
                    value={formData.password}
                    onChange={handleInputChange}
                    placeholder="Enter password"
                    minLength={8}
                  />
                  <FormHelperText>
                    Password must be at least 8 characters long
                  </FormHelperText>
                </FormControl>
              )}

              {selectedUser && selectedUser.role === 'admin' && (
                <FormControl>
                  <FormLabel>Současné heslo (potvrzení)</FormLabel>
                  <Input
                    type="password"
                    name="currentPassword"
                    value={formData.currentPassword}
                    onChange={handleInputChange}
                    placeholder="Zadejte současné heslo administrátora"
                  />
                  <FormHelperText>Pro úpravu administrátorského účtu je nutné zadat současné heslo.</FormHelperText>
                </FormControl>
              )}

              <FormControl>
                <FormLabel>Role</FormLabel>
                <Select
                  name="role"
                  value={formData.role}
                  onChange={handleInputChange}
                >
                  <option value="editor" disabled={!!selectedUser && selectedUser.role === 'admin'}>Editor</option>
                  <option value="admin">Admin</option>
                </Select>
                {selectedUser?.role === 'admin' && (
                  <FormHelperText>Administrátorský účet nelze degradovat na editora přes tuto obrazovku.</FormHelperText>
                )}
              </FormControl>

              <FormControl display="flex" alignItems="center">
                <FormLabel mb="0" mr={2}>
                  Active
                </FormLabel>
                <Switch
                  name="isActive"
                  isChecked={formData.isActive}
                  onChange={handleInputChange}
                  colorScheme="blue"
                />
              </FormControl>
            </VStack>
          </ModalBody>

          <ModalFooter>
            <Button variant="ghost" mr={3} onClick={onClose}>
              Cancel
            </Button>
            <Button
              colorScheme="blue"
              type="submit"
              isLoading={isSubmitting}
              loadingText="Saving..."
            >
              {selectedUser ? 'Update' : 'Create'} User
            </Button>
          </ModalFooter>
        </ModalContent>
        </Modal>
      </Box>
    </AdminLayout>
  );
};

export default UsersAdminPage;
