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 AddCustomer from "./AddCustomer";
import CustomerTable from "./CustomerTable";
import { 
    downloadCSV, openDialog, closeDialog
} from "../../functions";
import BookifyLogo from "../../assets/bookify-logo.png";
import { ReactComponent as CrownIcon } from "../../assets/crown.svg";
import { ReactComponent as CsvIcon } from "../../assets/csv.svg";

class Customers extends Component {
    state = {
        headCells: [
            { id: "id", label: "ID", priority: 0 },
            { id: "customer_name", label: "Customer Name", priority: 5 },
            { id: "customer_phone", label: "Phone", priority: 10 },
            { id: "customer_email", label: "Email", priority: 15 },
            { id: "total_appointments", label: "Total Appointments", priority: 20 },
            { id: "last_appointment", label: "Last Appointment", priority: 25 },
            { id: "action", label: "Action", priority: 30 },
        ],
        allCustomerData: [],
        TableData: [],
        searchText: "",
        totalCount: 0,
        page: 0,
        pageSize: 10,
        order: "desc",
        orderBy: "id",
        editDialogHandle: null,
        dateFormat: "",
        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() {
        const title = window.wp.hooks.applyFilters("bookify_customer_title", "Customers");
        this.setState({ title });

        this.fetchCustomerData();
    }

    fetchCustomerData = (page = 1, pageSized = 10, changePageSize = false) => {
        const { searchText, pageSize } = this.state;
        let perPageSized = pageSize;
        if ( changePageSize ) {
            perPageSized = pageSized;
        }
        const searchQuery = searchText ? `&search=${encodeURIComponent(searchText)}` : "";
        this.setState({ dataLoading: true });

        fetch(`${wpbAdmin.root}bookify/v1/customers?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({
                allCustomerData: data.data,
                TableData: data.data,
                totalCount: data.total,
                dateFormat: data.dateFormat
            });
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
        })
        .finally(() => {
            this.setState({ dataLoading: false });
        });
    };

    fetchCustomerById = (customerId) => {
        return this.state.TableData.find(customer => customer.id === customerId);
    };

    handleSearchData = (event) => {
        const searchText = event.target.value.toLowerCase();
        const { allCustomerData } = this.state;
    
        let filteredData;
    
        if (searchText == "") {
            filteredData = allCustomerData;
        } else {
            filteredData = allCustomerData.filter(customer => {
                return (
                    customer.customer_name.toLowerCase().includes(searchText) ||
                    customer.customer_email.toLowerCase().includes(searchText) ||
                    customer.customer_phone.toLowerCase().includes(searchText) ||
                    customer.total_appointments.toString().toLowerCase().includes(searchText) ||
                    customer.last_appointment.toLowerCase().includes(searchText)
                );
            });
        }
        
        this.setState({ 
            searchText: event.target.value, 
            TableData: filteredData 
        });
    };

    handleProVerion = () => {
        window.open("https://wpbookify.com/pricing/", "_blank");
    }

    render() {
        const { headCells, TableData, theme, title, orderBy, order, totalCount, pageSize, page, editDialogHandle, dateFormat, 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"}}>
                        <Box Component="div">
                            <FormControl sx={{width:"40em"}}>
                                <TextField
                                    variant="outlined"
                                    placeholder="Search customers"
                                    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>
                        <Box Component="div" sx={{display:"flex", justifyContent:"flex-start", gap:"20px"}}>
                            <Box Component="div">
                                <Button variant="wpbkThemeCSVBtn" startIcon={<CsvIcon />} onClick={() => downloadCSV(this.state, "Bookify Customers")} >
                                    {__("Export to CSV", "bookify")}
                                </Button>
                            </Box>
                            <Box Component="div">
                                <Button variant="wpbkThemeBtn" startIcon={<AddIcon />} onClick={() => openDialog(this.state, this.setState.bind(this), "AddCustomerDialog")} >
                                    {__("Add Customer", "bookify")}
                                </Button>
                                <AddCustomer
                                    open={this.state.AddCustomerDialog}
                                    onClose={() => closeDialog(this.state, this.setState.bind(this), "AddCustomerDialog")}
                                    fetchCustomerById={this.fetchCustomerById}
                                    fetchCustomerData={this.fetchCustomerData}
                                    customerId={editDialogHandle}
                                />
                            </Box>
                        </Box>
                    </Box>
                    <Box component="div" sx={{m:"2em"}}>
                        <CustomerTable
                            state={this.state}
                            setState={this.setState.bind(this)}
                            headCells={headCells}
                            fetchCustomerData={this.fetchCustomerData}
                            TableData={TableData}
                            dateFormat={dateFormat}
                            totalCount={totalCount}
                            pageSize={pageSize}
                            page={page}
                            orderBy={orderBy}
                            order={order}
                            dataLoading={dataLoading}
                        />
                    </Box>
                </Box>
            </ThemeProvider>
        );
    }
}

export default Customers;
