import Layout from '@/components/Layout';
import React, { useState } from 'react';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { EllipsisVertical, FolderClosed, Plus } from 'lucide-react';
import {
    Empty,
    EmptyDescription,
    EmptyHeader,
    EmptyMedia,
    EmptyTitle,
} from '@/components/ui/empty';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { router, useForm, usePage } from '@inertiajs/react';
import { Field, FieldDescription, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import AppPagination from '@/components/AppPagination';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import PageHeader from '@/components/PageHeader';

interface TableData {
    id: any;
    name: string;
    email: string;
    created_at: string;
}
interface LinkData {
    url: string | null;
    label: string;
    active: boolean;
}
interface PageProps {
    data: {
        data: TableData[];
        current_page: number;
        last_page: number;
        links: LinkData[];
        from: number | null;
        to: number | null;
        total: number;
    };
}

interface FormData {
    id: number | '';
    name: string | '';
    email: string | '';
    password: string | '';
}

export default function users({ data: initData }: PageProps) {
    const { auth } = usePage().props;
    const AuthUser = auth.user;

    const [formDialog, setFormDialog] = useState(false);

    // form
    const { data, setData, processing, post, reset, errors } =
        useForm<FormData>({
            id: '',
            name: '',
            email: '',
            password: '',
        });
    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post(route('users.store'), {
            preserveScroll: true,
            onSuccess: () => {
                reset();
                setFormDialog(false);
            },
        });
    };
    return (
        <Layout title="Expense">
            <PageHeader
                title="All Users"
                subtitle="Track and manage all users in your business."
            >
                <div className="flex flex-col items-center gap-2 md:flex-row">
                    <Button onClick={() => setFormDialog(true)}>
                        <Plus className="size-4" />
                        Add User
                    </Button>
                </div>
            </PageHeader>

            <Card>
                <CardContent>
                    {initData?.data?.length > 0 ? (
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="w-25">ID</TableHead>
                                    <TableHead>Name</TableHead>
                                    <TableHead>Email</TableHead>
                                    <TableHead>Date</TableHead>
                                    <TableHead className="text-right"></TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {initData?.data?.map((items) => (
                                    <TableRow key={items.id}>
                                        <TableCell className="font-medium">
                                            {items.id}
                                        </TableCell>
                                        <TableCell>{items.name}</TableCell>
                                        <TableCell>{items.email}</TableCell>
                                        <TableCell>
                                            {items.created_at}
                                        </TableCell>
                                        <TableCell className="text-right">
                                            <DropdownMenu>
                                                <DropdownMenuTrigger
                                                    render={
                                                        <Button
                                                            variant="ghost"
                                                            size="icon"
                                                            className="size-8"
                                                        >
                                                            <EllipsisVertical />
                                                            <span className="sr-only">
                                                                Open menu
                                                            </span>
                                                        </Button>
                                                    }
                                                />
                                                <DropdownMenuContent align="end">
                                                    <DropdownMenuItem
                                                        onClick={() => {
                                                            setData(
                                                                'id',
                                                                items.id,
                                                            );
                                                            setData(
                                                                'email',
                                                                items.email,
                                                            );
                                                            setData(
                                                                'name',
                                                                items.name,
                                                            );
                                                            setFormDialog(true);
                                                        }}
                                                    >
                                                        Edit
                                                    </DropdownMenuItem>
                                                    {items.id !=
                                                        AuthUser.id && (
                                                        <>
                                                            <DropdownMenuSeparator />
                                                            <DropdownMenuItem
                                                                variant="destructive"
                                                                onClick={() => {
                                                                    router.get(
                                                                        route(
                                                                            'users.delete',
                                                                            {
                                                                                id: items.id,
                                                                            },
                                                                        ),
                                                                    );
                                                                }}
                                                            >
                                                                Delete
                                                            </DropdownMenuItem>
                                                        </>
                                                    )}
                                                </DropdownMenuContent>
                                            </DropdownMenu>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    ) : (
                        <Empty>
                            <EmptyHeader>
                                <EmptyMedia variant="icon">
                                    <FolderClosed />
                                </EmptyMedia>
                                <EmptyTitle>No Users Yet</EmptyTitle>
                                <EmptyDescription>
                                    You haven't created any user yet. Get
                                    started by creating your first user.
                                </EmptyDescription>
                            </EmptyHeader>
                        </Empty>
                    )}
                </CardContent>

                <AppPagination data={initData} />
            </Card>

            {/* add and update dialog */}
            <Dialog open={formDialog}>
                <DialogContent showCloseButton={false} className="md:w-120">
                    <DialogHeader className="border-b border-border pb-2">
                        <DialogTitle>
                            {data.id ? 'Update User' : 'Create New User'}
                        </DialogTitle>
                        <DialogDescription>
                            {data.id
                                ? 'Update the user details and account information.'
                                : 'Add a new user and provide their account information.'}
                        </DialogDescription>
                    </DialogHeader>

                    <div className="w-full space-y-5">
                        <Field>
                            <FieldLabel>Name*</FieldLabel>
                            <Input
                                value={data.name}
                                onChange={(e) =>
                                    setData('name', e.target.value)
                                }
                            />
                            {errors.name && (
                                <FieldDescription className="text-destructive">
                                    {errors.name}
                                </FieldDescription>
                            )}
                        </Field>
                        <Field>
                            <FieldLabel>Email*</FieldLabel>
                            <Input
                                type="email"
                                value={data.email}
                                onChange={(e) =>
                                    setData('email', e.target.value)
                                }
                            />
                            {errors.email && (
                                <FieldDescription className="text-destructive">
                                    {errors.email}
                                </FieldDescription>
                            )}
                        </Field>
                        <Field>
                            <FieldLabel>Password*</FieldLabel>
                            <Input
                                type="text"
                                value={data.password}
                                onChange={(e) =>
                                    setData('password', e.target.value)
                                }
                            />
                            {errors.password && (
                                <FieldDescription className="text-destructive">
                                    {errors.password}
                                </FieldDescription>
                            )}
                        </Field>
                    </div>

                    <DialogFooter className="flex items-center justify-end gap-2">
                        <Button
                            onClick={() => {
                                reset();
                                setFormDialog(false);
                            }}
                            size="sm"
                            variant="outline"
                        >
                            Close
                        </Button>
                        <Button
                            onClick={handleSubmit}
                            size="sm"
                            variant="default"
                            disabled={processing}
                        >
                            Save Now{processing && '...'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </Layout>
    );
}
