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 PaymentFilters from "./PaymentFilters";
import PaymentTable from "./PaymentTable";
import { 
    downloadCSV
} 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 Payment extends Component {
    state = {
        headCells: [
            { id: "payment_id", label: "ID", priority: 0 },
            { id: "appointment_date", label: "Appointment Date", priority: 5 },
            { id: "customer_id", label: "Customer", priority: 10 },
            { id: "staff_id", label: "Staff", priority: 15 },
            { id: "appointment_service", label: "Service", priority: 20 },
            { id: "method", label: "Payment Method", priority: 25 },
            { id: "total", label: "Total Amount", priority: 30 },
            { id: "paid", label: "Paid Amount", priority: 35 },
            { id: "due", label: "Due Amount", priority: 40 },
            { id: "status", label: "Status", priority: 45 },
            { id: "action", label: "Action", priority: 50 },
        ],
        allPaymentData: [],
        TableData: [],
        searchText: "",
        staffs: [],
        services: [],
        customers: [],
        dateFormat: "",
        totalCount: 0,
        page: 0,
        pageSize: 10,
        order: "desc",
        orderBy: "id",
        filterDate: null,
        filterStaff: "none",
        filterService: "none",
        filterCustomer: "none",
        filterStatus: "none",
        dataLoading: true,
        StatusOptions: [
            "Paid", 
            "Unpaid", 
            "Pending", 
            "Cancelled"
        ],
        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: "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.fetchPaymentData();

        const title = window.wp.hooks.applyFilters("bookify_payment_title", "Payments");
        this.setState({ title });
    }

    fetchPaymentData = (page = 1, pageSized = 10, changePageSize = false, searchDate= "", searchStaff= "", searchService="", searchCustomer="", searchStatus="") => {
        const { searchText, pageSize } = this.state;
        let perPageSized = pageSize;
        if ( changePageSize ) {
            perPageSized = pageSized;
        }
        const params = {
            search: searchText.trim(),
            date: searchDate,
            staff: searchStaff,
            service: searchService,
            customer: searchCustomer,
            status: searchStatus
        };

        const queryString = Object.entries(params)
            .filter(([key, value]) => value && value != "none")
            .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
            .join("&");

        this.setState({ dataLoading: true });


        fetch(`${wpbAdmin.root}bookify/v1/payment?page=${page}&pageSize=${perPageSized}&${queryString}`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpApiSettings.nonce
            }
        })
        .then(response => response.json())
        .then(data => {
            this.setState({
            allPaymentData: data.data,
            TableData: data.data,
            totalCount: data.total,
            staffs: data.staffs,
            customers: data.customers,
            services: data.services,
            currency: data.currency,
            dateFormat: data.dateFormat
            });
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
        })
        .finally(() => {
            this.setState({ dataLoading: false });
        });
    };

    handleSearchData = (event) => {
        const searchText = event.target.value.toLowerCase();
        const { allPaymentData } = this.state;
    
        let filteredData;
    
        if (searchText == "") {
            filteredData = allPaymentData;
        } else {
            filteredData = allPaymentData.filter(payment => {
                return (
                    payment.appointment_date.toLowerCase().includes(searchText) ||
                    payment.appointment_customer_name.toLowerCase().includes(searchText) ||
                    payment.appointment_customer_email.toLowerCase().includes(searchText) ||
                    payment.appointment_staff_name.toLowerCase().includes(searchText) ||
                    payment.appointment_staff_email.toLowerCase().includes(searchText) ||
                    payment.service_name.toLowerCase().includes(searchText) ||
                    payment.method.toLowerCase().includes(searchText) ||
                    payment.total.toLowerCase().includes(searchText) ||
                    payment.paid.toLowerCase().includes(searchText) ||
                    payment.due.toLowerCase().includes(searchText) ||
                    payment.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, staffs, services, customers, filterDate, 
            filterStaff, filterService, filterCustomer, filterStatus, currency, 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 payments"
                                    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">
                            <Button variant="wpbkThemeCSVBtn" startIcon={<CsvIcon />} onClick={() => downloadCSV(this.state, "Bookify Payments")} >
                                {__("Export to CSV", "bookify")}
                            </Button>
                        </Box>
                    </Box>

                    <Box component="div" sx={{m:"2em", backgroundColor:"#FFFFFF"}}>
                        <PaymentFilters
                            state={this.state}
                            setState={this.setState.bind(this)}
                            filterDate={filterDate}
                            filterStaff={filterStaff}
                            filterService={filterService}
                            filterCustomer={filterCustomer}
                            filterStatus={filterStatus}
                            staffs={staffs}
                            services={services}
                            customers={customers}
                            fetchPaymentData={this.fetchPaymentData}
                        />
                        <PaymentTable
                            state={this.state}
                            setState={this.setState.bind(this)}
                            headCells={headCells}
                            fetchPaymentData={this.fetchPaymentData}
                            TableData={TableData}
                            totalCount={totalCount}
                            pageSize={pageSize}
                            page={page}
                            orderBy={orderBy}
                            order={order}
                            currency={currency}
                            dateFormat={dateFormat}
                            dataLoading={dataLoading}
                        />
                    </Box>
                </Box>
            </ThemeProvider>
        );
    }
}

export default Payment;

