import { Link, useNavigate } from 'react-router-dom';
import { DataTable, DataTableSortStatus } from 'mantine-datatable';
import { useEffect, useState } from 'react';
import Tippy from '@tippyjs/react';
import 'tippy.js/dist/tippy.css';
import sortBy from 'lodash/sortBy';
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, deleteRoleAPI, fetchRolesAPI } from '../../API';
import { hasAccess } from '../../../../../utils/hasAccess';
import { FaEye, FaEdit, FaTrash, FaUserPlus } from 'react-icons/fa';
import { useLoader } from '../../store/LoaderProvider';

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

    const PAGE_SIZES = [10, 20, 30, 50, 100];
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
    const [initialRecords, setInitialRecords] = useState<any[]>([]);
    const [recordsData, setRecordsData] = useState<any[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [search, setSearch] = useState('');
    const [sortStatus, setSortStatus] = useState<DataTableSortStatus>({ columnAccessor: 'name', direction: 'asc' });
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

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

    const fetchRoles = async () => {
        showLoader();
        try {
            const data = await fetchRolesAPI();

            if (data.status == 'true') {
                const formatted = data.data.map((role: any, i: number) => {
                    // Handle timestamp conversion - if it's an integer timestamp (unix timestamp)
                    let createdAtFormatted = 'N/A';
                    if (role.created_at) {
                        // If it's already an integer (unix timestamp in seconds)
                        if (typeof role.created_at === 'number') {
                            createdAtFormatted = new Date(role.created_at * 1000).toLocaleDateString('en-US', {
                                year: 'numeric',
                                month: 'short',
                                day: 'numeric'
                            });
                        } 
                        // If it's still a MongoDB date object or string
                        else if (typeof role.created_at === 'object' && role.created_at.$date) {
                            createdAtFormatted = new Date(role.created_at.$date).toLocaleDateString('en-US', {
                                year: 'numeric',
                                month: 'short',
                                day: 'numeric'
                            });
                        }
                        // If it's a string date
                        else if (typeof role.created_at === 'string') {
                            createdAtFormatted = new Date(role.created_at).toLocaleDateString('en-US', {
                                year: 'numeric',
                                month: 'short',
                                day: 'numeric'
                            });
                        }
                    }
                    
                    return {
                        id: i + 1,
                        _id: role._id,
                        name: capitalize(role.name),
                        createdAt: createdAtFormatted,
                        createdAtRaw: role.created_at, // Keep raw for sorting
                        updatedAt: role.updated_at,
                        status: role.delete_status === 'NO' ? 'Active' : 'Deleted'
                    };
                });

                setInitialRecords(formatted);
                setTotalRecords(data.totalRecords || formatted.length);
            } else {
                setError(data.message || 'Failed to load role data.');
            }
        } catch (err: any) {
            setError(err.message);
        } finally {
            hideLoader();
        }
    };

    useEffect(() => {
        dispatch(setPageTitle('Role Management'));
        fetchRoles();
    }, []);

    useEffect(() => {
        setPage(1);
    }, [pageSize]);

    useEffect(() => {
        let sorted = sortBy(initialRecords, sortStatus.columnAccessor);
        sorted = sortStatus.direction === 'desc' ? sorted.reverse() : sorted;

        const filtered = sorted.filter(item =>
            (item.name || '').toLowerCase().includes(search.toLowerCase()) ||
            (item.status || '').toLowerCase().includes(search.toLowerCase())
        );

        const from = (page - 1) * pageSize;
        const to = from + pageSize;
        setRecordsData(filtered.slice(from, to));
        setTotalRecords(filtered.length);
    }, [page, pageSize, search, sortStatus, initialRecords]);

    const handleEditClick = (roleId: number) => {
        navigate(`/roles/updaterole/`, { state: { roleId } });
    };

    const handleViewClick = (roleId: number) => {
        navigate(`/roles/roledetails/`, { state: { roleId } });
    };

    const deleteRole = async (roleId: number) => {
        try {
            const result = await Swal.fire({
                title: 'Are you sure?',
                text: 'This role will be permanently deleted!',
                icon: 'warning',
                showCancelButton: true,
            confirmButtonColor: '#5c4d2f', 
                cancelButtonColor: '#2196f3',
                confirmButtonText: 'Yes, delete it!',
    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 deleteRoleAPI(roleId);

                if (data.status == 'true') {
                    showMessage(data.message, data.status);
                    setInitialRecords(prev => prev.filter(role => role._id !== roleId));
                    fetchRoles();
                } else {
                    showMessage(data.message, data.status);
                }
            }
        } catch (err) {
            showMessage('Failed to delete role', 'error');
        } finally {
            hideLoader();
        }
    };

    return (
        <div className="relative">
            <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">Role Management</h5>
                        {/* <p className="text-sm text-gray-500 dark:text-gray-400">Manage all system roles and permissions</p> */}
                    </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 roles..."
                                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>
                        
                        {hasAccess(permissions, "Role", "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 gap-2"
                                to={"/roles/addrole"}
                            >
                                <FaUserPlus className="text-lg" /> Add Role
                            </Link>
                        )}
                    </div>
                </div>

                {error && (
                    <div className="mb-5 rounded-lg bg-red-100 dark:bg-red-900/50 text-red-600 dark:text-red-300 px-4 py-3">
                        {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={recordsData}
                            columns={[
                                { 
                                    accessor: 'name', 
                                    title: 'Role Name', 
                                    sortable: true,
                                    render: ({ name }) => (
                                        <span className="font-medium text-primary-DEFAULT dark:text-primary-light">{name}</span>
                                    )
                                },
                                { 
                                    accessor: 'status', 
                                    title: 'Status', 
                                    sortable: true,
                                    render: ({ status }) => (
                                        <span className={`px-2 py-1 rounded-md text-sm font-medium ${
                                            status === 'Active' 
                                                ? 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-100'
                                                : 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-100'
                                        }`}>
                                            {status}
                                        </span>
                                    )
                                },
                                { 
                                    accessor: 'createdAt', 
                                    title: 'Created At', 
                                    sortable: true,
                                    render: ({ createdAt }) => (
                                        <span className="text-gray-600 dark:text-gray-300">{createdAt}</span>
                                    )
                                },
                                {
                                    accessor: 'action',
                                    title: 'Actions',
                                    titleClassName: '!text-center',
                                    render: (row) => (
                                        <div className="flex items-center w-max mx-auto  ">
                                            <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._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="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, "Role", "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._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, "Role", "delete") && (
                                                <Tippy content="Delete">
                                                    <button
                                                        className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200"
                                                        onClick={() => deleteRole(row._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={setPage}
                            recordsPerPageOptions={PAGE_SIZES}
                            onRecordsPerPageChange={setPageSize}
                            sortStatus={sortStatus}
                            onSortStatusChange={setSortStatus}
                            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(' ') // Split by spaces
    .map(word => 
      word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
    )
    .join(' '); // Join back into a single string
}

export default RoleManagement;