import React, { useState, useMemo } from 'react';
import { Users, Plus, Edit, Trash2, Shield } from 'lucide-react';
import { dataAPI } from '../infrastructure/api/data';
import { SYSTEM_TABLE_NAMES } from '@nexuscrm/generated-schema';
import { COMMON_FIELDS } from '../core/constants';
import { ConfirmationModal } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { ProfileFormModal } from '../features/admin/components/ProfileFormModal';
import { PermissionEditorModal, PermissionEntity } from '../features/security/components/PermissionEditorModal';
import { PowerList, PowerListColumn } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { Tooltip } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { Badge } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { useErrorToast, useSuccessToast } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { formatApiError } from '@nexuscrm/host-sdk';
import { useProfiles } from '../features/users/userQueries';
import type { Profile } from '../types';

const ProfileManager: React.FC = () => {
    const errorToast = useErrorToast();
    const successToast = useSuccessToast();

    const { data: profiles = [], isLoading: loading, error: queryError } = useProfiles();

    const [showModal, setShowModal] = useState(false);
    const [editingProfile, setEditingProfile] = useState<Profile | null>(null);
    const [saving, setSaving] = useState(false);

    // Permission editor state
    const [editingPermissions, setEditingPermissions] = useState<PermissionEntity | null>(null);

    // Delete state
    const [deleteModalOpen, setDeleteModalOpen] = useState(false);
    const [profileToDelete, setProfileToDelete] = useState<Profile | null>(null);

    const handleCreate = () => {
        setEditingProfile(null);
        setShowModal(true);
    };

    const handleEdit = (profile: Profile) => {
        setEditingProfile(profile);
        setShowModal(true);
    };

    const handleDelete = (profile: Profile) => {
        if (profile.IsSystem) {
            errorToast('Cannot delete system profiles');
            return;
        }
        setProfileToDelete(profile);
        setDeleteModalOpen(true);
    };

    const confirmDelete = async () => {
        if (!profileToDelete) return;
        try {
            await dataAPI.deleteRecord(SYSTEM_TABLE_NAMES.PROFILE, profileToDelete[COMMON_FIELDS.ID] as string);
            successToast('Profile deleted');
            setDeleteModalOpen(false);
            setProfileToDelete(null);
        } catch (err: unknown) {
            errorToast(`Failed to delete profile: ${formatApiError(err).message}`);
        }
    };

    const handleSave = async (formData: { Name: string; Description: string }) => {
        setSaving(true);
        try {
            if (editingProfile) {
                await dataAPI.updateRecord(SYSTEM_TABLE_NAMES.PROFILE, editingProfile[COMMON_FIELDS.ID] as string, formData);
                successToast('Profile updated');
            } else {
                await dataAPI.createRecord(SYSTEM_TABLE_NAMES.PROFILE, formData);
                successToast('Profile created');
            }
            setShowModal(false);
        } catch (err: unknown) {
            errorToast(`Failed to save profile: ${formatApiError(err).message}`);
        } finally {
            setSaving(false);
        }
    };

    const columns: PowerListColumn<Profile>[] = useMemo(() => [
        {
            key: 'Name', label: 'Profile Name', minWidth: '180px',
            render: (val, profile) => (
                <div className="flex items-center gap-3">
                    <div className="p-2 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                        {profile.IsSystem
                            ? <Shield className="w-4 h-4 text-purple-600 dark:text-purple-400" />
                            : <Users className="w-4 h-4 text-blue-600 dark:text-blue-400" />
                        }
                    </div>
                    <span className="font-medium text-gray-900 dark:text-white">{val ? String(val) : '—'}</span>
                </div>
            ),
        },
        {
            key: 'Description', label: 'Description', minWidth: '200px',
            render: (val) => (
                <span className="text-gray-500 dark:text-gray-400 truncate block max-w-md">
                    {val ? String(val) : '—'}
                </span>
            ),
        },
        {
            key: 'IsSystem', label: 'Type', width: '120px',
            render: (val) => val ? (
                <Badge variant="purple">System</Badge>
            ) : (
                <Badge variant="neutral">Custom</Badge>
            ),
        },
    ], []);

    const renderActions = (profile: Profile) => (
        <div className="flex items-center justify-end gap-1">
            <Tooltip content="Permissions" position="top">
                <button
                    onClick={() => setEditingPermissions({
                        id: profile[COMMON_FIELDS.ID] as string,
                        name: profile.Name,
                        type: 'profile',
                    })}
                    className="p-1.5 rounded-lg hover:bg-purple-50 dark:hover:bg-purple-900/20 text-purple-600 dark:text-purple-400 transition-colors"
                >
                    <Shield className="w-4 h-4" />
                </button>
            </Tooltip>
            <Tooltip content="Edit" position="top">
                <button
                    onClick={() => handleEdit(profile)}
                    className="p-1.5 rounded-lg hover:bg-blue-50 dark:hover:bg-blue-900/20 text-blue-600 dark:text-blue-400 transition-colors"
                >
                    <Edit className="w-4 h-4" />
                </button>
            </Tooltip>
            <Tooltip content={profile.IsSystem ? 'Cannot delete system profile' : 'Delete'} position="top">
                <button
                    onClick={() => handleDelete(profile)}
                    disabled={profile.IsSystem}
                    className={`p-1.5 rounded-lg transition-colors ${profile.IsSystem
                        ? 'text-gray-300 cursor-not-allowed dark:text-gray-600'
                        : 'hover:bg-red-50 dark:hover:bg-red-900/20 text-red-600 dark:text-red-400'}`}
                >
                    <Trash2 className="w-4 h-4" />
                </button>
            </Tooltip>
        </div>
    );

    return (
        <div className="p-6 max-w-7xl mx-auto">
            {/* Header */}
            <div className="flex items-center justify-between mb-6">
                <div className="flex items-center gap-3">
                    <div className="p-2 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl shadow-lg">
                        <Users className="w-6 h-6 text-white" />
                    </div>
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Profiles</h1>
                        <p className="text-sm text-gray-500 dark:text-gray-400">
                            Manage user profiles and access levels
                        </p>
                    </div>
                </div>
                <button
                    onClick={handleCreate}
                    className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-500 to-indigo-600
                    text-white rounded-lg hover:from-blue-600 hover:to-indigo-700 transition-all shadow-md"
                >
                    <Plus className="w-4 h-4" />
                    New Profile
                </button>
            </div>

            {/* Error */}
            {queryError && (
                <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
                    Failed to load profiles
                </div>
            )}

            {/* PowerList */}
            <PowerList<Profile>
                data={profiles}
                columns={columns}
                loading={loading}
                rowKey={(p) => p[COMMON_FIELDS.ID] as string}
                searchable
                searchPlaceholder="Search profiles..."
                defaultSort={{ key: 'Name', direction: 'asc' }}
                emptyIcon={<Users className="w-12 h-12" />}
                emptyTitle="No Profiles Found"
                emptyMessage="Get started by creating a new profile."
                emptyAction={{ label: 'Create Profile', onClick: handleCreate }}
                actions={renderActions}
                ariaLabel="Profiles list"
            />

            {/* Create/Edit Modal */}
            <ProfileFormModal
                isOpen={showModal}
                onClose={() => setShowModal(false)}
                onSave={handleSave}
                initialData={editingProfile ? { Name: editingProfile.Name, Description: editingProfile.Description || '' } : undefined}
                submitting={saving}
            />

            <ConfirmationModal
                isOpen={deleteModalOpen}
                onClose={() => setDeleteModalOpen(false)}
                onConfirm={confirmDelete}
                title="Delete Profile"
                message={`Are you sure you want to delete "${profileToDelete?.Name}"? Users assigned to this profile may lose access.`}
                confirmLabel="Delete"
                variant="danger"
            />

            {/* Permission Editor Modal */}
            {editingPermissions && (
                <PermissionEditorModal
                    entity={editingPermissions}
                    onClose={() => setEditingPermissions(null)}
                    onSave={() => {
                        successToast('Permissions saved successfully');
                    }}
                />
            )}
        </div>
    );
};

export default ProfileManager;
