import { __ } from "@wordpress/i18n";
import { Snackbar, Alert, IconButton, Dialog, DialogActions,
    DialogContent, DialogContentText, DialogTitle, Button, Box,
    Divider,
    Typography
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import LoadingButton from "@mui/lab/LoadingButton";
import { ReactComponent as WarningIcon } from "../admin/assets/warning-icon.svg";
import ProModalBG from "../admin/assets/pro-modal-bg.svg";
import BookifyLogoWhite from "../admin/assets/bookify-logo-white.png";

export function handleRequestSort(state, setState, property) {
    const { orderBy, order, TableData } = state;
    const isAsc = orderBy === property && order === "asc";

    const sortedData = [...TableData].sort((a, b) => {
        let valueA = a[property];
        let valueB = b[property];

        if (typeof valueA === "string" && !isNaN(valueA)) {
            valueA = parseFloat(valueA);
        }
        if (typeof valueB === "string" && !isNaN(valueB)) {
            valueB = parseFloat(valueB);
        }

        if (typeof valueA === "number" && typeof valueB === "number") {
            return isAsc ? valueA - valueB : valueB - valueA;
        }

        if (typeof valueA === "string" && typeof valueB === "string") {
            return isAsc ? valueA.localeCompare(valueB) : valueB.localeCompare(valueA);
        }

        return 0;
    });

    setState({
        ...state,
        TableData: sortedData,
        order: isAsc ? "desc" : "asc",
        orderBy: property,
    });
}

export function handleSelectAllClick(state, setState, event) {
    const { data } = state;
    if (event.target.checked) {
        const newSelected = data.map((n) => n.id);
        setState({ ...state, selected: newSelected });
        return;
    }
    setState({ ...state, selected: [] });
}

export function handleClick(state, setState, event, id) {
    const { selected } = state;
    const selectedIndex = selected.indexOf(id);
    let newSelected = [];

    if (selectedIndex === -1) {
        newSelected = [...selected, id];
    } else if (selectedIndex === 0) {
        newSelected = selected.slice(1);
    } else if (selectedIndex === selected.length - 1) {
        newSelected = selected.slice(0, -1);
    } else if (selectedIndex > 0) {
        newSelected = [
            ...selected.slice(0, selectedIndex),
            ...selected.slice(selectedIndex + 1),
        ];
    }

    setState({ ...state, selected: newSelected });
};

function convertToCSV(state) {
    const { headCells, TableData } = state;
    const csvRows = [];

    const filteredHeadCells = headCells.filter(cell => cell.id !== "action");

    const headers = filteredHeadCells.map(cell => cell.label);
    csvRows.push(headers.join(","));

    for (const row of TableData) {
        const values = filteredHeadCells.map(cell => {
            if (cell.id === "appointment_service") {
                return row["service_name"];
            }
            if (cell.id === "appointment_duration") {
                return JSON.parse(row["appointment_duration"]).join(" | ");
            }
            return row[cell.id]}
        );
        csvRows.push(values.join(","));
    }

    return csvRows.join("\n");
};

export function downloadCSV(state, fileName) {
    const csvData = convertToCSV(state);
    const blob = new Blob([csvData], { type: "text/csv" });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.setAttribute("hidden", "");
    a.setAttribute("href", url);
    a.setAttribute("download", `${fileName}.csv`);
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
};

export function openDialog(state, setState, dialogHandle, editID = null) {
    setState({ ...state, [dialogHandle]: true, editDialogHandle: editID });
}

export function closeDialog(state, setState, dialogHandle) {
    setState({ ...state, [dialogHandle]: false});
};

export function handleChangePage(state, setState, fetchData, newPage) {
    setState({ ...state, page: newPage });
    fetchData(newPage + 1, state.pageSize);
}

export function handleChangeRowsPerPage(state, setState, fetchData, event) {
    const newPageSize = parseInt(event.target.value, 10);
    setState({ ...state, pageSize: newPageSize, page: 0 });
    fetchData(1, newPageSize, true);
}

export const SnackbarNotice = ({ state, setState, open, message, type }) => {
    const handleClose = (event, reason) => {
        if (reason === "clickaway") {
            return;
        }
        setState({ ...state, snackbarOpen: false });
    };

    return (
        <Snackbar
            anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
            open={open}
            autoHideDuration={4000}
            onClose={handleClose}
            message={message}
            action={
                <IconButton
                    size="small"
                    aria-label="close"
                    color="inherit"
                    onClick={handleClose}
                >
                    <CloseIcon fontSize="small" />
                </IconButton>
            }
        >
            <Alert
                onClose={handleClose}
                severity={type}
                variant="filled"
                sx={{ width: "100%" }}
            >
                {message}
            </Alert>
        </Snackbar>
    );
};

function handleBookifyProLink(onClose) {
    window.open("https://wpbookify.com/pricing/", "_blank");
    if (typeof onClose === "function") {
        onClose();
    }
}

export const GetProModal = ({ open, onClose }) => {
    return (
        <Dialog open={open} onClose={onClose} maxWidth={"sm"}>
            <Box sx={{background: "linear-gradient(180deg, #036666 0%, #042626 100%)"}}>
                <IconButton onClick={onClose} sx={{position:"absolute", right:8, top:8, color:"#D5F1F1"}}>
                    <CloseIcon sx={{fontSize:"17px"}} />
                </IconButton>
                <Box sx={{backgroundImage:`url(${ProModalBG})`, backgroundRepeat:"no-repeat", backgroundPosition:"bottom", padding:"65px 100px", textAlign:"center", display:"flex", flexDirection:"column", alignItems:"center", gap:"45px"}}>
                    <img src={BookifyLogoWhite} alt="Bookify Logo" style={{height:50}} />
                    <Typography sx={{textAlign:"center", fontSize:"20px", fontWeight:500, color:"#D5F1F1"}}>
                        {__("Interested in unlocking this feature?", "bookify")}
                    </Typography>
                    <Button onClick={() => handleBookifyProLink(onClose)} 
                        sx={{
                            borderColor: "none",
                            backgroundColor: "#FFC759",
                            color: "#3F3116",
                            textTransform: "capitalize",
                            width: "13em",
                            height: "45px",
                            fontSize: "14px",
                            fontWeight: 600,
                            "&:hover": {
                                backgroundColor: "#FFC759",
                            },
                        }}
                    >
                        {__("Get Bookify Pro Today", "bookify")}
                    </Button>
                </Box>
            </Box>
        </Dialog>
    )
}

export const ConfirmationDialog = ({ open, onClose, onConfirm, loading }) => {
    return (
        <Dialog open={open} onClose={onClose}>    
            <Box component={"div"} sx={{textAlign:"center", padding:"30px"}}>
                <WarningIcon />
                <DialogTitle sx={{textAlign:"center", fontSize:"16px", fontWeight:600, color:"#042626"}}>{__("Are you sure?", "bookify")}</DialogTitle>
                <DialogContent>
                    <DialogContentText sx={{fontSize:"14px", fontWeight:400, color:"#587373"}}>{__("You won\’t be able to see it again.", "bookify")}</DialogContentText>
                </DialogContent>
            </Box>

            <Divider sx={{borderColor:"#DDEEEE"}} />

            <DialogActions sx={{p:"10px"}}>
                <Button onClick={onClose} 
                    sx={{
                        borderColor: "none",
                        color: "#036666",
                        textTransform: "capitalize",
                        width: "6em",
                        height: "40px",
                        "&:hover": {
                            backgroundColor: "#DDEEEE",
                        },
                    }}
                >
                    {__("Cancel", "bookify")}
                </Button>
                <LoadingButton onClick={onConfirm} autoFocus loading={loading} 
                    sx={{
                        borderColor: "none",
                        backgroundColor: "#036666",
                        color: "#FFFFFF",
                        textTransform: "capitalize",
                        width: "6em",
                        height: "40px",
                        "&:hover": {
                            backgroundColor: "#025151",
                            color: "#FFFFFF"
                        },
                        "&.Mui-disabled": {
                            color: "#FFFFFF",
                            opacity: 0.7,
                        },
                        "& .MuiLoadingButton-loadingIndicator": {
                            color: "#FFFFFF",
                        }
                    }}
                >
                    {__("Delete", "bookify")}
                </LoadingButton>
            </DialogActions>
        </Dialog>
    );
};

export const Placeholders = [
    { primary: "{appointment_id}", secondary: "Appointment number" },
    { primary: "{appointment_date}", secondary: "Date of booked appointment" },
    { primary: "{appointment_slot}", secondary: "Slot of booked appointment" },
    { primary: "{appointment_duration}", secondary: "Duration of booked appointment" },
    { primary: "{appointment_timezone}", secondary: "Timezone of booked appointment" },
    { primary: "{appointment_service_category}", secondary: "Service\"s category name of booked appointment" },
    { primary: "{appointment_service}", secondary: "Service name of booked appointment" },
    { primary: "{appointment_price}", secondary: "Total price of booked appointment" },
    { primary: "{appointment_status}", secondary: "Status of booked appointment" },
    { primary: "{appointment_note}", secondary: "Appointment note" },
    { primary: "{service_price}", secondary: "Price of the service" },
    { primary: "{service_note}", secondary: "Service note" },
    { primary: "{customer_name}", secondary: "Customer name" },
    { primary: "{customer_phone}", secondary: "Customer phone number" },
    { primary: "{customer_email}", secondary: "Customer email" },
    { primary: "{customer_note}", secondary: "Customer note" },
    { primary: "{staff_name}", secondary: "Staff name" },
    { primary: "{staff_phone}", secondary: "Staff phone" },
    { primary: "{staff_email}", secondary: "Staff email" },
    { primary: "{staff_profession}", secondary: "Staff profession" },
    { primary: "{staff_note}", secondary: "Staff note" },
    { primary: "{company_name}", secondary: "Company name" },
    { primary: "{company_address}", secondary: "Company address" },
    { primary: "{company_phone}", secondary: "Company phone" },
    { primary: "{company_website}", secondary: "company website address" },
    { primary: "{company_logo}", secondary: "Company logo" },
];
