import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import {
    Paper, Typography, TableContainer, Table, TableHead, 
    TableRow, TableCell, TableSortLabel, TableBody,
    TablePagination, Box, Button
} from "@mui/material";
import currencies from "./currencies.json";
import { SnackbarNotice, ConfirmationDialog } from "./functions";
import { 
    handleRequestSort, handleChangePage, handleChangeRowsPerPage 
} from "./functions";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";

class AppointmentApp extends Component {

    state = {
        headCells: [
            { id: "appointment_id", label: "ID", priority: 0 },
            { id: "appointment_date", label: "Appointment Date", priority: 5 },
            { id: "appointment_staff", label: "Staff", priority: 15 },
            { id: "appointment_service", label: "Service", priority: 20 },
            { id: "appointment_price", label: "Payment", priority: 25 },
            { id: "appointment_duration", label: "Duration", priority: 30 },
            { id: "appointment_created", label: "Created At", priority: 35 },
            { id: "appointment_status", label: "Status", priority: 40 },
        ],
        title: "Appointment(s)",
        currency: "USD",
        TableData: [],
        orderBy: "id",
        order: "desc",
        totalCount: 0,
        pageSize: 10,
        page: 0,
        timeFormat: "12-hour",
        snackbarOpen: false,
        snackbarMessage: "",
        snackbarType: "success",
        confirmationDialogOpen: false,
        confirmationLoading: false,
        AppointmentStatus: null,
    }

    componentDidMount() {
        dayjs.extend(utc);
        dayjs.extend(timezone);

        this.fetchAppointmentData();

        const title = window.wp.hooks.applyFilters("bookify_frontend_appointment_title", "Appointment(s)");
        this.setState({ 
            title: title,
        });

        const ZoomMeeting = window.ZoomMeeting;

        if ( ZoomMeeting ) {
            this.state.headCells.push(
                { id: "zoom_meeting", label: "Zoom Meeting", priority: 37 },
            );
        }
    }

