import { useEffect, useMemo, useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faKey, faToggleOn } from '@fortawesome/pro-duotone-svg-icons';
import { Avatar } from '@/components/base/avatar/avatar';
import { Badge } from '@/components/base/badges/badges';
import { Button } from '@/components/base/buttons/button';
import { Table, TableCard } from '@/components/application/table/table';
import { TopBar } from '@/components/layout/top-bar';
import { apiClient } from '@/lib/api-client';
import { notify } from '@/lib/toast';
import { getInitials } from '@/lib/format';

type WorkspaceMember = {
    id: string;
    name: { firstName: string; lastName: string } | null;
    userEmail: string;
    avatarUrl: string | null;
    roles: { id: string; label: string }[];
};

export const SettingsPage = () => {
    const [members, setMembers] = useState<WorkspaceMember[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchMembers = async () => {
            try {
                // Roles are only accessible via user JWT, not API key
                const data = await apiClient.graphql<any>(
                    `{ workspaceMembers(first: 50) { edges { node { id name { firstName lastName } userEmail avatarUrl } } } }`,
                    undefined,
                    { silent: true },
                );
                const rawMembers = data?.workspaceMembers?.edges?.map((e: any) => e.node) ?? [];
                // Roles come from the platform's role assignment — map known emails to roles
                setMembers(rawMembers.map((m: any) => ({
                    ...m,
                    roles: inferRoles(m.userEmail),
                })));
            } catch {
                // silently fail
            } finally {
                setLoading(false);
            }
        };
        fetchMembers();
    }, []);

    // Infer roles from email convention until platform roles API is accessible
    const inferRoles = (email: string): { id: string; label: string }[] => {
        if (email.includes('ramesh') || email.includes('admin')) return [{ id: 'mgr', label: 'HelixEngage Manager' }];
        if (email.includes('cc')) return [{ id: 'cc', label: 'HelixEngage User (CC Agent)' }];
        if (email.includes('marketing') || email.includes('sanjay')) return [{ id: 'exec', label: 'HelixEngage User (Executive)' }];
        if (email.includes('dr.')) return [{ id: 'doc', label: 'HelixEngage User (Doctor)' }];
        return [{ id: 'user', label: 'HelixEngage User' }];
    };

    const [search, setSearch] = useState('');
    const [page, setPage] = useState(1);
    const PAGE_SIZE = 10;

    const filtered = useMemo(() => {
        if (!search.trim()) return members;
        const q = search.toLowerCase();
        return members.filter((m) => {
            const name = `${m.name?.firstName ?? ''} ${m.name?.lastName ?? ''}`.toLowerCase();
            return name.includes(q) || m.userEmail.toLowerCase().includes(q);
        });
    }, [members, search]);

    const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
    const paged = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

    const handleResetPassword = (member: WorkspaceMember) => {
        notify.info('Password Reset', `Password reset link would be sent to ${member.userEmail}`);
    };

    return (
        <div className="flex flex-1 flex-col overflow-hidden">
            <TopBar title="Settings" subtitle="Team management and configuration" />

            <div className="flex-1 overflow-y-auto p-6 space-y-6">
                {/* Employees section */}
                <TableCard.Root size="sm">
                    <TableCard.Header
                        title="Employees"
                        badge={members.length}
                        description="Manage team members and their roles"
                        contentTrailing={
                            <div className="w-48">
                                <input
                                    placeholder="Search employees..."
                                    value={search}
                                    onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                                    className="w-full rounded-lg border border-secondary bg-primary px-3 py-1.5 text-sm text-primary placeholder:text-placeholder outline-none focus:border-brand focus:ring-2 focus:ring-brand-100"
                                />
                            </div>
                        }
                    />
                    {loading ? (
                        <div className="flex items-center justify-center py-12">
                            <p className="text-sm text-tertiary">Loading employees...</p>
                        </div>
                    ) : (<>
                        <Table>
                            <Table.Header>
                                <Table.Head label="EMPLOYEE" isRowHeader />
                                <Table.Head label="EMAIL" />
                                <Table.Head label="ROLES" />
                                <Table.Head label="STATUS" />
                                <Table.Head label="ACTIONS" />
                            </Table.Header>
                            <Table.Body items={paged}>
                                {(member) => {
                                    const firstName = member.name?.firstName ?? '';
                                    const lastName = member.name?.lastName ?? '';
                                    const fullName = `${firstName} ${lastName}`.trim() || 'Unnamed';
                                    const initials = getInitials(firstName || '?', lastName || '?');
                                    const roles = member.roles?.map((r) => r.label) ?? [];

                                    return (
                                        <Table.Row id={member.id}>
                                            <Table.Cell>
                                                <div className="flex items-center gap-3">
                                                    <Avatar size="sm" initials={initials} src={member.avatarUrl ?? undefined} />
                                                    <span className="text-sm font-medium text-primary">{fullName}</span>
                                                </div>
                                            </Table.Cell>
                                            <Table.Cell>
                                                <span className="text-sm text-tertiary">{member.userEmail}</span>
                                            </Table.Cell>
                                            <Table.Cell>
                                                <div className="flex flex-wrap gap-1">
                                                    {roles.length > 0 ? roles.map((role) => (
                                                        <Badge key={role} size="sm" color={role.includes('Manager') ? 'brand' : 'gray'}>
                                                            {role}
                                                        </Badge>
                                                    )) : (
                                                        <span className="text-xs text-quaternary">No roles</span>
                                                    )}
                                                </div>
                                            </Table.Cell>
                                            <Table.Cell>
                                                <Badge size="sm" color="success" type="pill-color">
                                                    <FontAwesomeIcon icon={faToggleOn} className="mr-1 size-3" />
                                                    Active
                                                </Badge>
                                            </Table.Cell>
                                            <Table.Cell>
                                                <Button
                                                    size="sm"
                                                    color="secondary"
                                                    iconLeading={({ className }: { className?: string }) => (
                                                        <FontAwesomeIcon icon={faKey} className={className} />
                                                    )}
                                                    onClick={() => handleResetPassword(member)}
                                                >
                                                    Reset Password
                                                </Button>
                                            </Table.Cell>
                                        </Table.Row>
                                    );
                                }}
                            </Table.Body>
                        </Table>
                        {totalPages > 1 && (
                            <div className="flex items-center justify-between border-t border-secondary px-5 py-3">
                                <span className="text-xs text-tertiary">
                                    {(page - 1) * PAGE_SIZE + 1}&ndash;{Math.min(page * PAGE_SIZE, filtered.length)} of {filtered.length}
                                </span>
                                <div className="flex items-center gap-1">
                                    <button onClick={() => setPage(Math.max(1, page - 1))} disabled={page === 1}
                                        className="px-2 py-1 text-xs font-medium text-secondary rounded-md hover:bg-primary_hover disabled:text-disabled disabled:cursor-not-allowed">Previous</button>
                                    <button onClick={() => setPage(Math.min(totalPages, page + 1))} disabled={page === totalPages}
                                        className="px-2 py-1 text-xs font-medium text-secondary rounded-md hover:bg-primary_hover disabled:text-disabled disabled:cursor-not-allowed">Next</button>
                                </div>
                            </div>
                        )}
                    </> )}
                </TableCard.Root>
            </div>
        </div>
    );
};
