import { Dialog } from "../Dialog/Dialog";
import Lottie from "lottie-react";
import animationData from './lottie.json';
import { Box, Flex, Skeleton, Text } from "@mantine/core";
import { useDialogsList } from "@/app/providers/DialogListProvider/useDialogsList";
import { GroupDialog } from "../GroupDialog/GroupDialog";
import { AnimatePresence, motion } from "framer-motion";

interface DialogsListProps {
	mode: 'all' | 'requests';
	onSelectDialog: (publicKey: string) => void;
}

export function DialogsList(props : DialogsListProps) {
	const {dialogs, loadingDialogs} = useDialogsList();
	const filteredDialogs = dialogs.filter(v => (v.is_request == (props.mode == 'requests')));

	return (
		<>
			{loadingDialogs === 0 && dialogs.filter(v => (v.is_request == (props.mode == 'requests'))).length <= 0 && (
				<Flex align={'center'} mt={100} direction={'column'} justify={'center'}>
					<Lottie style={{
						width: 90,
						height: 90
					}} loop={true} animationData={animationData}></Lottie>
					<Text mt={'sm'} c={'dimmed'} fz={13}>
						Write to someone
					</Text>
				</Flex>
			)}
			{loadingDialogs > 0 && (
				<>
					{Array.from({ length: loadingDialogs }).map((_, index) => (
						<Box w={'100%'} h={74} key={index}>
							<Skeleton height={74} radius={0} mb={index == loadingDialogs - 1 ? 0 : 1} />
						</Box>
					))}				
				</>
			)}
            <motion.div style={{display: 'flex', flexDirection: 'column'}}>
                <AnimatePresence mode="popLayout">
                    {loadingDialogs === 0 && filteredDialogs.map((dialog) => (
                        <motion.div
                            key={dialog.dialog_id}
                            layout
                            initial={false}
                            transition={{ duration: 0.1, ease: 'easeInOut' }}
                        >
                            {dialog.dialog_id.startsWith('#group:') ? (
                                <GroupDialog
                                    onClickDialog={props.onSelectDialog}
                                    {...dialog}
                                />
                            ) : (
                                <Dialog
                                    onClickDialog={props.onSelectDialog}
                                    {...dialog}
                                />
                            )}
                        </motion.div>
                    ))}
                </AnimatePresence>
            </motion.div>
		</>
	);
}