    fetchAppointmentData = (page = 1, pageSized = 10, changePageSize = false) => {
        const { pageSize } = this.state;
        let perPageSized = pageSize;
        if ( changePageSize ) {
            perPageSized = pageSized;
        }
        fetch(`${wpbAptApp.root}bookify/frontend/v1/get-appointments?page=${page}&pageSize=${perPageSized}`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpbAptApp.nonce
            }
        })
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                TableData: data.data,
                totalCount: data.total,
                currency: data.currency,
                timeFormat: data.timeFormat,
            });
        })
        .catch(error => {
            console.error("Error:", error);
        })
    };

    handleCancelAppointment = ( event, appointmentId ) => {
        this.setState({ confirmationDialogOpen: true, AppointmentStatus: appointmentId });
    }

    confirmationAppointmentDelete = () => {
        const { AppointmentStatus } = this.state;
        this.setState({ confirmationLoading: true });

        const dataToSend = {};
        dataToSend.appointment_id = AppointmentStatus;

        fetch(`${wpbAptApp.root}bookify/frontend/v1/appointment-status`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpbAptApp.nonce
            },
            body: JSON.stringify(dataToSend)
        })
        .then(response => response.json())
        .then((response) => {
            if ( response.success ) {
                this.setState({ 
                    confirmationDialogOpen: false,
                    confirmationLoading: false,
                    AppointmentStatus: null,
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "success",
                });
                this.fetchAppointmentData();
            } else {
                this.setState({ 
                    confirmationDialogOpen: false,
                    confirmationLoading: false,
                    AppointmentStatus: null,
                    snackbarOpen: true,
                    snackbarMessage: response.message,
                    snackbarType: "error",
                });
            }
        })
        .catch(error => {
            console.error("Error deleting category:", error);
            this.setState({ confirmationLoading: false });
        })
    }

    convertSlotToTimezone = (slot, UserTimezone) => {
        const { timeFormat } = this.state;
        const timeFormated = timeFormat == "12-hour" ? "hh:mm A" : "HH:mm";
        const [start, end] = slot.split(" - ");

        const formatedStartTime = dayjs(`1970-01-01 ${start}`).format("HH:mm");
        const formatedEndTime = dayjs(`1970-01-01 ${end}`).format("HH:mm");

        const startTime = dayjs.tz(`1970-01-01 ${formatedStartTime}`, wpbAptApp.wpTimezone).tz(UserTimezone).format(timeFormated);
        const endTime = dayjs.tz(`1970-01-01 ${formatedEndTime}`, wpbAptApp.wpTimezone).tz(UserTimezone).format(timeFormated);

        return `${startTime} - ${endTime}`;
    };

    handleZoomJoinLink = (zoomLinks) => {
        window.open( zoomLinks.join_url, "_blank" );
    }

    render() {

        const { headCells, title, TableData, currency, orderBy, order, totalCount, pageSize, page, snackbarOpen, snackbarMessage, snackbarType, confirmationDialogOpen, confirmationLoading } = this.state;
        const matchedCurrency = Object.values(currencies).find(eachCurrency => eachCurrency.code === currency);

        return(
            <>
                <Paper sx={{ pt:"1em", boxShadow:"none", border:"1px solid #DDEEEE", borderRadius:"4px" }}>
                    <Typography sx={{ pl: "1rem", pb:"1rem" }} variant="h6" component="div">
                        {title}
                    </Typography>
                    <TableContainer>
                        <Table>
                            <TableHead>
                                <TableRow>
                                    {headCells.sort((a, b) => a.priority - b.priority).map((headCell) => (
                                        <TableCell
                                            key={headCell.id}
                                            align="left"
                                            sortDirection={orderBy === headCell.id ? order : false}
                                            sx={{borderBottom: "1px solid #CDE0E0"}}
                                        >
                                            <TableSortLabel
                                                active={orderBy === headCell.id}
                                                direction={orderBy === headCell.id ? order : "desc"}
                                                onClick={(event) => handleRequestSort(this.state, this.setState.bind(this), headCell.id)}
                                            >
                                                {headCell.label}
                                            </TableSortLabel>
                                        </TableCell>
                                    ))}
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {TableData.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={headCells.length} align="center" sx={{borderBottom: "1px solid #CDE0E0", height:"36px"}}>
                                            {__("No records to display", "bookify")}
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    TableData.map((row) => {
                                        return (
                                            <TableRow hover key={row.appointment_id} >
                                                {headCells.sort((a, b) => a.priority - b.priority).map((headCell) => (
                                                    <TableCell key={headCell.id} align="left" sx={{borderBottom: "1px solid #CDE0E0"}}>
                                                        {headCell.id === "appointment_date" ? (
                                                            <Typography 
                                                                sx={{
                                                                    display: "flex",
                                                                    flexDirection: "column",
                                                                    color:"#036666",
                                                                    fontSize:"0.875rem"
                                                                }}
                                                            >
                                                                {row[headCell.id]}
                                                            </Typography>
                                                        ) : headCell.id === "appointment_staff" ? (
                                                            <Box sx={{ display: "flex" }}>
                                                                <Typography 
                                                                    sx={{
                                                                        display: "flex",
                                                                        flexDirection: "column",
                                                                        color: "#036666",
                                                                        fontSize: "0.875rem"
                                                                    }}
                                                                >
                                                                    {row["appointment_staff_name"]}
                                                                    <Typography 
                                                                        variant="caption"
                                                                        sx={{
                                                                            color: "#18120F",
                                                                            fontSize: "0.875rem"
                                                                        }}
                                                                    >
                                                                        {row["appointment_staff_email"]}
                                                                    </Typography>
                                                                </Typography>
                                                            </Box>
                                                        ) : headCell.id === "appointment_service" ? (
                                                            <Typography 
                                                                sx={{
                                                                    display: "flex",
                                                                    flexDirection: "column",
                                                                    fontSize: "0.875rem"
                                                                }}
                                                            >
                                                                {row["service_name"] ? row["service_name"] : " - "}
                                                            </Typography>
                                                        ) : headCell.id === "appointment_price" ? (
                                                            <Box component={"span"}>
                                                                {matchedCurrency ? `${matchedCurrency.symbol_native} ${row[headCell.id]}` : row[headCell.id]}
                                                            </Box>
                                                        ) : headCell.id === "appointment_duration" ? (
                                                            <Box component={"span"} sx={{ whiteSpace: "nowrap" }}>
                                                                {(() => {
                                                                    const UserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
                                                                    return JSON.parse(row[headCell.id])
                                                                        .map(slot => this.convertSlotToTimezone(slot, UserTimezone))
                                                                        .join(" | ");
                                                                })()}
                                                            </Box>
                                                        ) : headCell.id === "zoom_meeting" ? (
                                                            row.zoom_links ? (
                                                                <Box sx={{ display: "flex", gap: "7px", flexDirection: "column", alignItems: "center" }}>
                                                                    <Button
                                                                        variant="contained"
                                                                        onClick={() => this.handleZoomJoinLink(row.zoom_links)}
                                                                        sx={{
                                                                            backgroundColor: "#FF6C22",
                                                                            width: "8rem",
                                                                            fontSize: "13px",
                                                                            textTransform: "capitalize",
                                                                            padding: "3px",
                                                                            "&:hover": {
                                                                                backgroundColor: "#EB5E17",
                                                                            },
                                                                        }}
                                                                    >
                                                                        {__("Join Now", "bookify")}
                                                                    </Button>
                                                                </Box>
                                                            ) : "-"
                                                        ) : headCell.id === "appointment_status" ? (
                                                            row.appointment_status === "Pending" ? (
                                                                <Button variant="contained" onClick={(event) => this.handleCancelAppointment(event, row.appointment_id)}
                                                                    sx={{
                                                                        textTransform: "capitalize",
                                                                        "&:hover": {
                                                                            color:"#FFFFFF",
                                                                        }
                                                                    }}
                                                                >
                                                                    {__("Cancel Appointment", "bookify")}
                                                                </Button>
                                                            ) : row.appointment_status === "Confirmed" ? (
                                                                <Box sx={{borderRadius:"14px", padding:"4px 10px", backgroundColor:"#E7F3D7", color:"#545E48", textAlign:"center", maxWidth:"fit-content"}}>
                                                                    {row.appointment_status}
                                                                </Box>
                                                            ) : row.appointment_status === "Completed" ? (
                                                                <Box sx={{borderRadius:"14px", padding:"4px 10px", backgroundColor:"#E3EEFF", color:"#1C3E74", textAlign:"center", maxWidth:"fit-content"}}>
                                                                    {row.appointment_status}
                                                                </Box>
                                                            ) : row.appointment_status === "Delayed" ? (
                                                                <Box sx={{borderRadius:"14px", padding:"4px 10px", backgroundColor:"#F3E4FF", color:"#54485E", textAlign:"center", maxWidth:"fit-content"}}>
                                                                    {row.appointment_status}
                                                                </Box>
                                                            ) : row.appointment_status === "On Hold" ? (
                                                                <Button variant="contained" onClick={(event) => this.handleCancelAppointment(event, row.appointment_id)}
                                                                    sx={{
                                                                        textTransform: "capitalize",
                                                                        "&:hover": {
                                                                            color:"#FFFFFF",
                                                                        }
                                                                    }}
                                                                >
                                                                    {__("Cancel Appointment", "bookify")}
                                                                </Button>
                                                            ) : (
                                                                <Box sx={{borderRadius:"14px", padding:"4px 10px", backgroundColor:"#FFE9E3", color:"#74311C", textAlign:"center", maxWidth:"fit-content"}}>
                                                                    {row.appointment_status}
                                                                </Box>
                                                            )
                                                        ) : (
                                                            row[headCell.id]
                                                        )}
                                                    </TableCell>
                                                ))}
                                            </TableRow>
                                        );
                                    })
                                )}
                            </TableBody>
                        </Table>
                    </TableContainer>
                    <TablePagination
                        component="div"
                        count={totalCount}
                        rowsPerPage={pageSize}
                        page={page}
                        onPageChange={(event, newPage) => handleChangePage(this.state, this.setState.bind(this), this.fetchAppointmentData, newPage)}
                        onRowsPerPageChange={(event) => handleChangeRowsPerPage(this.state, this.setState.bind(this), this.fetchAppointmentData, event)}
                    />
                </Paper>
                <SnackbarNotice
                    state={this.state}
                    setState={this.setState.bind(this)}
                    open={snackbarOpen}
                    message={snackbarMessage}
                    type={snackbarType}
                />
                <ConfirmationDialog
                    open={confirmationDialogOpen}
                    onClose={() => this.setState({ confirmationDialogOpen: false, AppointmentStatus: null })}
                    onConfirm={this.confirmationAppointmentDelete}
                    loading={confirmationLoading}
                />
            </>
        )
    }
}

export default AppointmentApp;