import { Head, Link, router } from '@inertiajs/react';
import { RotateCcw, ShieldCheck, UserPlus, UserRound } from 'lucide-react';
import { useState, type FormEvent } from 'react';
import { EmptyState, PageHeader } from '@/components/crm/page-header';
import { NativeSelect } from '@/components/crm/native-select';
import { StatusLabel, StatusPill } from '@/components/crm/status-badge';
import { toneClasses } from '@/components/crm/tone';
import { SearchInput, TableCard, FilterBar, DataPagination } from '@/components/crm/toolbar';
import { Button } from '@/components/ui/button';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { formatDateTime, formatRelative, initials } from '@/lib/format';
import { cn } from '@/lib/utils';
import { index as rolesIndex } from '@/routes/roles';
import {
    create as userCreate,
    destroy as userDestroy,
    edit as userEdit,
    index as usersIndex,
} from '@/routes/users';
import type { Option, Paginated, UserSummary } from '@/types';

type Props = {
    users: Paginated<UserSummary>;
    filters: {
        search: string | null;
        role: string | null;
        status: string | null;
    };
    filterOptions: {
        roles: string[];
        statuses: Option[];
    };
    can: {
        create: boolean;
        manageRoles: boolean;
    };
};

/**
 * Role colours so the same role reads the same way everywhere in the app.
 */
const roleTones: Record<string, string> = {
    'Super Admin': 'violet',
    'Managing Director': 'teal',
    Admin: 'blue',
    'Admin Support': 'indigo',
    'Operations Manager': 'amber',
    'Sales Manager': 'cyan',
    Sales: 'emerald',
    Installer: 'orange',
    Warehouse: 'slate',
    Finance: 'green',
};

function roleTone(role: string): string {
    return roleTones[role] ?? 'slate';
}

const headClass =
    '[&_th]:text-[11px] [&_th]:font-semibold [&_th]:tracking-wide [&_th]:uppercase';

