import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
  Button,
  VStack,
  Text,
  Divider,
  HStack,
  Badge,
  useClipboard,
  useToast,
  Box,
  Input,
  FormControl,
  FormLabel,
  useDisclosure,
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverHeader,
  PopoverBody,
  PopoverArrow,
  PopoverCloseButton,
} from '@chakra-ui/react';
import { EmailIcon, CopyIcon, CheckIcon, DeleteIcon, ArrowForwardIcon } from '@chakra-ui/icons';
import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { forwardMessage } from '../../services/admin/contactMessages';
import { format } from 'date-fns';
import { cs } from 'date-fns/locale';

interface MessageDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  message: {
    id: string;
    name: string;
    email: string;
    subject?: string;
    message: string;
    source?: string;
    ipAddress?: string;
    userAgent?: string;
    isRead: boolean;
    createdAt: string;
  };
  onDelete: () => void;
  onMarkAsRead: () => void;
}

export default function MessageDetailModal({
  isOpen,
  onClose,
  message,
  onDelete,
  onMarkAsRead,
}: MessageDetailModalProps) {
  const toast = useToast();
  const queryClient = useQueryClient();
  const { hasCopied, onCopy } = useClipboard(message.email);
  const { isOpen: isPopoverOpen, onOpen: onPopoverOpen, onClose: onPopoverClose } = useDisclosure();
  const [forwardEmail, setForwardEmail] = useState('');

  const formatDate = (dateString: string) => {
    return format(new Date(dateString), 'd. M. yyyy HH:mm', { locale: cs });
  };

  const handleCopyEmail = () => {
    onCopy();
    toast({
      title: 'E-mail zkopírován do schránky',
      status: 'success',
      duration: 2000,
      isClosable: true,
    });
  };

  const forwardMutation = useMutation({
    mutationFn: (toEmail: string) => forwardMessage(message.id, toEmail),
    onSuccess: () => {
      toast({
        title: 'Zpráva přeposílána',
        description: `Zpráva bude odeslána na ${forwardEmail}`,
        status: 'success',
        duration: 3000,
        isClosable: true,
      });
      setForwardEmail('');
      onPopoverClose();
    },
    onError: () => {
      toast({
        title: 'Chyba',
        description: 'Nepodařilo se přeposlat zprávu',
        status: 'error',
        duration: 3000,
        isClosable: true,
      });
    },
  });

  const handleForward = () => {
    if (!forwardEmail || !forwardEmail.includes('@')) {
      toast({
        title: 'Chyba',
        description: 'Zadejte platnou e-mailovou adresu',
        status: 'error',
        duration: 3000,
      });
      return;
    }
    forwardMutation.mutate(forwardEmail);
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="xl">
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>
          <Box>
            <Text fontSize="lg" fontWeight="bold">
              {message.subject || 'Bez předmětu'}
            </Text>
            <HStack mt={1} fontSize="sm" color="gray.500">
              <Text>{formatDate(message.createdAt)}</Text>
              {!message.isRead && (
                <Badge colorScheme="blue">
                  Nová zpráva
                </Badge>
              )}
              {message.source && (
                <Badge colorScheme={message.source === 'sponsor' ? 'purple' : 'gray'}>
                  {message.source === 'sponsor' ? 'Sponzor' : 'Kontakt'}
                </Badge>
              )}
            </HStack>
          </Box>
        </ModalHeader>
        <ModalCloseButton />
        <ModalBody>
          <VStack align="stretch" spacing={4}>
            <Box>
              <Text fontWeight="bold" mb={1}>
                Od:
              </Text>
              <HStack>
                <Text>{message.name}</Text>
                <HStack
                  as="button"
                  onClick={handleCopyEmail}
                  color="blue.500"
                  _hover={{ textDecoration: 'underline' }}
                  spacing={1}
                >
                  <Text>&lt;{message.email}&gt;</Text>
                  {hasCopied ? (
                    <CheckIcon boxSize={3} />
                  ) : (
                    <CopyIcon boxSize={3} />
                  )}
                </HStack>
              </HStack>
            </Box>

            <Divider />

            <Box>
              <Text fontWeight="bold" mb={2}>
                Zpráva:
              </Text>
              <Text whiteSpace="pre-wrap" p={3} bg="gray.50" borderRadius="md">
                {message.message}
              </Text>
            </Box>

            {(message.ipAddress || message.userAgent) && (
              <Box mt={4} fontSize="sm" color="gray.500">
                <Text fontWeight="bold" mb={1}>
                  Technické informace:
                </Text>
                {message.ipAddress && (
                  <Text>
                    <Text as="span" fontWeight="medium">IP adresa:</Text>{' '}
                    {message.ipAddress}
                  </Text>
                )}
                {message.userAgent && (
                  <Text mt={1} isTruncated title={message.userAgent}>
                    <Text as="span" fontWeight="medium">Prohlížeč:</Text>{' '}
                    {message.userAgent.length > 50
                      ? `${message.userAgent.substring(0, 47)}...`
                      : message.userAgent}
                  </Text>
                )}
              </Box>
            )}
          </VStack>
        </ModalBody>

        <ModalFooter>
          <HStack spacing={2} flexWrap="wrap" justify="flex-end" w="full">
            <Button
              variant="outline"
              colorScheme="red"
              leftIcon={<DeleteIcon />}
              onClick={onDelete}
              size={{ base: "sm", md: "md" }}
            >
              Smazat
            </Button>
            
            <Popover isOpen={isPopoverOpen} onClose={onPopoverClose}>
              <PopoverTrigger>
                <Button
                  colorScheme="teal"
                  leftIcon={<ArrowForwardIcon />}
                  onClick={onPopoverOpen}
                  size={{ base: "sm", md: "md" }}
                >
                  Přeposlat
                </Button>
              </PopoverTrigger>
              <PopoverContent>
                <PopoverArrow />
                <PopoverCloseButton />
                <PopoverHeader>Přeposlat zprávu</PopoverHeader>
                <PopoverBody>
                  <VStack spacing={3}>
                    <FormControl>
                      <FormLabel fontSize="sm">E-mailová adresa</FormLabel>
                      <Input
                        placeholder="prijemce@email.cz"
                        value={forwardEmail}
                        onChange={(e) => setForwardEmail(e.target.value)}
                        type="email"
                        size="sm"
                      />
                    </FormControl>
                    <Button
                      size="sm"
                      colorScheme="teal"
                      width="full"
                      onClick={handleForward}
                      isLoading={forwardMutation.isLoading}
                    >
                      Odeslat
                    </Button>
                  </VStack>
                </PopoverBody>
              </PopoverContent>
            </Popover>
            
            {!message.isRead && (
              <Button
                colorScheme="blue"
                leftIcon={<EmailIcon />}
                onClick={onMarkAsRead}
                size={{ base: "sm", md: "md" }}
              >
                Označit jako přečtené
              </Button>
            )}
            <Button variant="ghost" onClick={onClose} size={{ base: "sm", md: "md" }}>
              Zavřít
            </Button>
          </HStack>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
}
