import { Form, Head } from '@inertiajs/react';
import { useState } from 'react';

import HeadingSmall from '@/components/heading-small';
import { SortableHeader, useSort } from '@/components/sortable-header';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from '@/components/ui/dialog';
import { useUserTimezone } from '@/hooks/use-user-timezone';
import AppLayout from '@/layouts/app-layout';
import { formatDate } from '@/lib/format-date';
import { index, store, update, destroy } from '@/routes/admin/users';

type User = {
    id: number;
    name: string;
    email: string;
    email_verified_at: string | null;
    created_at: string;
};

type Props = {
    users: User[];
};

const breadcrumbs = [{ title: 'Users', href: index.url() }];

export default function Users({ users }: Props) {
    const timezone = useUserTimezone();
    const [createOpen, setCreateOpen] = useState(false);
    const [editingId, setEditingId] = useState<number | null>(null);
    const { sorted, sortColumn, sortDirection, toggleSort } = useSort<User>(users, 'name');

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Users" />

            <h1 className="sr-only">Users</h1>

            <div className="space-y-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <HeadingSmall
                        title="Users"
                        description="Manage user accounts for the energy market platform."
                    />

                    <Dialog open={createOpen} onOpenChange={setCreateOpen}>
                        <DialogTrigger asChild>
                            <button
                                type="button"
                                className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
                            >
                                Add user
                            </button>
                        </DialogTrigger>

                        <DialogContent className="sm:max-w-lg">
                            <DialogHeader>
                                <DialogTitle>Add user</DialogTitle>
                                <DialogDescription>
                                    Create a new user account for the platform.
                                </DialogDescription>
                            </DialogHeader>

                            <Form
                                method="post"
                                action={store.url()}
                                resetOnSuccess
                                onSuccess={() => setCreateOpen(false)}
                            >
                                {({ processing, errors }) => (
                                    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                                        <div className="flex flex-col gap-1 sm:col-span-2">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Name
                                            </label>
                                            <input
                                                name="name"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="Jane Smith"
                                            />
                                            {errors.name && (
                                                <div className="text-xs text-red-600">{errors.name}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1 sm:col-span-2">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Email
                                            </label>
                                            <input
                                                name="email"
                                                type="email"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="jane@example.com"
                                            />
                                            {errors.email && (
                                                <div className="text-xs text-red-600">{errors.email}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Password
                                            </label>
                                            <input
                                                name="password"
                                                type="password"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                            />
                                            {errors.password && (
                                                <div className="text-xs text-red-600">{errors.password}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Confirm password
                                            </label>
                                            <input
                                                name="password_confirmation"
                                                type="password"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                            />
                                        </div>

                                        <div className="flex items-end justify-end gap-3 sm:col-span-2">
                                            <button
                                                type="button"
                                                onClick={() => setCreateOpen(false)}
                                                className="rounded-md px-3 py-2 text-sm font-medium text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
                                            >
                                                Cancel
                                            </button>
                                            <button
                                                type="submit"
                                                disabled={processing}
                                                className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                                            >
                                                Add user
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </Form>
                        </DialogContent>
                    </Dialog>
                </div>

                {/* Users table */}
                <div className="overflow-hidden rounded-md border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950">
                    <div className="overflow-x-auto">
                        <table className="w-full text-left text-sm">
                            <thead className="border-b border-zinc-200 text-xs uppercase text-zinc-600 dark:border-zinc-800 dark:text-zinc-400">
                                <tr>
                                    <SortableHeader
                                        label="Name"
                                        column="name"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                    />
                                    <SortableHeader
                                        label="Email"
                                        column="email"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                    />
                                    <SortableHeader
                                        label="Verified"
                                        column="email_verified_at"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                    />
                                    <SortableHeader
                                        label="Joined"
                                        column="created_at"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                    />
                                    <th className="px-4 py-3" />
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                {sorted.map((u) => (
                                    <tr key={u.id}>
                                        <td className="px-4 py-3 font-medium">{u.name}</td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                            {u.email}
                                        </td>
                                        <td className="px-4 py-3">
                                            {u.email_verified_at ? (
                                                <span className="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800 dark:bg-green-900/30 dark:text-green-400">
                                                    Verified
                                                </span>
                                            ) : (
                                                <span className="inline-flex items-center rounded-full bg-zinc-100 px-2 py-0.5 text-xs font-medium text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400">
                                                    Unverified
                                                </span>
                                            )}
                                        </td>
                                        <td className="px-4 py-3 text-sm text-zinc-600 dark:text-zinc-400">
                                            {formatDate(u.created_at, timezone)}
                                        </td>
                                        <td className="px-4 py-3 text-right">
                                            <div className="flex items-center justify-end gap-4">
                                                <Dialog
                                                    open={editingId === u.id}
                                                    onOpenChange={(open) => setEditingId(open ? u.id : null)}
                                                >
                                                    <DialogTrigger asChild>
                                                        <button
                                                            type="button"
                                                            className="text-sm text-zinc-700 hover:underline dark:text-zinc-300"
                                                        >
                                                            Edit
                                                        </button>
                                                    </DialogTrigger>

                                                    <DialogContent className="sm:max-w-lg">
                                                        <DialogHeader>
                                                            <DialogTitle>Edit user</DialogTitle>
                                                            <DialogDescription>
                                                                Update {u.name}'s account details.
                                                            </DialogDescription>
                                                        </DialogHeader>

                                                        <Form
                                                            method="put"
                                                            action={update.url(u.id)}
                                                            onSuccess={() => setEditingId(null)}
                                                        >
                                                            {({ processing, errors }) => (
                                                                <div className="grid grid-cols-1 gap-3">
                                                                    <div className="flex flex-col gap-1">
                                                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                            Name
                                                                        </label>
                                                                        <input
                                                                            name="name"
                                                                            defaultValue={u.name}
                                                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                        />
                                                                        {errors.name && (
                                                                            <div className="text-xs text-red-600">
                                                                                {errors.name}
                                                                            </div>
                                                                        )}
                                                                    </div>

                                                                    <div className="flex flex-col gap-1">
                                                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                            Email
                                                                        </label>
                                                                        <input
                                                                            name="email"
                                                                            type="email"
                                                                            defaultValue={u.email}
                                                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                        />
                                                                        {errors.email && (
                                                                            <div className="text-xs text-red-600">
                                                                                {errors.email}
                                                                            </div>
                                                                        )}
                                                                    </div>

                                                                    <div className="flex items-end justify-end gap-3">
                                                                        <button
                                                                            type="button"
                                                                            onClick={() => setEditingId(null)}
                                                                            className="rounded-md px-3 py-2 text-sm font-medium text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
                                                                        >
                                                                            Cancel
                                                                        </button>
                                                                        <button
                                                                            type="submit"
                                                                            disabled={processing}
                                                                            className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                                                                        >
                                                                            Save
                                                                        </button>
                                                                    </div>
                                                                </div>
                                                            )}
                                                        </Form>
                                                    </DialogContent>
                                                </Dialog>

                                                <Form method="delete" action={destroy.url(u.id)}>
                                                    {({ processing }) => (
                                                        <button
                                                            type="submit"
                                                            disabled={processing}
                                                            className="text-sm text-red-700 hover:underline disabled:opacity-60 dark:text-red-400"
                                                        >
                                                            Delete
                                                        </button>
                                                    )}
                                                </Form>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

                    {users.length === 0 && (
                        <div className="p-4 text-sm text-zinc-600 dark:text-zinc-400">
                            No users yet.
                        </div>
                    )}
                </div>
            </div>
        </AppLayout>
    );
}
