import { Link, useNavigate } from 'react-router-dom';
import { DataTable, DataTableSortStatus } from 'mantine-datatable';
import { useCallback, useEffect, useRef, useState } from 'react';
import Tippy from '@tippyjs/react';
import 'tippy.js/dist/tippy.css';
import { useDispatch, useSelector } from 'react-redux';
import { IRootState } from '../../store';
import { setPageTitle } from '../../store/themeConfigSlice';
import Swal from 'sweetalert2';
import { showMessage } from '../../general';
import { 
    generateOrder, 
    getCustomers, 
    deleteCustomer as deleteCustomerAPI, 
    exportCustomers, 
    getCustomerNotes, 
    getCustomerNotesCount, 
    addCustomerNote, 
    updateCustomerNote, 
    deleteCustomerNote 
} from '../../API';
import { hasAccess } from '../../../../../utils/hasAccess';
import { useLoader } from '../../store/LoaderProvider';
import AutoCallerModal from '../../components/AutoCallerModal';

const OrderSorting = () => {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const isDark = useSelector((state: IRootState) => state.themeConfig.theme === 'dark' || state.themeConfig.isDarkMode);

    useEffect(() => {
        const loggedIn = localStorage.getItem('isLoggedIn') === 'true';
        if (!loggedIn) {
            navigate('/login');
        }
    }, [navigate]);

    const PAGE_SIZES = [10, 20, 30, 50, 100];
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(PAGE_SIZES[3]);
    const [records, setRecords] = useState<any[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [search, setSearch] = useState('');
    const [sortStatus, setSortStatus] = useState<DataTableSortStatus>({
        columnAccessor: 'created_at',
        direction: 'desc'
    });
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [generatingOrderFor, setGeneratingOrderFor] = useState<string | null>(null);
    const [showNotesModal, setShowNotesModal] = useState(false);
    const [selectedCustomerId, setSelectedCustomerId] = useState<string | null>(null);
    const [notes, setNotes] = useState<any[]>([]);
    const [showAddNote, setShowAddNote] = useState(false);
    const [noteText, setNoteText] = useState('');
    const [editingNoteId, setEditingNoteId] = useState<string | null>(null);
    const [loadingNotes, setLoadingNotes] = useState(false);
    const [noteCounts, setNoteCounts] = useState<{ [key: string]: number }>({});
    const [showCallerModal, setShowCallerModal] = useState(false);
    const [selectedCustomer, setSelectedCustomer] = useState<any>(null);

    const isRtl = useSelector((state: IRootState) => state.themeConfig.rtlClass) === 'rtl';
    const permissions = JSON.parse(localStorage.getItem("permissions") || "[]");
    const { showLoader, hideLoader } = useLoader();
    const loaderRef = useRef({ showLoader, hideLoader });

    useEffect(() => {
        loaderRef.current = { showLoader, hideLoader };
    }, [showLoader, hideLoader]);

    const fetchCustomerData = useCallback(async () => {
        setLoading(true);
        setError(null);
        loaderRef.current.showLoader();
        try {
            const data = await getCustomers({
                email: localStorage.getItem('email') || '',
                page,
                per_page: pageSize,
                search: search.trim(),
                sort_by: sortStatus.columnAccessor,
                sort_dir: sortStatus.direction,
            });

            if (data.status === 'success') {
                const formattedData = data.data.map((item: any) => ({
                    id: item._id ?? item.cust_id,
                    cust_id: item.cust_id,
                    firstName: capitalize(`${item.firstName ?? ''} ${item.lastName ?? ''}`.trim()),
                    email: item.email,
                    phone: formatPhoneNumber(item.phone),
                    address: item.address || '',
                    city: item.city || '',
                    state: item.state || '',
                    zip: item.zip || '',
                    country: item.country || '',
                    order_status: item.order_status || false,
                    order_id: item.order_id || 'Not Generated',
                    process_status: item.process_status || null,
                    deleted_status: item.RecDeleted,
                    created_at: item.created_at_formatted || formatTimestamp(item.created_at),
                }));

                setRecords(formattedData);
                setTotalRecords(data.meta?.total ?? formattedData.length);
                setError(null);
                
                // Fetch note counts for all customers
                if (formattedData.length > 0) {
                    fetchAllNoteCounts(formattedData.map((item: any) => item.cust_id));
                }
            } else {
                setError(data.message || 'Failed to load customer data.');
                setRecords([]);
                setTotalRecords(0);
            }
        } catch (err) {
            console.error(err);
            setError('Failed to load customer data. Please try again later.');
            setRecords([]);
            setTotalRecords(0);
        } finally {
            loaderRef.current.hideLoader();
            setLoading(false);
        }
    }, [page, pageSize, search, sortStatus.columnAccessor, sortStatus.direction]);

    useEffect(() => {
        const handler = setTimeout(() => {
            fetchCustomerData();
        }, 250);

        return () => clearTimeout(handler);
    }, [fetchCustomerData]);

    const deleteCustomer = async (customerId: string) => {
        try {
            const result = await Swal.fire({
                title: 'Are you sure?',
                text: 'You won\'t be able to revert this!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#a8916a', // Your primary color
                cancelButtonColor: '#6c757d', // A neutral gray color
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel',
                customClass: {
                    confirmButton: 'bg-[#5c4d2f] text-white px-4 py-2 rounded hover:bg-[#4a3e27]',
                    cancelButton: 'px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-secondary dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors',
                    actions: 'space-x-3' // adds gap between confirm & cancel buttons
                },
                buttonsStyling: false
            });

            if (result.isConfirmed) {
                showLoader();
                const data = await deleteCustomerAPI(customerId);
                if (data.status === 'success') {
                    hideLoader();
                    showMessage("Customer deleted successfully!");
                    fetchCustomerData();
                } else {
                    showMessage(data.message, data.status);
                    hideLoader();
                }
            }
        } catch (err) {
            Swal.fire('Error!', 'An error occurred while deleting the customer.', 'error');
            hideLoader();
        }
    };

    useEffect(() => {
        setPage(1);
    }, [pageSize, search, sortStatus.columnAccessor, sortStatus.direction]);

    useEffect(() => {
        dispatch(setPageTitle('Customer Details'));
    }, [dispatch]);

    const handleEditClick = (customerId: string) => {
        navigate(`/customers/updatecustomer/`, { state: { customerId } });
    };

    const handleViewClick = (customerId: string) => {
        navigate(`/customers/customerdetails/`, { state: { customerId } });
    };

    const handleCallClick = (customer: any) => {
        setSelectedCustomer(customer);
        setShowCallerModal(true);
    };

    const handleGenerateOrder = async (customerId: string) => {
        setGeneratingOrderFor(customerId);
        try {
            const custId = parseInt(customerId);
            const data = await generateOrder(custId);

            if (data.status == true) {
                showMessage(data.message, data.status);
                await fetchCustomerData();
            } else {
                showMessage(data.message, data.status);
            }
        } catch (error) {
            showMessage('An error occurred while generating the order', 'error');
        } finally {
            setGeneratingOrderFor(null);
        }
    };

    const handleExportToExcel = async () => {
        try {
            showLoader();
            
            const blob = await exportCustomers({
                email: localStorage.getItem('email') || '',
                search: search.trim(),
                sort_by: sortStatus.columnAccessor,
                sort_dir: sortStatus.direction,
            });
            
            // Create a download link
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `customers_export_${new Date().toISOString().split('T')[0]}.csv`;
            document.body.appendChild(link);
            link.click();
            
            // Cleanup
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            
            hideLoader();
            showMessage('Customers exported successfully!', 'success');
        } catch (error) {
            hideLoader();
            console.error('Export error:', error);
            showMessage('Failed to export customers. Please try again.', 'error');
        }
    };

    const handleOpenNotes = async (customerId: string) => {
        setSelectedCustomerId(customerId);
        setShowNotesModal(true);
        await fetchNotes(customerId);
    };

    const fetchNotes = async (customerId: string) => {
        setLoadingNotes(true);
        try {
            const data = await getCustomerNotes(customerId, localStorage.getItem('email') || '');
            if (data.status === 'success') {
                setNotes(data.data || []);
            } else {
                setNotes([]);
            }
        } catch (error) {
            console.error('Error fetching notes:', error);
            setNotes([]);
        } finally {
            setLoadingNotes(false);
        }
    };

    const fetchAllNoteCounts = async (customerIds: string[]) => {
        try {
            const data = await getCustomerNotesCount(customerIds, localStorage.getItem('email') || '');
            if (data.status === 'success' && data.data) {
                setNoteCounts(data.data);
            }
        } catch (error) {
            console.error('Error fetching note counts:', error);
        }
    };

    const handleSaveNote = async () => {
        if (!noteText.trim()) {
            showMessage('Please enter a note', 'error');
            return;
        }

        try {
            showLoader();
            const email = localStorage.getItem('email') || '';
            
            const data = editingNoteId 
                ? await updateCustomerNote(editingNoteId, noteText.trim(), selectedCustomerId!, email)
                : await addCustomerNote(selectedCustomerId!, noteText.trim(), email);
            
            if (data.status === 'success' || data.status === true) {
                showMessage(data.message, 'success');
                setNoteText('');
                setShowAddNote(false);
                setEditingNoteId(null);
                await fetchNotes(selectedCustomerId!);
                // Refresh note counts
                await fetchAllNoteCounts(records.map((item: any) => item.cust_id));
            } else {
                showMessage(data.message, 'error');
            }
        } catch (error) {
            console.error('Error saving note:', error);
            showMessage('Failed to save note', 'error');
        } finally {
            hideLoader();
        }
    };

    const handleEditNote = (note: any) => {
        setNoteText(note.note);
        setEditingNoteId(note._id);
        setShowAddNote(true);
    };

    const handleDeleteNote = async (noteId: string) => {
        try {
            const result = await Swal.fire({
                title: 'Are you sure?',
                text: 'You won\'t be able to revert this!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#a8916a',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel',
                customClass: {
                    container: 'swal-high-z-index',
                    confirmButton: 'bg-[#5c4d2f] text-white px-4 py-2 rounded hover:bg-[#4a3e27]',
                    cancelButton: 'px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-secondary dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors',
                    actions: 'space-x-3'
                },
                buttonsStyling: false,
                backdrop: true
            });

            if (result.isConfirmed) {
                showLoader();
                const data = await deleteCustomerNote(noteId, localStorage.getItem('email') || '');
                if (data.status === 'success' || data.status === true) {
                    showMessage('Note deleted successfully', 'success');
                    await fetchNotes(selectedCustomerId!);
                    // Refresh note counts
                    await fetchAllNoteCounts(records.map((item: any) => item.cust_id));
                } else {
                    showMessage(data.message, 'error');
                }
                hideLoader();
            }
        } catch (error) {
            console.error('Error deleting note:', error);
            showMessage('Failed to delete note', 'error');
            hideLoader();
        }
    };

    const handleCloseNotesModal = () => {
        setShowNotesModal(false);
        setSelectedCustomerId(null);
        setNotes([]);
        setShowAddNote(false);
        setNoteText('');
        setEditingNoteId(null);
    };


    const formatPhoneNumber = (phoneNumber: string): string => {
        if (typeof phoneNumber !== 'string' || !phoneNumber) return '';

        const cleaned = phoneNumber.replace(/\D/g, '');
        let cleanedWithoutCountryCode = cleaned;

        if (cleaned.length > 10) {
            const countryCodeLength = cleaned.length - 10;
            cleanedWithoutCountryCode = cleaned.slice(countryCodeLength);
        }

        if (cleanedWithoutCountryCode.length === 10) {
            return `+${cleaned.slice(0, cleaned.length - 10)} (${cleanedWithoutCountryCode.slice(0, 3)}) ${cleanedWithoutCountryCode.slice(3, 6)}-${cleanedWithoutCountryCode.slice(6)}`;
        }

        return phoneNumber;
    };

    const formatFullAddress = (row: any): string => {
        const parts = [
            row.address,
            row.city,
            row.state,
            row.zip,
            row.country
        ].filter(part => part && part.trim() !== '');
        
        return parts.length > 0 ? parts.join(', ') : 'N/A';
    };

    const formatTimestamp = (value: unknown): string => {
        if (value === null || value === undefined || value === '') {
            return '';
        }

        let date: Date | null = null;

        if (typeof value === 'number') {
            const adjusted = value.toString().length === 13 ? value : value * 1000;
            date = new Date(adjusted);
        } else if (typeof value === 'string') {
            const numeric = Number(value);
            if (!Number.isNaN(numeric) && value.trim() !== '') {
                const adjusted = value.trim().length === 13 ? numeric : numeric * 1000;
                date = new Date(adjusted);
            } else {
                const parsed = new Date(value);
                if (!Number.isNaN(parsed.getTime())) {
                    date = parsed;
                }
            }
        }

        if (!date || Number.isNaN(date.getTime())) {
            return '';
        }

        return new Intl.DateTimeFormat('en-US', {
            timeZone: 'America/Chicago',
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
        }).format(date);
    };

    const formatTimestampWithTime = (value: unknown): string => {
        if (value === null || value === undefined || value === '') {
            return '';
        }

        let date: Date | null = null;

        if (typeof value === 'number') {
            const adjusted = value.toString().length === 13 ? value : value * 1000;
            date = new Date(adjusted);
        } else if (typeof value === 'string') {
            const numeric = Number(value);
            if (!Number.isNaN(numeric) && value.trim() !== '') {
                const adjusted = value.trim().length === 13 ? numeric : numeric * 1000;
                date = new Date(adjusted);
            } else {
                const parsed = new Date(value);
                if (!Number.isNaN(parsed.getTime())) {
                    date = parsed;
                }
            }
        }

        if (!date || Number.isNaN(date.getTime())) {
            return '';
        }

        return new Intl.DateTimeFormat('en-US', {
            timeZone: 'America/Chicago',
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: true
        }).format(date);
    };

    return (
        <div className="relative">
            <style>
                {`
                    .swal-high-z-index {
                        z-index: 99999 !important;
                    }
                    .swal2-container {
                        z-index: 99999 !important;
                    }
                `}
            </style>
            <div className="panel  ">
                <div className="flex md:items-center md:flex-row flex-col mb-5 gap-5">
                    <div>
                        <h5 className="font-semibold text-lg dark:text-white-light">Customer Management</h5>

                    </div>

                    <div className="ltr:ml-auto rtl:mr-auto flex items-center gap-4">
                        <div className="relative flex-1">
                            <input
                                type="text"
                                className="form-input w-full pl-10 pr-4 py-2 rounded-lg border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:focus:ring-primary-400 dark:focus:border-primary-400 transition-all duration-200"
                                placeholder="Search customers..."
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                            />
                            <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                                </svg>
                            </div>
                        </div>

                        <button
                            onClick={handleExportToExcel}
                            className="btn btn-outline-primary rounded-lg px-4 py-2 border-2 border-primary-DEFAULT text-primary-DEFAULT hover:bg-primary-DEFAULT hover:text-white transition-all duration-200 flex items-center gap-2"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                            </svg>
                            Export to Excel
                        </button>

                        {hasAccess(permissions, "Customer", "add") && (
                            <Link
                                className="btn btn-primary rounded-lg px-4 py-2 text-white bg-primary-DEFAULT hover:bg-primary-light border-primary-DEFAULT hover:border-primary-light transition-all duration-200 shadow-primary hover:shadow-primary-lg flex items-center"
                                to={'/customers/addcustomer'}
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                                </svg>
                                Add Customer
                            </Link>
                        )}
                    </div>
                </div>

                {error && (
                    <div className="mb-4 rounded-lg border border-danger/20 bg-danger/10 px-4 py-3 text-danger">
                        {error}
                    </div>
                )}

                {loading && (
                    <div className="fixed inset-0 flex justify-center items-center bg-black bg-opacity-50 z-[9999]">
                        <div className="w-16 h-16 border-t-4 border-primary-DEFAULT border-solid rounded-full animate-spin"></div>
                    </div>
                )}

                {/* {loading ? (
                    <div className="flex justify-center items-center h-64">
                        <div className="w-12 h-12 border-t-4 border-primary-DEFAULT border-solid rounded-full animate-spin"></div>
                    </div>
                ) : ( */}
                <div className="datatables">
                    <DataTable
                        highlightOnHover
                        className="whitespace-nowrap table-hover rounded-lg overflow-hidden"
                        records={records}
                        columns={[
                            {
                                accessor: 'firstName',
                                title: 'Name',
                                sortable: true,
                                render: ({ firstName, cust_id }) => (
                                    <div className="flex items-center">
                                        <div className="w-10 h-10 rounded-full bg-primary/10 dark:bg-primary-dark-light flex items-center justify-center mr-3">
                                            <span className="text-primary-DEFAULT dark:text-primary-light font-semibold">
                                                {firstName.charAt(0)}
                                            </span>
                                        </div>
                                        <Tippy content={firstName} placement="top" arrow={false}>
                                            <span className="truncate max-w-[150px] inline-block font-medium dark:text-white-light">
                                                {firstName}
                                            </span>
                                        </Tippy>
                                    </div>
                                )
                            },
                            {
                                accessor: 'email',
                                title: 'Email',
                                sortable: true,
                                render: ({ email }) => (
                                    <Tippy content={email} placement="top" arrow={false}>
                                        <span className="truncate max-w-[200px] inline-block text-gray-600 dark:text-gray-300">
                                            {email}
                                        </span>
                                    </Tippy>
                                )
                            },
                            {
                                accessor: 'phone',
                                title: 'Phone',
                                sortable: true,
                                render: ({ phone }) => (
                                    <span className="text-gray-600 dark:text-gray-300">
                                        {phone}
                                    </span>
                                )
                            },
                            {
                                accessor: 'address',
                                title: 'Address',
                                sortable: true,
                                render: (row) => (
                                    <Tippy content={formatFullAddress(row)} placement="top" arrow={false}>
                                        <span className="truncate max-w-[250px] inline-block text-gray-600 dark:text-gray-300">
                                            {formatFullAddress(row)}
                                        </span>
                                    </Tippy>
                                )
                            },
                            {
                                accessor: 'deleted_status',
                                title: 'Status',
                                sortable: false,
                                render: ({ deleted_status }) => (
                                    <span
                                        className={`inline-block px-3 py-1 text-sm font-medium rounded-full border 
        ${deleted_status === 'yes'
                                                ? 'bg-red-100 text-red-800 border-red-200 dark:bg-red-900 dark:text-red-100 dark:border-red-700'
                                                : 'bg-green-100 text-green-800 border-green-200 dark:bg-green-900 dark:text-green-100 dark:border-green-700'
                                            }`}
                                    >
                                        {deleted_status === 'yes' ? 'Inactive' : 'Active'}
                                    </span>
                                ),
                            },
                            {
                                accessor: 'created_at',
                                title: 'Registered At',
                                sortable: true,
                                render: ({ created_at }) => (
                                    <span className="text-gray-600 dark:text-gray-300">
                                        {created_at}
                                    </span>
                                )
                            },

                            // { 
                            //     accessor: 'order_id', 
                            //     title: 'Order ID', 
                            //     sortable: true,
                            //     render: ({ order_id }) => (
                            //         <span className={`px-2 py-1 rounded-md text-sm font-medium ${
                            //             order_id === "Not Generated" 
                            //                 ? 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200' 
                            //                 : 'bg-secondary/10 dark:bg-secondary-dark-light text-secondary-DEFAULT dark:text-secondary-light'
                            //         }`}>
                            //             {order_id}
                            //         </span>
                            //     )
                            // },
                            // {
                            //     accessor: 'generateOrder',
                            //     title: 'Order Status',
                            //     render: (row) => {
                            //         const shouldEnable = row.process_status === "processing" && !row.order_status;
                            //         const isDisabled = !shouldEnable || row.order_status || generatingOrderFor === row.cust_id;

                            //         return (
                            //             <button
                            //                 onClick={() => shouldEnable && handleGenerateOrder(row.cust_id)}
                            //                 className={`px-4 py-2 rounded-lg transition-all duration-200 ${
                            //                     (generatingOrderFor !== row.cust_id && !row.order_status && row.process_status !== "processing")
                            //                         ? 'bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 cursor-not-allowed'
                            //                         : isDisabled
                            //                             ? 'bg-primary/20 dark:bg-primary-dark-light text-primary-DEFAULT/50 dark:text-primary-light/50 cursor-not-allowed'
                            //                             : 'bg-primary hover:bg-primary-light text-white shadow-primary hover:shadow-primary-lg'
                            //                 }`}
                            //                 disabled={isDisabled}
                            //             >
                            //                 {generatingOrderFor === row.cust_id
                            //                     ? (
                            //                         <span className="flex items-center">
                            //                             <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            //                                 <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            //                                 <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            //                             </svg>
                            //                             Generating...
                            //                         </span>
                            //                     )
                            //                     : row.order_status
                            //                         ? 'Order Generated'
                            //                         : row.process_status === "processing"
                            //                             ? 'Generate Order'
                            //                             : 'Not Ready'
                            //                 }
                            //             </button>
                            //         );
                            //     },
                            // },
                            {
                                accessor: 'actions',
                                title: 'Actions',
                                titleClassName: '!text-center',
                                render: (row) => (
                                    <div className="flex items-center w-max mx-auto  ">
                                        <Tippy content="AI Call">
                                            <button
                                                className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200"
                                                onClick={() => handleCallClick(row)}
                                            >
                                                <svg className="w-5 h-5 text-gray-500 hover:text-primary dark:text-gray-300 dark:hover:text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                                </svg>
                                            </button>
                                        </Tippy>

                                        <Tippy content="Notes">
                                            <button
                                                className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200 relative"
                                                onClick={() => handleOpenNotes(row.cust_id)}
                                            >
                                                <svg className="w-5 h-5 text-gray-500 hover:text-primary dark:text-gray-300 dark:hover:text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                                </svg>
                                                {noteCounts[row.cust_id] > 0 && (
                                                    <span className="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full h-5 w-5 flex items-center justify-center font-semibold">
                                                        {noteCounts[row.cust_id]}
                                                    </span>
                                                )}
                                            </button>
                                        </Tippy>

                                        <Tippy content="View History">
                                            <Link
                                                to={`/customers/history/${row.cust_id}`}
                                                className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200"
                                            >
                                                <svg className="w-5 h-5 text-gray-500 hover:text-primary dark:text-gray-300 dark:hover:text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                                </svg>
                                            </Link>
                                        </Tippy>

                                        {hasAccess(permissions, "Customer", "edit") && (
                                            <Tippy content="Edit">
                                                <button
                                                    className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200"
                                                    onClick={() => handleEditClick(row.cust_id)}
                                                >
                                                    <svg className="w-5 h-5 text-gray-500 hover:text-primary dark:text-gray-300 dark:hover:text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                    </svg>
                                                </button>
                                            </Tippy>
                                        )}

                                        {hasAccess(permissions, "Customer", "delete") && (
                                            <Tippy content="Delete">
                                                <button
                                                    className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200"
                                                    onClick={() => deleteCustomer(row.cust_id)}
                                                >
                                                    <svg className="w-5 h-5 text-gray-500 hover:text-danger dark:text-gray-300 dark:hover:text-danger" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                    </svg>
                                                </button>
                                            </Tippy>
                                        )}
                                    </div>
                                ),
                            }
                        ]}
                        totalRecords={totalRecords}
                        recordsPerPage={pageSize}
                        page={page}
                        onPageChange={(p) => setPage(p)}
                        recordsPerPageOptions={PAGE_SIZES}
                        onRecordsPerPageChange={setPageSize}
                        sortStatus={sortStatus}
                        onSortStatusChange={(status) => {
                            setSortStatus(status);
                        }}
                        minHeight={200}
                        rowClassName={(record) =>
                            `transition-colors duration-100 ${isDark ? 'hover:bg-gray-700' : 'hover:bg-gray-50'}`
                        }
                        paginationText={({ from, to, totalRecords }) => (
                            <span className="dark:text-white-light">
                                Showing {from} to {to} of {totalRecords} entries
                            </span>
                        )}
                    />
                </div>
                {/* // )} */}
            </div>

            {/* Notes Modal */}
            {showNotesModal && (
                <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black bg-opacity-50" onClick={handleCloseNotesModal}>
                    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden" onClick={(e) => e.stopPropagation()}>
                        {/* Modal Header */}
                        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
                            <h3 className="text-xl font-semibold text-gray-900 dark:text-white">Customer Notes</h3>
                            <button
                                onClick={handleCloseNotesModal}
                                className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                            >
                                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>

                        {/* Modal Body */}
                        <div className="p-6 overflow-y-auto max-h-[calc(80vh-140px)]">
                            {/* Add Note Button */}
                            {!showAddNote && (
                                <button
                                    onClick={() => setShowAddNote(true)}
                                    className="mb-4 w-full flex items-center justify-center gap-2 px-4 py-3 bg-primary hover:bg-primary-light text-white rounded-lg transition-all duration-200"
                                >
                                    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                                    </svg>
                                    Add New Note
                                </button>
                            )}

                            {/* Add/Edit Note Form */}
                            {showAddNote && (
                                <div className="mb-6 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        {editingNoteId ? 'Edit Note' : 'New Note'}
                                    </label>
                                    <textarea
                                        value={noteText}
                                        onChange={(e) => setNoteText(e.target.value)}
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary dark:bg-gray-800 dark:text-white resize-none"
                                        rows={4}
                                        placeholder="Enter your note here..."
                                    />
                                    <div className="flex gap-2 mt-3">
                                        <button
                                            onClick={handleSaveNote}
                                            className="px-4 py-2 bg-primary hover:bg-primary-light text-white rounded-lg transition-all duration-200"
                                        >
                                            {editingNoteId ? 'Update' : 'Save'}
                                        </button>
                                        <button
                                            onClick={() => {
                                                setShowAddNote(false);
                                                setNoteText('');
                                                setEditingNoteId(null);
                                            }}
                                            className="px-4 py-2 bg-gray-300 dark:bg-gray-600 hover:bg-gray-400 dark:hover:bg-gray-500 text-gray-700 dark:text-gray-300 rounded-lg transition-all duration-200"
                                        >
                                            Cancel
                                        </button>
                                    </div>
                                </div>
                            )}

                            {/* Notes List */}
                            {loadingNotes ? (
                                <div className="flex justify-center items-center py-8">
                                    <div className="w-8 h-8 border-t-4 border-primary-DEFAULT border-solid rounded-full animate-spin"></div>
                                </div>
                            ) : notes.length === 0 ? (
                                <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                                    <svg className="w-16 h-16 mx-auto mb-4 text-gray-300 dark:text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                    </svg>
                                    <p>No notes yet. Add your first note!</p>
                                </div>
                            ) : (
                                <div className="space-y-4">
                                    {notes.map((note) => (
                                        <div key={note._id} className="p-4 bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg shadow-sm">
                                            <div className="flex justify-between items-start mb-2">
                                                <p className="text-sm text-gray-600 dark:text-gray-400">
                                                    {formatTimestampWithTime(note.created_at)}
                                                </p>
                                                <div className="flex gap-2">
                                                    <button
                                                        onClick={() => handleEditNote(note)}
                                                        className="text-primary hover:text-primary-light transition-colors"
                                                        title="Edit"
                                                    >
                                                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                        </svg>
                                                    </button>
                                                    <button
                                                        onClick={() => handleDeleteNote(note._id)}
                                                        className="text-danger hover:text-red-600 transition-colors"
                                                        title="Delete"
                                                    >
                                                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                        </svg>
                                                    </button>
                                                </div>
                                            </div>
                                            <p className="text-gray-800 dark:text-gray-200 whitespace-pre-wrap">{note.note}</p>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            )}

            <AutoCallerModal
                isOpen={showCallerModal}
                onClose={() => {
                    setShowCallerModal(false);
                    setSelectedCustomer(null);
                }}
                customerId={selectedCustomer?.cust_id}
                customerName={selectedCustomer?.firstName}
                customerPhone={selectedCustomer?.phone}
            />
        </div>
    );
};

function capitalize(text: string): string {
    if (!text) return '';

    return text
        .split(' ') // Split by spaces
        .map(word =>
            word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
        )
        .join(' '); // Join back into a single string
}

export default OrderSorting;