import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import {
    Stack, Typography, Box, FormControl, TextField,
    InputAdornment, Button
} from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import AddIcon from "@mui/icons-material/Add";
import { 
    downloadCSV, openDialog, closeDialog
} from "../../functions";
import AppointmentTable from "./AppointmentTable";
import AddAppointment from "./AddAppointment";
import BookifyLogo from "../../assets/bookify-logo.png";
import { ReactComponent as CrownIcon } from "../../assets/crown.svg";
import { ReactComponent as CsvIcon } from "../../assets/csv.svg";

class Appointments extends Component {
    state = {
        headCells: [
            { id: "appointment_id", label: "ID", priority: 0 },
            { id: "appointment_date", label: "Appointment Date", priority: 5 },
            { id: "appointment_customer", label: "Customer", priority: 10 },
            { 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 },
            { id: "action", label: "Action", priority: 45 },
        ],
        allAppointmentData: [],
        TableData: [],
        selected: [],
        searchText: "",
        totalCount: 0,
        page: 0,
        pageSize: 10,
        order: "desc",
        orderBy: "id",
        currency: "USD",
        locations: [],
        services: [],
        customers: [],
        DefaultAppointmentStatus: "",
        dateFormat: "",
        timeFormat: "",
        priorToggle: "Disable",
        priorTime: "3",
        isStaff: false,
        dataLoading: true,
        theme: createTheme({
            typography: {
                h2: {
                    fontSize: "2em",
                    textTransform: "capitalize",
                    color: "#587373",
                    marginLeft: "10px"
                },
            },
            components: {
                MuiButton: {
                    variants: [
                        {
                            props: { variant: "wpbkGetPro" },
                            style: {
                                textTransform: "capitalize",
                                backgroundColor: "#FFDD9A",
                                boxShadow: "none",
                                color: "#735928",
                                padding: "10px 20px",
                                fontWeight: 600,
                                "&:hover": {
                                    backgroundColor: "#f5cd7d",
                                    boxShadow: "none",
                                },
                            },
                        },
                        {
                            props: { variant: "wpbkThemeBtn" },
                            style: {
                                borderColor: "none",
                                backgroundColor: "#036666",
                                color: "#FFFFFF",
                                textTransform: "capitalize",
                                width: "13em",
                                height: "100%",
                                "&:hover": {
                                    backgroundColor: "#025151",
                                    color: "#FFFFFF"
                                },
                                "&.Mui-disabled": {
                                    color: "#FFFFFF",
                                    opacity: 0.7,
                                }
                            },
                        },
                        {
                            props: { variant: "wpbkThemeCSVBtn" },
                            style: {
                                border: "1px solid #BFD4D4",
                                color: "#042626",
                                textTransform: "capitalize",
                                height: "100%",
                                width: "12em",
                                "&.Mui-disabled": {
                                    color: "#FFFFFF",
                                    opacity: 0.7,
                                }
                            },
                        },
                    ],
                },
                MuiStack: {
                    styleOverrides: {
                        root: {
                            backgroundColor: "#FFFFFF",
                            border: "1px solid #DDEEEE",
                            borderRadius: "4px",
                        },
                    },
                },
            },
        }),
    };

    componentDidMount() {

        this.fetchAppointmentData();

        const title = window.wp.hooks.applyFilters("bookify_appointment_title", "Appointments");
        this.setState({ title });
    }