export default function UsersIndex({ users, filters, filterOptions, can }: Props) {
    const [search, setSearch] = useState(filters.search ?? '');
    const [role, setRole] = useState(filters.role ?? '');
    const [status, setStatus] = useState(filters.status ?? 'all');

    const applyFilters = (event: FormEvent): void => {
        event.preventDefault();

        const params: Record<string, string> = {};

        if (search.trim()) {
            params.search = search.trim();
        }

        if (role) {
            params.role = role;
        }

        if (status && status !== 'all') {
            params.status = status;
        }

        router.get(usersIndex().url, params, {
            preserveState: true,
            preserveScroll: true,
            replace: true,
        });
    };

    const resetFilters = (): void => {
        setSearch('');
        setRole('');
        setStatus('all');
        router.get(usersIndex().url, {}, { preserveScroll: true, replace: true });
    };

    const removeStaff = (user: UserSummary): void => {
        const confirmed = window.confirm(
            `Hide ${user.name}? Their sign-in stops immediately and everything they did stays on record. Nothing is destroyed — a Super Admin can restore the account from the recycle bin.`,
        );

        if (confirmed) {
            router.delete(userDestroy(user.id).url, { preserveScroll: true });
        }
    };

    const activeCount = users.data.filter((user) => user.is_active).length;

    return (
        <>
            <Head title="Staff" />

            <PageHeader
                eyebrow={
                    <>
                        <span>{users.total} staff accounts</span>
                        <span aria-hidden className="text-muted-foreground/50">
                            ·
                        </span>
                        <span>{activeCount} active on this page</span>
                    </>
                }
                title="Staff"
                description="Everyone who can sign in, and the role that decides what they can do."
                actions={
                    <>
                        {can.manageRoles ? (
                            <Button variant="outline" size="sm" asChild>
                                <Link href={rolesIndex()}>
                                    <ShieldCheck className="size-4" />
                                    Roles and permissions
                                </Link>
                            </Button>
                        ) : null}
                        {can.create ? (
                            <Button size="sm" asChild>
                                <Link href={userCreate()}>
                                    <UserPlus className="size-4" />
                                    Add staff
                                </Link>
                            </Button>
                        ) : null}
                    </>
                }
            />

            <form onSubmit={applyFilters}>
                <FilterBar
                    actions={
                        <>
                            <Button type="submit" size="sm">
                                Filter
                            </Button>
                            <Button
                                type="button"
                                size="sm"
                                variant="ghost"
                                onClick={resetFilters}
                            >
                                <RotateCcw className="size-4" />
                                Reset
                            </Button>
                        </>
                    }
                >
                    <div className="flex min-w-[16rem] flex-1 flex-col gap-1">
                        <span className="crm-label">Search</span>
                        <SearchInput
                            value={search}
                            onChange={setSearch}
                            placeholder="Name, email, employee code or job title"
                        />
                    </div>

                    <label className="flex w-full flex-col gap-1 sm:w-52">
                        <span className="crm-label">Role</span>
                        <NativeSelect
                            value={role}
                            onChange={(event) => setRole(event.target.value)}
                        >
                            <option value="">Any role</option>
                            {filterOptions.roles.map((option) => (
                                <option key={option} value={option}>
                                    {option}
                                </option>
                            ))}
                        </NativeSelect>
                    </label>

                    <label className="flex w-full flex-col gap-1 sm:w-40">
                        <span className="crm-label">Status</span>
                        <NativeSelect
                            value={status}
                            onChange={(event) => setStatus(event.target.value)}
                        >
                            {filterOptions.statuses.map((option) => (
                                <option key={option.value} value={option.value}>
                                    {option.label}
                                </option>
                            ))}
                        </NativeSelect>
                    </label>
                </FilterBar>
            </form>

            {users.data.length === 0 ? (
                <EmptyState
                    icon={UserRound}
                    title="No staff match these filters"
                    description="Try a different search term, role or status."
                />
            ) : (
                <TableCard>
                    <Table>
                        <TableHeader className={headClass}>
                            <TableRow>
                                <TableHead>Person</TableHead>
                                <TableHead>Role</TableHead>
                                <TableHead>Position</TableHead>
                                <TableHead>Contact</TableHead>
                                <TableHead>Status</TableHead>
                                <TableHead>Last sign in</TableHead>
                                <TableHead className="text-right">Actions</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {users.data.map((user) => {
                                const primary =
                                    user.primary_role ?? user.roles[0] ?? '';
                                const roleClasses = toneClasses(
                                    roleTone(primary),
                                );

                                return (
                                    <TableRow key={user.id}>
                                        <TableCell>
                                            <div className="flex items-center gap-3">
                                                <span
                                                    aria-hidden
                                                    className={cn(
                                                        'flex size-9 shrink-0 items-center justify-center rounded-full text-xs font-semibold',
                                                        roleClasses.soft,
                                                    )}
                                                >
                                                    {initials(user.name)}
                                                </span>
                                                <div className="flex min-w-0 flex-col">
                                                    <Link
                                                        href={userEdit(user.id)}
                                                        className="truncate text-sm font-medium hover:underline"
                                                    >
                                                        {user.name}
                                                    </Link>
                                                    <span className="text-muted-foreground truncate text-xs">
                                                        {user.email}
                                                    </span>
                                                </div>
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <div className="flex flex-wrap gap-1">
                                                {user.roles.length === 0 ? (
                                                    <span className="text-muted-foreground text-xs">
                                                        No role
                                                    </span>
                                                ) : (
                                                    user.roles.map((roleName) => (
                                                        <StatusPill
                                                            key={roleName}
                                                            tone={roleTone(roleName)}
                                                            className="text-[11px]"
                                                        >
                                                            {roleName}
                                                        </StatusPill>
                                                    ))
                                                )}
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <div className="flex flex-col">
                                                <span className="text-sm">
                                                    {user.job_title ?? '—'}
                                                </span>
                                                {user.department ? (
                                                    <span className="text-muted-foreground text-xs">
                                                        {user.department}
                                                    </span>
                                                ) : null}
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <div className="flex flex-col text-xs">
                                                <span className="crm-num">
                                                    {user.phone ?? '—'}
                                                </span>
                                                {user.employee_code ? (
                                                    <span className="text-muted-foreground font-mono">
                                                        {user.employee_code}
                                                    </span>
                                                ) : null}
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <StatusLabel
                                                tone={user.is_active ? 'success' : 'slate'}
                                                quiet={!user.is_active}
                                            >
                                                {user.is_active
                                                    ? 'Active'
                                                    : 'Deactivated'}
                                            </StatusLabel>
                                        </TableCell>
                                        <TableCell className="text-muted-foreground text-xs">
                                            <span
                                                title={formatDateTime(
                                                    user.last_login_at,
                                                )}
                                            >
                                                {user.last_login_at
                                                    ? formatRelative(
                                                          user.last_login_at,
                                                      )
                                                    : 'Never'}
                                            </span>
                                        </TableCell>
                                        <TableCell>
                                            <div className="flex items-center justify-end gap-1.5">
                                                <Button
                                                    variant="outline"
                                                    size="sm"
                                                    asChild
                                                >
                                                    <Link href={userEdit(user.id)}>
                                                        Edit
                                                    </Link>
                                                </Button>
                                                {can.create ? (
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        className="text-muted-foreground hover:text-destructive"
                                                        onClick={() =>
                                                            removeStaff(user)
                                                        }
                                                    >
                                                        Hide
                                                    </Button>
                                                ) : null}
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                );
                            })}
                        </TableBody>
                    </Table>

                    <DataPagination page={users} noun="staff" />
                </TableCard>
            )}
        </>
    );
}

UsersIndex.layout = {
    breadcrumbs: [
        {
            title: 'Staff',
            href: usersIndex(),
        },
    ],
};
