import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import 'mantine-datatable/styles.css';
import { DataTable } from '@/components/Shared/DataTable';

import { setPageTitle } from '../../store/themeConfigSlice';
import { getStatusColorClass } from '@/lib/order-status-lib';

import ProtectedRoute from '@/components/ProtectedRoute';
import { logActivity } from '@/utils/activityLogger';
import CloseIcon from '@mui/icons-material/Close';

interface Customer {
    customer_email: string;
    customer_name: string;
    customer_phone: string;
    orderCount: number;
}

interface CustomerTransaction {
    order_id: string;
    order_date: string;
    order_status: string;
    sub_total: number;
    order_items: Array<{ name?: string }>;
}

const CustomersIndex = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Customers'));
    }, []);

    const [isMounted, setIsMounted] = useState(false);

    useEffect(() => {
        setIsMounted(true);
    }, []);

    const [page, setPage] = useState(1);
    const PAGE_SIZES = [5, 10, 20, 30, 50, 100];
    const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
    const [records, setRecords] = useState<Customer[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [search, setSearch] = useState('');

    const [isLoading, setIsLoading] = useState(true); // Add isLoading state
    const [isLoadingDownload, setIsLoadingDownload] = useState(false);
    const [isTransactionModalOpen, setIsTransactionModalOpen] = useState(false);
    const [isLoadingTransaction, setIsLoadingTransaction] = useState(false);
    const [selectedCustomerEmail, setSelectedCustomerEmail] = useState('');
    const [customerTransactions, setCustomerTransactions] = useState<CustomerTransaction[]>([]);

    // Fetch data from API
    const fetchData = async () => {
        setIsLoading(true); // Set isLoading to true before fetching data
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/customer?page=${page}&per_page=${pageSize}&q=${search}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include', // Include this option
            });
            const data = await response.json();

            setPage(data.currentPage);
            setTotalRecords(data.totalData);
            setRecords(data.data);

            setIsLoading(false); // Set isLoading to false after data is fetched
        } catch (error) {
            console.error('Error fetching data:', error);
            setIsLoading(false); // Set isLoading to false even if there's an error
        }
    };

    useEffect(() => {
        fetchData();
    }, [page, pageSize]);

    const handleKeypress = (event: React.KeyboardEvent<HTMLInputElement>) => {
        if (event.keyCode === 13) {
            if (page !== 1) {
                setPage(1);
            } else {
                fetchData();
            }
        }
    };

    async function handleDownloadExcel(data: any) {
        const XLSX = await import('xlsx');
        const workbook = XLSX.utils.book_new();
        const worksheet = XLSX.utils.json_to_sheet(data);

        XLSX.utils.book_append_sheet(workbook, worksheet, 'Customer');

        XLSX.writeFile(workbook, 'Customer.xlsx', { compression: true });
    }

    const fetchAllCustomer = async () => {
        const api_url = process.env.API_URL;
        const response = await fetch(`${api_url}api/customer/all`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include', // Include this option
        });
        return await response.json();
    };

    const handleDownload = async () => {
        setIsLoadingDownload(true);
        const allData = await fetchAllCustomer();

        if (allData.length > 0) {
            const mappingCustomer = allData.map((data: Customer) => ({
                email: data.customer_email || '',
                name: data.customer_name || '',
                phone: data.customer_phone || '',
                orderCount: data.orderCount || 0,
            }));
            handleDownloadExcel(mappingCustomer);
        }
        await logActivity({
            location: 'Customer',
            description: `Download Customer`,
        });
        setIsLoadingDownload(false);
    };

    const formatTransactionDate = (date: string) => {
        if (!date) return '-';
        return new Date(date).toLocaleString('id-ID');
    };

    const formatTransactionProduct = (items: Array<{ name?: string }>) => {
        if (!Array.isArray(items) || items.length === 0) return '-';
        return items.map((item) => item?.name || '-').join(', ');
    };

    const formatTransactionPrice = (price: number) => {
        return `Rp ${(price || 0).toLocaleString('id-ID')}`;
    };

    const handleOpenTransactionModal = async (customerEmail: string) => {
        setSelectedCustomerEmail(customerEmail);
        setIsTransactionModalOpen(true);
        setIsLoadingTransaction(true);
        setCustomerTransactions([]);

        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/order/list?page=1&per_page=100&customer_email=${encodeURIComponent(customerEmail)}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
            });
            const data = await response.json();
            const transactions = Array.isArray(data?.data) ? data.data : [];
            const sortedTransactions = transactions.sort((a: CustomerTransaction, b: CustomerTransaction) => {
                return new Date(b.order_date).getTime() - new Date(a.order_date).getTime();
            });
            setCustomerTransactions(sortedTransactions);
        } catch (error) {
            console.error('Error fetching customer transactions:', error);
            setCustomerTransactions([]);
        } finally {
            setIsLoadingTransaction(false);
        }
    };

    const statusTransaction = (status: string) => {
        if (status === 'Pending') {
            return <span className="text-yellow-500">Pending</span>;
        } else if (status === 'Processing') {
            return <span className="text-blue-500">Processing</span>;
        } else if (status === 'Failed') {
            return <span className="text-red-800">Failed</span>;
        } else if (status === 'Completed') {
            return <span className="text-green-500">Completed</span>;
        } else if (status === 'Canceled') {
            return <span className="text-red-500">Canceled</span>;
        }
    };

    return (
        <>
            {isMounted && (
                    <>
                        <div className="mb-3">
                            <ul className="flex space-x-2 rtl:space-x-reverse">
                                <li>
                                    <span>Customers</span>
                                </li>
                            </ul>
                        </div>

                        <div className="flex flex-wrap items-center justify-between gap-4">
                            <div className="flex w-full flex-col gap-4 sm:w-auto sm:flex-row sm:items-center sm:gap-3">
                                <div className="relative">
                                    <input
                                        type="text"
                                        placeholder="Search by email"
                                        className="peer form-input py-2 ltr:pr-11 rtl:pl-11"
                                        value={search}
                                        onChange={(e) => setSearch(e.target.value)}
                                        onKeyDown={handleKeypress}
                                    />
                                    <div className="absolute top-1/2 -translate-y-1/2 peer-focus:text-primary ltr:right-[11px] rtl:left-[11px]">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <circle cx="11.5" cy="11.5" r="9.5" stroke="currentColor" strokeWidth="1.5" opacity="0.5"></circle>
                                            <path d="M18.5 18.5L22 22" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"></path>
                                        </svg>
                                    </div>
                                </div>
                                <div className="flex w-full flex-col gap-4 sm:w-auto sm:flex-row sm:items-center sm:gap-3">
                                    <button className="btn btn-sm btn-outline-success flex items-center justify-center" onClick={handleDownload} disabled={isLoading}>
                                        {isLoadingDownload ? (
                                            <>
                                                <div className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent"></div>
                                                <span className="ml-2">Downloading..</span>
                                            </>
                                        ) : (
                                            'Download Customer'
                                        )}
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div className="panel mt-5  overflow-hidden border-0 px-0 pt-0">
                            <div className="user-table">
                                <div className="datatables pagination-padding">
                                    {isLoading ? (
                                        // Show loading indicator here
                                        <div className="flex justify-center py-4 text-center">
                                            <svg
                                                viewBox="0 0 24 24"
                                                width="24"
                                                height="24"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                                fill="none"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                                className="h-5 w-5 animate-spin text-white-dark"
                                            >
                                                <line x1="12" y1="2" x2="12" y2="6"></line>
                                                <line x1="12" y1="18" x2="12" y2="22"></line>
                                                <line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
                                                <line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
                                                <line x1="2" y1="12" x2="6" y2="12"></line>
                                                <line x1="18" y1="12" x2="22" y2="12"></line>
                                                <line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
                                                <line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
                                            </svg>
                                            <span className="ms-3">Please wait, we&apos;re still working to load the data...</span>
                                        </div>
                                    ) : (
                                        <DataTable
                                            className="table-hover whitespace-nowrap"
                                            records={records}
                                            minHeight={250}
                                            noRecordsText="No data found"
                                            columns={[
                                                {
                                                    accessor: 'email',
                                                    render: ({ customer_email }) => (
                                                        <button
                                                            type="button"
                                                            className="font-semibold text-primary hover:underline"
                                                            onClick={() => handleOpenTransactionModal(customer_email)}
                                                        >
                                                            {customer_email}
                                                        </button>
                                                    ),
                                                },

                                                {
                                                    accessor: 'name',
                                                    render: ({ customer_name }) => <>{customer_name}</>,
                                                },
                                                {
                                                    accessor: 'phone',
                                                    render: ({ customer_phone }) => <>{customer_phone}</>,
                                                },
                                                {
                                                    accessor: 'order total',
                                                    render: ({ orderCount }) => <>{orderCount}</>,
                                                },
                                            ]}
                                            highlightOnHover
                                            totalRecords={totalRecords}
                                            recordsPerPage={pageSize}
                                            page={page}
                                            onPageChange={(p) => setPage(p)}
                                            recordsPerPageOptions={PAGE_SIZES}
                                            onRecordsPerPageChange={setPageSize}
                                            paginationText={({ from, to, totalRecords }) => `Showing  ${from} to ${to} of ${totalRecords} customers`}
                                        />
                                    )}
                                </div>
                            </div>
                        </div>
                        {isTransactionModalOpen && (
                            <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setIsTransactionModalOpen(false)}>
                                <div className="max-h-[90vh] w-full max-w-6xl overflow-y-auto rounded-lg bg-white p-4 shadow-xl dark:bg-[#1e293b]" onClick={(e) => e.stopPropagation()}>
                                    <div className="mb-4 flex items-center justify-between">
                                        <h3 className="text-lg font-semibold">Transaksi Customer: {selectedCustomerEmail}</h3>
                                        <button type="button" onClick={() => setIsTransactionModalOpen(false)}>
                                            <CloseIcon />
                                        </button>
                                    </div>

                                    <DataTable
                                        className="table-hover whitespace-nowrap"
                                        records={customerTransactions}
                                        minHeight={220}
                                        noRecordsText={isLoadingTransaction ? 'Memuat data transaksi...' : 'Tidak ada transaksi'}
                                        columns={[
                                            {
                                                accessor: 'transaction_date',
                                                title: 'Tanggal Transaksi',
                                                render: ({ order_date }) => <>{formatTransactionDate(order_date)}</>,
                                            },
                                            {
                                                accessor: 'order_id',
                                                title: 'Order ID',
                                                render: ({ order_id }) => <>{order_id}</>,
                                            },
                                            {
                                                accessor: 'product',
                                                title: 'Product',
                                                render: ({ order_items }) => <div className="max-w-[380px] whitespace-normal">{formatTransactionProduct(order_items)}</div>,
                                            },
                                            {
                                                accessor: 'price',
                                                title: 'Harga',
                                                render: ({ sub_total }) => <div className="text-left">{formatTransactionPrice(sub_total)}</div>,
                                            },
                                            {
                                                accessor: 'status',
                                                title: 'Status Transaksi',
                                                render: ({ order_status }) => <span className={`flex w-24 justify-center badge badge-nb ${getStatusColorClass(order_status)} `}>{order_status}</span>,
                                            },
                                        ]}
                                    />
                                </div>
                            </div>
                        )}
                    </>
                )}
        </>
    );
};

export default CustomersIndex;