    fetchAppointmentData = (page = 1, pageSized = 10, changePageSize = false) => {
        const { searchText, pageSize } = this.state;
        let perPageSized = pageSize ;
        if ( changePageSize ) {
            perPageSized = pageSized;
        }
        this.setState({ dataLoading: true });

        const searchQuery = searchText ? `&search=${encodeURIComponent(searchText)}` : "";
        fetch(`${wpbAdmin.root}bookify/v1/appointments?page=${page}&pageSize=${perPageSized}${searchQuery}`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpApiSettings.nonce
            }
        })
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                allAppointmentData: data.data,
                TableData: data.data,
                totalCount: data.total,
                locations: data.locations,
                services: data.services,
                customers: data.customers,
                currency: data.currency,
                DefaultAppointmentStatus: data.default_status,
                dateFormat: data.dateFormat,
                timeFormat: data.timeFormat,
                priorToggle: data.priorToggle,
                priorTime: data.priorTime,
                isStaff: data.is_staff
            });
        })
        .catch(error => {
            console.error("Error:", error);
        })
        .finally(() => {
            this.setState({ dataLoading: false });
        });
    };

    handleSearchData = (event) => {
        const searchText = event.target.value.toLowerCase();
        const { allAppointmentData } = this.state;
    
        let filteredData;
    
        if (searchText == "") {
            filteredData = allAppointmentData;
        } else {
            filteredData = allAppointmentData.filter(appointment => {
                return (
                    appointment.appointment_date.toLowerCase().includes(searchText) ||
                    appointment.appointment_customer_name.toLowerCase().includes(searchText) ||
                    appointment.appointment_customer_email.toLowerCase().includes(searchText) ||
                    appointment.appointment_staff_name.toLowerCase().includes(searchText) ||
                    appointment.appointment_staff_email.toLowerCase().includes(searchText) ||
                    appointment.service_name.toLowerCase().includes(searchText) ||
                    appointment.appointment_price.toLowerCase().includes(searchText) ||
                    appointment.appointment_duration.toLowerCase().includes(searchText) ||
                    appointment.appointment_created.toLowerCase().includes(searchText) ||
                    appointment.appointment_status.toLowerCase().includes(searchText)
                );
            });
        }
        
        this.setState({ 
            searchText: event.target.value, 
            TableData: filteredData 
        });
    };

    handleProVerion = () => {
        window.open("https://wpbookify.com/pricing/", "_blank");
    }

    render() {

        const { headCells, TableData, totalCount, title, theme, order, orderBy, pageSize, page, currency, locations, services, customers, DefaultAppointmentStatus, dateFormat, timeFormat, priorToggle, priorTime, isStaff, dataLoading } = this.state;

        const ProLocation = window.ProLocation;
      
        return (
            <ThemeProvider theme={theme}>
                <Stack spacing={2} mb={"2em"} p={"1.5em 2em"} direction={"row"} alignItems={"center"} justifyContent={"space-between"}>
                    <Box sx={{display:"flex", direction:"row", alignItems:"flex-end"}}>
                        <img src={BookifyLogo} alt="Bookify Logo" style={{height:40}} />
                        <Typography variant={"h2"}>{title}</Typography>
                    </Box>
                    { ! ProLocation && 
                        <Box>
                            <Button variant="wpbkGetPro" startIcon={<CrownIcon />} onClick={this.handleProVerion}>
                                {__("Get Pro Version", "bookify")}
                            </Button>
                        </Box>
                    }
                </Stack>

                <Box component="section">
                    <Box Component="div" sx={{display:"flex", justifyContent:"space-between", m:"2em", p:"15px", backgroundColor:"#FFFFFF", border:"1px solid #DDEEEE", borderRadius:"4px", gap:"20px"}}>
                        <Box Component="div">
                            <FormControl sx={{width:"40em"}}>
                                <TextField
                                    variant="outlined"
                                    placeholder="Search appointments"
                                    sx={{
                                        height: "45px",
                                        border: "1px solid #BFD4D4",
                                        borderRadius: "4px",
                                        color: "#789595",
                                        justifyContent: "center",
                                        "& fieldset": {
                                            border: "none",
                                        }
                                    }}
                                    onChange={this.handleSearchData}
                                    InputProps={{
                                        sx: {
                                            paddingRight: "5px",
                                            "& input": {
                                                padding: "11px",
                                                "::placeholder": {
                                                    color: "#789595",
                                                    opacity: 1
                                                },
                                            },
                                        },
                                        endAdornment: (
                                            <InputAdornment position="start" sx={{color: "#042626"}}>
                                                <SearchIcon />
                                            </InputAdornment>
                                        ),
                                    }}
                                />
                            </FormControl>
                        </Box>
                        { ! isStaff && (
                            <Box Component="div" sx={{display:"flex", justifyContent:"flex-start", gap:"20px"}}>
                                <Box Component="div">
                                    <Button variant="wpbkThemeCSVBtn" startIcon={<CsvIcon />} onClick={() => downloadCSV(this.state, "Bookify Appointments")} >
                                        {__("Export to CSV", "bookify")}
                                    </Button>
                                </Box>
                                <Box Component="div">
                                    <Button variant="wpbkThemeBtn" startIcon={<AddIcon />} onClick={() => openDialog(this.state, this.setState.bind(this), "AddAppointmentDialog")} >
                                        {__("Add Appointment", "bookify")}
                                    </Button>
                                    <AddAppointment
                                        open={this.state.AddAppointmentDialog}
                                        onClose={() => closeDialog(this.state, this.setState.bind(this), "AddAppointmentDialog")}
                                        fetchAppointmentData={this.fetchAppointmentData}
                                        DefaultAppointmentStatus={DefaultAppointmentStatus}
                                        locations={locations}
                                        services={services}
                                        customers={customers}
                                        currency={currency}
                                        dateFormat={dateFormat}
                                        priorToggle={priorToggle}
                                        priorTime={priorTime}
                                    />
                                </Box>
                            </Box>
                        )}
                    </Box>

                    <Box component="div" sx={{ m:"2em"}}>
                        <AppointmentTable
                            state={this.state}
                            setState={this.setState.bind(this)}
                            headCells={headCells}
                            fetchAppointmentData={this.fetchAppointmentData}
                            TableData={TableData}
                            totalCount={totalCount}
                            pageSize={pageSize}
                            page={page}
                            orderBy={orderBy}
                            order={order}
                            currency={currency}
                            locations={locations}
                            services={services}
                            customers={customers}
                            priorToggle={priorToggle}
                            priorTime={priorTime}
                            dateFormat={dateFormat}
                            timeFormat={timeFormat}
                            isStaff={isStaff}
                            dataLoading={dataLoading}
                        />
                    </Box>
                </Box>
            </ThemeProvider>
        );
    }
}

export default Appointments;
