import HeadingSmall from '@/components/heading-small';
import InputError from '@/components/input-error';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';
import { timeAgo } from '@/lib/format';
import { type SharedData } from '@/types';
import { Head, router, useForm, usePage } from '@inertiajs/react';
import { Plus, UserPlus } from 'lucide-react';
import { FormEventHandler, useState } from 'react';

interface Member {
    id: number;
    name: string;
    email: string;
    status: 'active' | 'deactivated';
    availability: string;
    last_seen_at: string | null;
    role: { id: number; key: string; name: string } | null;
    group_ids: number[];
}

interface Props {
    members: Member[];
    roles: { id: number; key: string; name: string; permissions: string[] }[];
    groups: { id: number; name: string; users_count: number }[];
    seats: number;
    [key: string]: unknown;
}

const selectClass = 'border-input bg-background h-9 rounded-md border px-2 text-sm disabled:opacity-60';

export default function Team() {
    const { members, roles, groups, seats, auth, flash } = usePage<Props & SharedData>().props;
    const assignableRoles = roles.filter((r) => r.key !== 'owner');

    const update = (member: Member, changes: Record<string, string | number | number[]>) =>
        router.patch(`/team/${member.id}`, changes, { preserveScroll: true, preserveState: true });

    return (
        <AppLayout breadcrumbs={[{ title: 'Team', href: '/team' }]}>
            <Head title="Team" />

            <div className="mx-auto w-full max-w-5xl space-y-8 px-4 py-6">
                <div className="flex flex-wrap items-end justify-between gap-4">
                    <HeadingSmall title="Team members" description={`${seats} billable ${seats === 1 ? 'seat' : 'seats'}. Light agents and billing admins are free.`} />
                    <InviteDialog roles={assignableRoles} groups={groups} />
                </div>

                {flash.success && (
                    <p className="rounded-md border border-emerald-300 bg-emerald-50 px-3 py-2 text-sm text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200">
                        {flash.success}
                    </p>
                )}

                <div className="overflow-x-auto rounded-lg border">
                    <table className="w-full text-sm">
                        <thead className="bg-muted/50 text-muted-foreground text-left text-xs">
                            <tr>
                                <th className="px-4 py-2 font-medium">Name</th>
                                <th className="px-4 py-2 font-medium">Role</th>
                                <th className="px-4 py-2 font-medium">Groups</th>
                                <th className="px-4 py-2 font-medium">Last seen</th>
                                <th className="px-4 py-2 font-medium">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            {members.map((m) => {
                                const locked = m.role?.key === 'owner' || m.id === auth.user.id;
                                return (
                                    <tr key={m.id} className="border-t align-top">
                                        <td className="px-4 py-3">
                                            <div className="font-medium">
                                                {m.name} {m.id === auth.user.id && <span className="text-muted-foreground font-normal">(you)</span>}
                                            </div>
                                            <div className="text-muted-foreground text-xs">{m.email}</div>
                                        </td>
                                        <td className="px-4 py-3">
                                            {locked ? (
                                                <Badge variant="secondary">{m.role?.name}</Badge>
                                            ) : (
                                                <select className={selectClass} value={m.role?.id} onChange={(e) => update(m, { role_id: Number(e.target.value) })} aria-label={`Role for ${m.name}`}>
                                                    {assignableRoles.map((r) => (
                                                        <option key={r.id} value={r.id}>
                                                            {r.name}
                                                        </option>
                                                    ))}
                                                </select>
                                            )}
                                        </td>
                                        <td className="px-4 py-3">
                                            <div className="flex flex-wrap gap-x-3 gap-y-1">
                                                {groups.map((g) => (
                                                    <label key={g.id} className="flex items-center gap-1 text-xs">
                                                        <input
                                                            type="checkbox"
                                                            checked={m.group_ids.includes(g.id)}
                                                            disabled={locked}
                                                            onChange={(e) =>
                                                                update(m, {
                                                                    group_ids: e.target.checked ? [...m.group_ids, g.id] : m.group_ids.filter((id) => id !== g.id),
                                                                })
                                                            }
                                                        />
                                                        {g.name}
                                                    </label>
                                                ))}
                                            </div>
                                        </td>
                                        <td className="text-muted-foreground px-4 py-3 text-xs">{m.last_seen_at ? timeAgo(m.last_seen_at) : 'Never'}</td>
                                        <td className="px-4 py-3">
                                            {locked ? (
                                                <Badge variant="outline">Active</Badge>
                                            ) : (
                                                <Button
                                                    size="sm"
                                                    variant={m.status === 'active' ? 'outline' : 'default'}
                                                    onClick={() => update(m, { status: m.status === 'active' ? 'deactivated' : 'active' })}
                                                >
                                                    {m.status === 'active' ? 'Deactivate' : 'Reactivate'}
                                                </Button>
                                            )}
                                        </td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>

                <GroupsSection groups={groups} />
            </div>
        </AppLayout>
    );
}

function InviteDialog({ roles, groups }: { roles: Props['roles']; groups: Props['groups'] }) {
    const [open, setOpen] = useState(false);
    const agentRole = roles.find((r) => r.key === 'agent');
    const form = useForm({ name: '', email: '', role_id: agentRole?.id ?? roles[0]?.id, password: '', group_ids: [] as number[] });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        form.post('/team', {
            preserveScroll: true,
            onSuccess: () => {
                form.reset();
                setOpen(false);
            },
        });
    };

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
                <Button>
                    <UserPlus className="size-4" /> Add member
                </Button>
            </DialogTrigger>
            <DialogContent>
                <form onSubmit={submit} className="space-y-4">
                    <DialogHeader>
                        <DialogTitle>Add a team member</DialogTitle>
                        <DialogDescription>Set a temporary password and share it with them. Email invitations come in a later release.</DialogDescription>
                    </DialogHeader>
                    <div className="space-y-1.5">
                        <Label htmlFor="name">Name</Label>
                        <Input id="name" required value={form.data.name} onChange={(e) => form.setData('name', e.target.value)} />
                        <InputError message={form.errors.name} />
                    </div>
                    <div className="space-y-1.5">
                        <Label htmlFor="email">Email</Label>
                        <Input id="email" type="email" required value={form.data.email} onChange={(e) => form.setData('email', e.target.value)} />
                        <InputError message={form.errors.email} />
                    </div>
                    <div className="space-y-1.5">
                        <Label htmlFor="role_id">Role</Label>
                        <select id="role_id" className={`${selectClass} w-full`} value={form.data.role_id} onChange={(e) => form.setData('role_id', Number(e.target.value))}>
                            {roles.map((r) => (
                                <option key={r.id} value={r.id}>
                                    {r.name}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div className="space-y-1.5">
                        <span className="text-sm font-medium">Groups</span>
                        <div className="flex flex-wrap gap-3">
                            {groups.map((g) => (
                                <label key={g.id} className="flex items-center gap-1.5 text-sm">
                                    <input
                                        type="checkbox"
                                        checked={form.data.group_ids.includes(g.id)}
                                        onChange={(e) =>
                                            form.setData('group_ids', e.target.checked ? [...form.data.group_ids, g.id] : form.data.group_ids.filter((id) => id !== g.id))
                                        }
                                    />
                                    {g.name}
                                </label>
                            ))}
                        </div>
                    </div>
                    <div className="space-y-1.5">
                        <Label htmlFor="password">Temporary password</Label>
                        <Input id="password" type="text" required value={form.data.password} onChange={(e) => form.setData('password', e.target.value)} />
                        <InputError message={form.errors.password} />
                    </div>
                    <DialogFooter>
                        <Button type="submit" disabled={form.processing}>
                            Add member
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}

function GroupsSection({ groups }: { groups: Props['groups'] }) {
    const { auth } = usePage<SharedData>().props;
    const form = useForm({ name: '' });

    if (!auth.user.permissions.includes('groups.manage')) return null;

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        form.post('/team/groups', { preserveScroll: true, onSuccess: () => form.reset() });
    };

    return (
        <section className="space-y-4">
            <HeadingSmall title="Groups" description="Tickets are routed to groups. Agents see tickets of their own groups." />
            <ul className="flex flex-wrap gap-2">
                {groups.map((g) => (
                    <li key={g.id} className="rounded-md border px-3 py-1.5 text-sm">
                        {g.name} <span className="text-muted-foreground">· {g.users_count}</span>
                    </li>
                ))}
            </ul>
            <form onSubmit={submit} className="flex max-w-sm items-start gap-2">
                <div className="flex-1">
                    <Input placeholder="New group name" value={form.data.name} onChange={(e) => form.setData('name', e.target.value)} aria-label="New group name" />
                    <InputError message={form.errors.name} className="mt-1" />
                </div>
                <Button type="submit" variant="outline" disabled={form.processing || !form.data.name.trim()}>
                    <Plus className="size-4" /> Add
                </Button>
            </form>
        </section>
    );
}
