import { Head, Link, router } from '@inertiajs/react';
import {
    BadgeCheck,
    ChevronDown,
    Eye,
    Lock,
    Pencil,
    UserPlus,
    Users,
} from 'lucide-react';
import DataTable from '@/components/data-table';
import type { DataTableColumn } from '@/components/data-table';
import MemberPage from '@/components/member/member-page';
import StatusBadge from '@/components/member/status-badge';
import type { BadgeTone } from '@/components/member/status-badge';
import { useInitials } from '@/hooks/use-initials';
import { formatDate } from '@/lib/format';
import { create, edit, show } from '@/routes/admin/users';
import type { Paginated, SelectOption } from '@/types';

export type UserRow = {
    id: number;
    memberId: string;
    membershipStatus: string;
    membershipStatusLabel: string;
    name: string;
    email: string;
    phone: string | null;
    kycStatus: string;
    kycStatusLabel: string;
    roles: string[];
    branch: string | null;
    joinedAt: string | null;
    canEdit: boolean;
};

const kycTones: Record<string, BadgeTone> = {
    verified: 'success',
    pending: 'pending',
    rejected: 'failed',
    unverified: 'neutral',
};

export type UserDirectoryProps = {
    users: Paginated<UserRow>;
    roles: string[];
    roleFilter: string;
    branches: SelectOption[];
    branchFilter: string;
    canManage: boolean;
};

/**
 * The Members or Staff list: the same table, with the columns, filters and
 * wording that suit each.
 */
