import {useTranslations} from "next-intl";
import {Box, Chip, Divider, Stack} from "@mui/material";
import HeadphonesIcon from '@mui/icons-material/Headphones';
import LoadingHistory from "./LoadingHistory";
import HistoryHeader from "./HistoryHeader";
import ErrorOrEmpty from "./ErrorOrEmpty";
import useCallerHistory from "@/lib/callWidget/hooks/useCallerHistory";
import ListItemOfCalls from "./ListItemOfCalls";
import {useState} from "react";

const max_size = 10;
const CallHistory = ({tab}) => {
    const t = useTranslations();
    const {
        firstItemOfHistory,
        historyList,
        isLoadingHistoryList,
        errorHistoryList
    } = useCallerHistory(tab.id, tab.phone_number, max_size);
    const [showRestOfHistory, setShowRestOfHistory] = useState(false);

    return (
        <Stack sx={{
            height: "100%",
            overflow: "hidden"
        }}>
            <HistoryHeader tab={tab}/>
            <Stack sx={{height: "100%", overflow: "scroll"}}>
                {isLoadingHistoryList ? (
                    <LoadingHistory/>
                ) : errorHistoryList ? (
                    <ErrorOrEmpty isErrorOrEmpty="error"/>
                ) : !firstItemOfHistory ? (
                    <ErrorOrEmpty isErrorOrEmpty="empty"/>
                ) : (
                    <Box>
                        <ListItemOfCalls historyItem={firstItemOfHistory}/>
                        {historyList && (
                            <Divider>
                                <Chip
                                    icon={<HeadphonesIcon/>}
                                    onClick={() => setShowRestOfHistory(true)}
                                    label={t("show_more")}
                                    disabled={showRestOfHistory}
                                />
                            </Divider>
                        )}
                        {showRestOfHistory && (
                            <>
                                {historyList.map((historyItem, index) => (
                                    <>
                                        <ListItemOfCalls key={historyItem.id} historyItem={historyItem}/>
                                        <Divider/>
                                    </>
                                ))}
                            </>)
                        }
                    </Box>
                )}
            </Stack>
        </Stack>
    )
}

export default CallHistory
