/**
 * PermissionAnalyzer Page
 * 
 * Thin orchestrator for user permission analysis and comparison.
 * All business logic lives in usePermissionAnalyzer hook.
 */
import React from 'react';
import { Users, Shield, Search, RefreshCw, AlertCircle, Check, X, Info, ChevronDown, ChevronRight } from 'lucide-react';
import { RecordListSkeleton } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { usePermissionAnalyzer } from '../features/permission-analyzer/hooks/usePermissionAnalyzer';

export const PermissionAnalyzer: React.FC = () => {
    const {
        searchQuery, setSearchQuery,
        searching, searchResults,
        selectedUser, compareUser,
        userPermissions, comparePermissions,
        loading, expandedSections,
        searchUsers, handleSelectUser, handleRefresh,
        toggleSection, clearCompare,
    } = usePermissionAnalyzer();

    const renderPermissionRow = (key: string, value: boolean, compareValue?: boolean) => {
        const isDifferent = compareValue !== undefined && value !== compareValue;
        return (
            <tr key={key} className={`border-b border-slate-100 hover:bg-slate-50 ${isDifferent ? 'bg-yellow-50' : ''}`}>
                <td className="px-4 py-2 font-mono text-sm text-slate-700">{key}</td>
                <td className="px-4 py-2 text-center">
                    {value ? <Check size={16} className="text-green-600 inline" /> : <X size={16} className="text-slate-400 inline" />}
                </td>
                {compareValue !== undefined && (
                    <td className="px-4 py-2 text-center">
                        {compareValue ? <Check size={16} className="text-green-600 inline" /> : <X size={16} className="text-slate-400 inline" />}
                    </td>
                )}
            </tr>
        );
    };

    const renderPermissionSection = (
        title: string,
        sectionKey: string,
        permissions: Record<string, boolean> | undefined,
        comparePerms: Record<string, boolean> | undefined
    ) => {
        const isExpanded = expandedSections.has(sectionKey);
        const allKeys = new Set([
            ...Object.keys(permissions || {}),
            ...Object.keys(comparePerms || {})
        ]);
        const sortedKeys = Array.from(allKeys).sort();
        const grantedCount = Object.values(permissions || {}).filter(v => v).length;

        return (
            <div className="mb-6">
                <button
                    onClick={() => toggleSection(sectionKey)}
                    className="flex items-center justify-between w-full p-3 bg-slate-100 rounded-lg hover:bg-slate-200 transition-colors"
                >
                    <div className="flex items-center gap-2">
                        {isExpanded ? <ChevronDown size={18} /> : <ChevronRight size={18} />}
                        <span className="font-semibold text-slate-800">{title}</span>
                        <span className="text-sm text-slate-500">({grantedCount}/{sortedKeys.length} granted)</span>
                    </div>
                </button>
                {isExpanded && sortedKeys.length > 0 && (
                    <div className="mt-2 border border-slate-200 rounded-lg overflow-hidden">
                        <table className="w-full text-sm">
                            <thead className="bg-slate-50 border-b border-slate-200">
                                <tr>
                                    <th className="px-4 py-2 text-left font-semibold text-slate-700">Permission</th>
                                    <th className="px-4 py-2 text-center font-semibold text-slate-700 w-24">
                                        {selectedUser?.name || 'User'}
                                    </th>
                                    {compareUser && (
                                        <th className="px-4 py-2 text-center font-semibold text-slate-700 w-24">
                                            {compareUser.name}
                                        </th>
                                    )}
                                </tr>
                            </thead>
                            <tbody>
                                {sortedKeys.map(key => renderPermissionRow(
                                    key,
                                    permissions?.[key] ?? false,
                                    comparePerms ? (comparePerms[key] ?? false) : undefined
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
                {isExpanded && sortedKeys.length === 0 && (
                    <div className="mt-2 p-4 text-center text-slate-500 bg-slate-50 rounded-lg">
                        No permissions in this category
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className="max-w-7xl mx-auto p-6">
            {/* Header */}
            <div className="flex items-center justify-between mb-8">
                <div className="flex items-center gap-4">
                    <div className="p-3 bg-indigo-100 rounded-lg">
                        <Users className="text-indigo-600" size={32} />
                    </div>
                    <div>
                        <h1 className="text-2xl font-bold text-slate-800">Permission Analyzer</h1>
                        <p className="text-slate-500">View and compare effective permissions for users.</p>
                    </div>
                </div>
                {selectedUser && (
                    <button
                        onClick={handleRefresh}
                        disabled={loading}
                        className="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-medium shadow-sm transition-colors disabled:opacity-50"
                    >
                        <RefreshCw size={18} className={loading ? 'animate-spin' : ''} />
                        Refresh
                    </button>
                )}
            </div>

            {/* Search Section */}
            <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6 mb-6">
                <h3 className="font-semibold text-slate-800 mb-3 flex items-center gap-2">
                    <Search size={18} />
                    Search Users
                </h3>
                <div className="flex gap-3">
                    <div className="relative flex-1">
                        <input
                            type="text"
                            placeholder="Search by name or email..."
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            onKeyDown={(e) => e.key === 'Enter' && searchUsers()}
                            className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500"
                        />
                    </div>
                    <button
                        onClick={searchUsers}
                        disabled={searching || !searchQuery.trim()}
                        className="px-4 py-2 bg-slate-700 text-white rounded-lg hover:bg-slate-800 transition-colors disabled:opacity-50"
                    >
                        {searching ? 'Searching...' : 'Search'}
                    </button>
                </div>

                {searchResults.length > 0 && (
                    <div className="mt-4 border border-slate-200 rounded-lg divide-y divide-slate-100">
                        {searchResults.map(user => (
                            <div key={user.id} className="p-3 flex items-center justify-between hover:bg-slate-50">
                                <div>
                                    <div className="font-medium text-slate-800">{user.name}</div>
                                    <div className="text-sm text-slate-500">{user.email} • {user.profile_name}</div>
                                </div>
                                <div className="flex gap-2">
                                    <button
                                        onClick={() => handleSelectUser(user, false)}
                                        disabled={loading}
                                        className="px-3 py-1 text-sm bg-indigo-100 text-indigo-700 rounded hover:bg-indigo-200 disabled:opacity-50"
                                    >
                                        Analyze
                                    </button>
                                    {selectedUser && (
                                        <button
                                            onClick={() => handleSelectUser(user, true)}
                                            disabled={loading}
                                            className="px-3 py-1 text-sm bg-amber-100 text-amber-700 rounded hover:bg-amber-200 disabled:opacity-50"
                                        >
                                            Compare
                                        </button>
                                    )}
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>

            {/* Selected Users Info */}
            {selectedUser && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div className="bg-indigo-50 rounded-xl border border-indigo-200 p-4">
                        <div className="flex items-center gap-3">
                            <Shield className="text-indigo-600" size={24} />
                            <div>
                                <div className="font-semibold text-slate-800">{selectedUser.name}</div>
                                <div className="text-sm text-slate-600">{selectedUser.email}</div>
                                <div className="text-xs text-slate-500">Profile: {selectedUser.profile_name}</div>
                            </div>
                        </div>
                    </div>
                    {compareUser ? (
                        <div className="bg-amber-50 rounded-xl border border-amber-200 p-4">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <Shield className="text-amber-600" size={24} />
                                    <div>
                                        <div className="font-semibold text-slate-800">{compareUser.name}</div>
                                        <div className="text-sm text-slate-600">{compareUser.email}</div>
                                        <div className="text-xs text-slate-500">Profile: {compareUser.profile_name}</div>
                                    </div>
                                </div>
                                <button onClick={clearCompare} className="text-slate-500 hover:text-slate-700" aria-label="Remove comparison user">
                                    <X size={18} />
                                </button>
                            </div>
                        </div>
                    ) : (
                        <div className="bg-slate-50 rounded-xl border border-dashed border-slate-300 p-4 flex items-center justify-center text-slate-400">
                            <Info size={18} className="mr-2" />
                            Search and select another user to compare
                        </div>
                    )}
                </div>
            )}

            {/* Permission Results */}
            {loading ? (
                <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
                    <RecordListSkeleton rows={8} columns={3} />
                </div>
            ) : selectedUser && userPermissions ? (
                <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
                    {renderPermissionSection('System Permissions', 'system', userPermissions.system_permissions, comparePermissions?.system_permissions)}
                    {renderPermissionSection('Custom Permissions', 'custom', userPermissions.custom_permissions, comparePermissions?.custom_permissions)}

                    {compareUser && (
                        <div className="mt-4 p-3 bg-yellow-50 rounded-lg flex items-center gap-2 text-yellow-800">
                            <AlertCircle size={18} />
                            <span className="text-sm">Highlighted rows indicate differences between users.</span>
                        </div>
                    )}
                </div>
            ) : !selectedUser && (
                <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-12 text-center">
                    <Shield className="mx-auto text-slate-300" size={48} />
                    <h3 className="mt-4 text-lg font-semibold text-slate-700">No User Selected</h3>
                    <p className="mt-2 text-slate-500">Search for a user to view their effective permissions.</p>
                </div>
            )}
        </div>
    );
};