export default function UserDirectory({
    kind,
    users,
    roles,
    roleFilter,
    branches,
    branchFilter,
    canManage,
}: UserDirectoryProps & { kind: 'members' | 'staff' }) {
    const getInitials = useInitials();
    const isStaff = kind === 'staff';

    const filterBy = (name: 'role' | 'branch', value: string) => {
        const query = new URLSearchParams(window.location.search);

        if (value) {
            query.set(name, value);
        } else {
            query.delete(name);
        }

        query.delete('page');
        router.get(
            `${window.location.pathname}${query.toString() ? `?${query}` : ''}`,
            {},
            { preserveState: true, preserveScroll: true, replace: true },
        );
    };

    const columns: DataTableColumn<UserRow>[] = [
        {
            key: 'name',
            header: isStaff ? 'Staff member' : 'Member',
            sortable: true,
            cell: (user) => (
                <Link
                    href={show(user.id)}
                    className="group flex min-w-0 items-center gap-3"
                >
                    <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-brand text-xs font-semibold text-white">
                        {getInitials(user.name)}
                    </span>
                    <span className="min-w-0">
                        <span className="block truncate font-semibold text-ink group-hover:text-brand">
                            {user.name}
                        </span>
                        <span className="block truncate text-xs text-ink-400">
                            <span className="font-mono">{user.memberId}</span> ·{' '}
                            {user.email}
                        </span>
                    </span>
                </Link>
            ),
        },
        {
            key: 'phone',
            header: 'Phone',
            hideOnMobile: true,
            className: 'text-xs whitespace-nowrap text-ink-500',
            cell: (user) => user.phone ?? '—',
        },
        ...(isStaff
            ? [
                  {
                      key: 'roles',
                      header: 'Role',
                      cell: (user) =>
                          user.roles.length > 0 ? (
                              <span className="flex flex-wrap gap-1">
                                  {user.roles.map((role) => (
                                      <StatusBadge key={role} tone="info">
                                          {role}
                                      </StatusBadge>
                                  ))}
                              </span>
                          ) : (
                              <span className="text-xs text-ink-400">
                                  Member
                              </span>
                          ),
                  } satisfies DataTableColumn<UserRow>,
              ]
            : []),
        {
            key: 'branch',
            header: 'Branch',
            hideOnMobile: true,
            className: 'font-mono text-xs whitespace-nowrap text-ink-500',
            cell: (user) => user.branch ?? '—',
        },
        ...(isStaff
            ? []
            : ([
                  {
                      key: 'membershipStatus',
                      header: 'Membership',
                      hideOnMobile: true,
                      cell: (user) => (
                          <StatusBadge
                              tone={
                                  user.membershipStatus === 'active'
                                      ? 'success'
                                      : user.membershipStatus === 'suspended'
                                        ? 'pending'
                                        : 'failed'
                              }
                          >
                              {user.membershipStatusLabel}
                          </StatusBadge>
                      ),
                  },
                  {
                      key: 'kycStatus',
                      header: 'Verification',
                      sortable: true,
                      hideOnMobile: true,
                      cell: (user) => (
                          <StatusBadge
                              tone={kycTones[user.kycStatus] ?? 'neutral'}
                          >
                              {user.kycStatusLabel}
                          </StatusBadge>
                      ),
                  },
              ] satisfies DataTableColumn<UserRow>[])),
        {
            key: 'joinedAt',
            header: 'Joined',
            sortable: true,
            hideOnMobile: true,
            className: 'text-xs whitespace-nowrap text-ink-500',
            cell: (user) => formatDate(user.joinedAt),
        },
        {
            key: 'actions',
            header: <span className="sr-only">Actions</span>,
            align: 'right',
            className: 'w-px whitespace-nowrap',
            cell: (user) => (
                <span className="inline-flex items-center gap-0.5">
                    <Link
                        href={show(user.id)}
                        className="inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-sm font-semibold text-ink-500 hover:bg-surface-100 hover:text-ink"
                        aria-label={`View ${user.name}`}
                    >
                        <Eye className="size-3.5" />
                        View
                    </Link>
                    {user.canEdit ? (
                        <Link
                            href={edit(user.id)}
                            className="inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-sm font-semibold text-brand hover:bg-brand-faint"
                            aria-label={`Change role for ${user.name}`}
                        >
                            {isStaff ? (
                                <Pencil className="size-3.5" />
                            ) : (
                                <BadgeCheck className="size-3.5" />
                            )}
                            {isStaff ? 'Role' : 'Make staff'}
                        </Link>
                    ) : (
                        canManage && (
                            <span
                                className="inline-flex items-center px-2.5 text-ink-300"
                                title="You cannot change this user's role"
                            >
                                <Lock className="size-3.5" />
                            </span>
                        )
                    )}
                </span>
            ),
        },
    ];

    return (
        <>
            <Head title={isStaff ? 'Staff' : 'Members'} />

            <MemberPage
                title={isStaff ? 'Staff' : 'Members'}
                description={
                    isStaff
                        ? 'Everyone who works in the system, with their role and branch.'
                        : 'Everyone who saves and borrows with the cooperative.'
                }
                actions={
                    canManage && (
                        <Link
                            href={create()}
                            className="inline-flex items-center gap-1.5 rounded-full bg-brand px-3.5 py-1.5 text-sm font-semibold text-white hover:bg-brand-hover"
                        >
                            <UserPlus className="size-4" />
                            {isStaff ? 'Add staff' : 'Register member'}
                        </Link>
                    )
                }
            >
                <DataTable
                    title={isStaff ? 'All staff' : 'All members'}
                    description={`${users.total} ${isStaff ? (users.total === 1 ? 'staff member' : 'staff members') : users.total === 1 ? 'member' : 'members'}`}
                    columns={columns}
                    page={users}
                    getRowId={(user) => user.id}
                    searchable
                    searchPlaceholder="Search name, email, phone or ADS-ID"
                    defaultSort={{ key: 'joinedAt', direction: 'desc' }}
                    toolbar={
                        <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
                            {isStaff && (
                                <div className="relative w-full sm:w-auto">
                                    <select
                                        value={roleFilter}
                                        onChange={(event) =>
                                            filterBy('role', event.target.value)
                                        }
                                        aria-label="Filter by role"
                                        className="h-9 w-full appearance-none rounded-md border border-input bg-white pr-8 pl-3 text-sm text-ink shadow-xs outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15 sm:w-48"
                                    >
                                        <option value="">All roles</option>
                                        {roles.map((role) => (
                                            <option key={role} value={role}>
                                                {role}
                                            </option>
                                        ))}
                                    </select>
                                    <ChevronDown className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-ink-400" />
                                </div>
                            )}
                            {branches.length > 0 && (
                                <div className="relative w-full sm:w-auto">
                                    <select
                                        value={branchFilter}
                                        onChange={(event) =>
                                            filterBy(
                                                'branch',
                                                event.target.value,
                                            )
                                        }
                                        aria-label="Filter by branch"
                                        className="h-9 w-full appearance-none rounded-md border border-input bg-white pr-8 pl-3 text-sm text-ink shadow-xs outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15 sm:w-48"
                                    >
                                        <option value="">All branches</option>
                                        <option value="none">No branch</option>
                                        {branches.map((branch) => (
                                            <option
                                                key={branch.value}
                                                value={branch.value}
                                            >
                                                {branch.label}
                                            </option>
                                        ))}
                                    </select>
                                    <ChevronDown className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-ink-400" />
                                </div>
                            )}
                        </div>
                    }
                    empty={{
                        icon: Users,
                        title: isStaff ? 'No staff found' : 'No members found',
                        description: 'Try another filter or clear the search.',
                    }}
                />
            </MemberPage>
        </>
    );
}
