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 { base_url, generateOrder } from '../../API';
import { hasAccess } from '../../../../../utils/hasAccess';
import { useLoader } from '../../store/LoaderProvider';

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 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 fetchInquiryData = useCallback(async () => {
        setLoading(true);
        setError(null);
        loaderRef.current.showLoader();
        try {
            const response = await fetch(`${base_url}get_inquiries`, {
                method: 'POST',
                body: JSON.stringify({
                    company_id: localStorage.getItem('companyId'),
                    page,
                    per_page: pageSize,
                    search: search.trim(),
                    sort_by: sortStatus.columnAccessor,
                    sort_dir: sortStatus.direction,
                }),
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                },
            });

            const data = await response.json();
            console.log(data.data?.data);
            if (data.status === 'success' && data.data?.data?.inquiries?.length > 0) {
                const formattedData = data.data.data.inquiries?.map((item: any) => ({
                    id: item._id,
                    inq: item._id,
                    fullName: capitalize(`${item.fullName ?? ''}`),
                    email: item.email,
                    phone: formatPhoneNumber(item.phone),
                    address: item.address || '',
                    recDeleted: item.recDeleted,
                    created_at: item.created_at_formatted || formatTimestamp(item.created_at),
                }));

                setRecords(formattedData);
                setTotalRecords(data.meta?.total ?? formattedData.length);
                setError(null);
            }
        } catch (err) {
            console.error(err);
            setError('Failed to load inquiry 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(() => {
            fetchInquiryData();
        }, 250);

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

    const deleteInquiry = async (inquiryId: string) => {
        console.log(inquiryId);

        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: {
                    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,
            });

            if (result.isConfirmed) {
                showLoader();
                const response = await fetch(`${base_url}delete_inquiry`, {
                    method: 'POST',
                    body: JSON.stringify({
                       inquiry_id: inquiryId,
                       company_id: localStorage.getItem('companyId')
                      }),
                    headers: {
                        Accept: 'application/json',
                        'Content-Type': 'application/json',
                    },
                });

                const data = await response.json();
                if (data.status === 'success') {
                    hideLoader();
                    showMessage('Inquiry deleted successfully!');
                    fetchInquiryData();
                } else {
                    showMessage(data.message, data.status);
                    hideLoader();
                }
            }
        } catch (err) {
            Swal.fire('Error!', 'An error occurred while deleting the inquiry.', 'error');
            hideLoader();
        }
    };

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

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

    const handleViewClick = (inquiryId: string) => {
        navigate(`/inquiries/view/`, { state: { inquiryId } });
    };

    const handleExportToExcel = async () => {
        try {
            showLoader();

            const response = await fetch(`${base_url}export_inquiries`, {
                method: 'POST',
                body: JSON.stringify({
                    email: localStorage.getItem('email'),
                    company_id: localStorage.getItem('companyId'),
                    search: search.trim(),
                    sort_by: sortStatus.columnAccessor,
                    sort_dir: sortStatus.direction,
                }),
                headers: {
                    Accept: 'text/csv',
                    'Content-Type': 'application/json',
                },
            });

            if (!response.ok) {
                throw new Error('Export failed');
            }

            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `inquiries_export_${new Date().toISOString().split('T')[0]}.csv`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);

            hideLoader();
            showMessage('Inquiries exported successfully!', 'success');
        } catch (error) {
            hideLoader();
            console.error('Export error:', error);
            showMessage('Failed to export Inquiries. Please try again.', 'error');
        }
    };

    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 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);
    };

    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">Inquiry 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 inquiries..."
                                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={'/inquiries/add'}
                            >
                                <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 Inquiry
                            </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>
                )}

                <div className="datatables">
                    <DataTable
                        highlightOnHover
                        className="whitespace-nowrap table-hover rounded-lg overflow-hidden"
                        records={records}
                        columns={[
                            {
                                accessor: 'firstName',
                                title: 'Name',
                                sortable: true,
                                render: ({ fullName, 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">
                                            {fullName ? <span className="text-primary-DEFAULT dark:text-primary-light font-semibold">{fullName.charAt(0)}</span> : 'N/A'}
                                        </div>
                                        <Tippy content={fullName} placement="top" arrow={false}>
                                            <span className="truncate max-w-[150px] inline-block font-medium dark:text-white-light">{fullName}</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: 'created_at',
                                title: 'Registered At',
                                sortable: true,
                                render: ({ created_at }) => <span className="text-gray-600 dark:text-gray-300">{created_at}</span>,
                            },
                            {
                                accessor: 'actions',
                                title: 'Actions',
                                titleClassName: '!text-center',
                                render: (row) => (
                                    <div className="flex items-center w-max mx-auto">
                                        {hasAccess(permissions, 'Customer', 'view') && (
                                            <Tippy content="View">
                                                <button className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200" onClick={() => handleViewClick(row.inq)}>
                                                    <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>
                                                </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={() => deleteInquiry(row.inq)}>
                                                    <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>
        </div>
    );
};

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

    return text
        .split(' ')
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
        .join(' ');
}

export default OrderSorting;
