import { Head, router, useForm, usePage } from '@inertiajs/react';
import { Pencil, Plus, Trash2 } from 'lucide-react';
import { FormEvent, useState } from 'react';
import {
    PaginationControls,
    type PaginatedData,
    SortableHeader,
    type TableFilters,
} from '@/components/data-table-controls';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import type { Auth } from '@/types';

type Store = {
    id: number;
    name: string;
    code: string | null;
    phone: string | null;
    email: string | null;
    address: string | null;
    is_active: boolean;
    created_at: string;
};

type PageProps = {
    auth: Auth;
    stores: PaginatedData<Store>;
    filters: TableFilters;
};

type StoreForm = {
    name: string;
    code: string;
    phone: string;
    email: string;
    address: string;
    is_active: boolean;
};

const emptyForm: StoreForm = {
    name: '',
    code: '',
    phone: '',
    email: '',
    address: '',
    is_active: true,
};

export default function StoresIndex({ stores, filters }: PageProps) {
    const { auth } = usePage<PageProps>().props;
    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState<Store | null>(null);
    const form = useForm<StoreForm>(emptyForm);
    const can = (permission: string) => auth.permissions.includes(permission);

    const openCreate = () => {
        setEditing(null);
        form.setData(emptyForm);
        form.clearErrors();
        setOpen(true);
    };

    const openEdit = (store: Store) => {
        setEditing(store);
        form.setData({
            name: store.name,
            code: store.code ?? '',
            phone: store.phone ?? '',
            email: store.email ?? '',
            address: store.address ?? '',
            is_active: store.is_active,
        });
        form.clearErrors();
        setOpen(true);
    };

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

        if (editing) {
            form.put(`/stores/${editing.id}`, {
                preserveScroll: true,
                onSuccess: () => setOpen(false),
            });
            return;
        }

        form.post('/stores', {
            preserveScroll: true,
            onSuccess: () => setOpen(false),
        });
    };

    const destroy = (store: Store) => {
        if (!window.confirm(`Delete ${store.name}?`)) {
            return;
        }

        router.delete(`/stores/${store.id}`, { preserveScroll: true });
    };

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <Heading
                        title="Stores"
                        description="Manage store locations and contact details."
                    />

                    {can('stores.create') && (
                        <Button onClick={openCreate}>
                            <Plus />
                            New store
                        </Button>
                    )}
                </div>

                <div className="overflow-hidden rounded-lg border">
                    <table className="w-full text-sm">
                        <thead className="bg-muted/50 text-left">
                            <tr>
                                <SortableHeader
                                    basePath="/stores"
                                    column="name"
                                    filters={filters}
                                    className="px-4 py-3"
                                >
                                    Store
                                </SortableHeader>
                                <th className="px-4 py-3 font-medium">
                                    Contact
                                </th>
                                <th className="px-4 py-3 font-medium">
                                    Address
                                </th>
                                <SortableHeader
                                    basePath="/stores"
                                    column="is_active"
                                    filters={filters}
                                    className="px-4 py-3"
                                >
                                    Status
                                </SortableHeader>
                                <SortableHeader
                                    basePath="/stores"
                                    column="created_at"
                                    filters={filters}
                                    className="px-4 py-3"
                                >
                                    Created
                                </SortableHeader>
                                <th className="w-28 px-4 py-3 text-right font-medium">
                                    Actions
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y">
                            {stores.data.map((store) => (
                                <tr key={store.id}>
                                    <td className="px-4 py-3">
                                        <div className="font-medium">
                                            {store.name}
                                        </div>
                                        <div className="text-xs text-muted-foreground">
                                            {store.code ?? 'No code'}
                                        </div>
                                    </td>
                                    <td className="px-4 py-3 text-muted-foreground">
                                        <div>{store.phone ?? 'No phone'}</div>
                                        <div>{store.email ?? 'No email'}</div>
                                    </td>
                                    <td className="max-w-md px-4 py-3 text-muted-foreground">
                                        <div className="line-clamp-2">
                                            {store.address ?? 'No address'}
                                        </div>
                                    </td>
                                    <td className="px-4 py-3">
                                        <Badge
                                            variant={
                                                store.is_active
                                                    ? 'secondary'
                                                    : 'outline'
                                            }
                                        >
                                            {store.is_active
                                                ? 'Active'
                                                : 'Inactive'}
                                        </Badge>
                                    </td>
                                    <td className="px-4 py-3 text-muted-foreground">
                                        {new Date(
                                            store.created_at,
                                        ).toLocaleDateString()}
                                    </td>
                                    <td className="px-4 py-3">
                                        <div className="flex justify-end gap-2">
                                            {can('stores.update') && (
                                                <Button
                                                    variant="outline"
                                                    size="icon"
                                                    onClick={() =>
                                                        openEdit(store)
                                                    }
                                                >
                                                    <Pencil />
                                                    <span className="sr-only">
                                                        Edit
                                                    </span>
                                                </Button>
                                            )}
                                            {can('stores.delete') && (
                                                <Button
                                                    variant="destructive"
                                                    size="icon"
                                                    onClick={() =>
                                                        destroy(store)
                                                    }
                                                >
                                                    <Trash2 />
                                                    <span className="sr-only">
                                                        Delete
                                                    </span>
                                                </Button>
                                            )}
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                    <PaginationControls
                        basePath="/stores"
                        filters={filters}
                        meta={stores}
                    />
                </div>
            </div>

            <Dialog open={open} onOpenChange={setOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>
                            {editing ? 'Edit store' : 'New store'}
                        </DialogTitle>
                    </DialogHeader>

                    <form onSubmit={submit} className="space-y-4">
                        <div className="grid gap-2">
                            <Label htmlFor="name">Name</Label>
                            <Input
                                id="name"
                                value={form.data.name}
                                onChange={(event) =>
                                    form.setData('name', event.target.value)
                                }
                            />
                            <InputError message={form.errors.name} />
                        </div>

                        <div className="grid gap-2">
                            <Label htmlFor="code">Code</Label>
                            <Input
                                id="code"
                                value={form.data.code}
                                onChange={(event) =>
                                    form.setData('code', event.target.value)
                                }
                            />
                            <InputError message={form.errors.code} />
                        </div>

                        <div className="grid gap-4 sm:grid-cols-2">
                            <div className="grid gap-2">
                                <Label htmlFor="phone">Phone</Label>
                                <Input
                                    id="phone"
                                    value={form.data.phone}
                                    onChange={(event) =>
                                        form.setData(
                                            'phone',
                                            event.target.value,
                                        )
                                    }
                                />
                                <InputError message={form.errors.phone} />
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="email">Email</Label>
                                <Input
                                    id="email"
                                    type="email"
                                    value={form.data.email}
                                    onChange={(event) =>
                                        form.setData(
                                            'email',
                                            event.target.value,
                                        )
                                    }
                                />
                                <InputError message={form.errors.email} />
                            </div>
                        </div>

                        <div className="grid gap-2">
                            <Label htmlFor="address">Address</Label>
                            <Input
                                id="address"
                                value={form.data.address}
                                onChange={(event) =>
                                    form.setData('address', event.target.value)
                                }
                            />
                            <InputError message={form.errors.address} />
                        </div>

                        <label className="flex items-center gap-2 text-sm">
                            <Checkbox
                                checked={form.data.is_active}
                                onCheckedChange={(checked) =>
                                    form.setData('is_active', checked === true)
                                }
                            />
                            Active store
                        </label>
                        <InputError message={form.errors.is_active} />

                        <DialogFooter>
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => setOpen(false)}
                            >
                                Cancel
                            </Button>
                            <Button disabled={form.processing}>Save</Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </>
    );
}

StoresIndex.layout = {
    breadcrumbs: [
        {
            title: 'Stores',
            href: '/stores',
        },
    ],
};
