import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';
import { BreadcrumbItem, PaginatedProducts, Product } from '@/types';
import { Input, Textarea } from '@headlessui/react';
import { Head, useForm, router } from '@inertiajs/react';
import { Link, Package, Pencil, Plus, Trash } from 'lucide-react';
import { FormEvent, useState } from 'react';
import { toast } from 'sonner';

interface Props {
    products: PaginatedProducts
}

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Products',
        href: '/products',
    },
];

export default function ProdctsIndex({ products }: Props) {
    const [showCreate, setShowCreate] = useState(false);
    const [editing, setEditing] = useState<Product | null>(null);
    const createForm = useForm({
        name: '',
        description: '',
        price: 0,
        stack: 0,
        is_active: true,
    })
    const editForm = useForm({
        name: '',
        description: '',
        price: 0,
        stack: 0,
        is_active: true,
    })

    function submitCreate(e: FormEvent) {
        e.preventDefault();
        createForm.post('/products', {
            onSuccess: () => {
                toast.success('Product created successfully');
                setShowCreate(false);
                createForm.reset();
            }
        });
    }

    function openEdit(product: Product) {
        setEditing(product);
        editForm.setData({
            name: product.name,
            description: product.description ?? "",
            price: String(product.price),
            stack: String(product.stack),
            is_active: product.is_active,
        });
    }
    function submitEdit(e: FormEvent) {
        e.preventDefault();
        if (!editing) return;
        editForm.patch(`/products/${editing.id}`, {
            onSuccess: () => {
                toast.success('Product updated successfully');
                setEditing(null);
            }
        })
    }

    function handleDelete(product: Product) {
        if (!confirm("Are you sure you want to delete this product?")) return;
        router.delete(`/products/${product.id}`, {
            onSuccess: () => {
                toast.success('Product deleted successfully');
            }
        })
    }

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Products" />
            <div className='p-6'>
                <div className='mb-6 flex items-center justify-between'>
                    <h1 className='text-2xl font-bold'>Products</h1>
                    <Button onClick={() => setShowCreate(true)}>
                        <Plus className="mr-2 h-4 w-4" />
                        Add Product
                    </Button>
                </div>
                {products.data.length === 0 ? (
                    <div className='flex flex-col items-center justify-center rounded-xl border border-dashed py-24 text-center'>
                        <Package className='mb-3 h-12 w-12 text-muted-foreground' />
                        <p className='font-semibold'>No products yet</p>
                        <p className='mt-1 text-sm text-muted-foreground'>Add your first product to get started.</p>
                    </div>
                ) : (
                    <div>
                        <div className='rounded-xl border'>
                            <table className='w-full text-sm'>
                                <thead className='border-b bg-muted/40'>
                                    <tr>
                                        <th className='px-4 py-3 text-left font-medium'>Name</th>
                                        <th className='px-4 py-3 text-left font-medium'>Description</th>
                                        <th className='px-4 py-3 text-left font-medium'>Price</th>
                                        <th className='px-4 py-3 text-left font-medium'>Stock</th>
                                        <th className='px-4 py-3 text-left font-medium'>Status</th>
                                        <th className='px-4 py-3' />
                                    </tr>
                                </thead>
                                <tbody className='divide-y'>
                                    {products.data.map(product => (
                                        <tr key={product.id} className='hover:bg-muted/20'>
                                            <td className='px-4 py-3 font-medium'>{product.name}</td>
                                            <td className='px-4 py-3 max-w-xs truncate text-muted-foreground'>{product.description ?? '-'}</td>
                                            <td className='px-4 py-3 text-right'>{product.price}</td>
                                            <td className={`px-4 py-3 text-right ${product.stack === 0 ? 'text-red-500 font-medium' : product.stack <= 5 ? 'text-orange-500' : ''}`}>{product.stack}</td>
                                            <td className={`px-4 py-3 text-right ${product.is_active ? 'bg-green-500' : 'bg-red-500'}`}></td>
                                            <td className={`px-4 py-3 text-right flex gap-2 justify-end`}>
                                                <button
                                                    onClick={() => openEdit(product)}
                                                    className='text-muted-foreground hover:text-foreground'
                                                    title="Edit" >
                                                    <Pencil className='h-4 w-4' />
                                                </button>
                                                <button
                                                    onClick={() => handleDelete(product)}
                                                    className='text-muted-foreground hover:text-foreground'
                                                    title="Edit" >
                                                    <Trash className='h-4 w-4 text-red-500' />
                                                </button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>

                        {products.last_page > 1 && (
                            <div className='mt-4 flex justify-center gap-1'>
                                {products.links.map((link, i) => (
                                    link.url ? (
                                        <Link
                                            key={i}
                                            href={link.url}
                                            className={`rounded px-3 py-1.5 text-sm ${link.active ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'}`}
                                            dangerouslySetInnerHTML={{ __html: link.label }}
                                        />
                                    ) : (
                                        <span
                                            key={i}
                                            className='rounded px-3 py-1.5 text-sm opacity-40'
                                            dangerouslySetInnerHTML={{ __html: link.label }}
                                        />
                                    )
                                ))}
                            </div>
                        )}
                    </div>
                )}
            </div>
            <Dialog open={showCreate} onOpenChange={(open: any) => { if (!open) { setShowCreate(false); createForm.reset(); } }}>
                <DialogContent className="max-w-md">
                    <DialogHeader>
                        <DialogTitle>Add Product</DialogTitle>
                    </DialogHeader>
                    <form onSubmit={submitCreate} className='space-y-4'>
                        <div>
                            <Label htmlFor='p-name'>Name</Label>

                            <Input
                                id='p-name'
                                value={createForm.data.name}
                                onChange={e => createForm.setData('name', e.target.value)}
                                autoFocus
                            />
                            <InputError message={createForm.errors.name} />
                        </div>

                        <div>
                            <Label htmlFor='p-desc'>Description</Label>

                            <Textarea
                                id='p-desc'
                                value={createForm.data.description}
                                onChange={e => createForm.setData('description', e.target.value)}
                                autoFocus
                            />
                            <InputError message={createForm.errors.description} />
                        </div>

                        <div>
                            <Label htmlFor='p-price'>Price</Label>

                            <Input
                                id='p-price'
                                value={createForm.data.price}
                                onChange={e => createForm.setData('price', Number(e.target.value))}
                                autoFocus
                            />
                            <InputError message={createForm.errors.price} />
                        </div>

                        <div>
                            <Label htmlFor='p-stack'>stack</Label>
                            <Input
                                id='p-stack'
                                value={createForm.data.stack}
                                onChange={e => createForm.setData('stack', Number(e.target.value))}
                                autoFocus
                            />
                            <InputError message={createForm.errors.stack} />
                        </div>
                        <div>
                            <Label htmlFor='p-is_active'>Is active</Label>

                            <Input
                                id='p-is_active'
                                checked={createForm.data.is_active}
                                type='checkbox'
                                onChange={e => createForm.setData('is_active', e.target.checked)}
                                autoFocus
                            />
                            <InputError message={createForm.errors.is_active} />
                        </div>

                        <div className='flex justify-end gap-2 pt-1'>
                            <Button type='button' variant='outline' onClick={() => { setShowCreate(false); createForm.reset(); }}>
                                cancel
                            </Button>
                            <Button type='submit' disabled={createForm.processing}>
                                {createForm.processing ? 'Creating ...' : 'Create'}
                            </Button>
                        </div>
                    </form>
                </DialogContent>

            </Dialog>

            <Dialog open={!!editing} onOpenChange={(open: any) => { if (!open) { setEditing(null); } }}>
                <DialogContent className="max-w-md">
                    <DialogHeader>
                        <DialogTitle>Edit Product</DialogTitle>
                    </DialogHeader>
                    <form onSubmit={submitEdit} className='space-y-4'>
                        <div>
                            <Label htmlFor='p-name'>Name</Label>

                            <Input
                                id='p-name'
                                value={editForm.data.name}
                                onChange={e => editForm.setData('name', e.target.value)}
                                autoFocus
                            />
                            <InputError message={editForm.errors.name} />
                        </div>

                        <div>
                            <Label htmlFor='p-desc'>Description</Label>

                            <Textarea
                                id='p-desc'
                                value={editForm.data.description}
                                onChange={e => editForm.setData('description', e.target.value)}
                                autoFocus
                            />
                            <InputError message={editForm.errors.description} />
                        </div>

                        <div>
                            <Label htmlFor='p-price'>Price</Label>

                            <Input
                                id='p-price'
                                value={editForm.data.price}
                                onChange={e => editForm.setData('price', Number(e.target.value))}
                                autoFocus
                            />
                            <InputError message={editForm.errors.price} />
                        </div>

                        <div>
                            <Label htmlFor='p-stack'>stack</Label>
                            <Input
                                id='p-stack'
                                value={editForm.data.stack}
                                onChange={e => editForm.setData('stack', Number(e.target.value))}
                                autoFocus
                            />
                            <InputError message={editForm.errors.stack} />
                        </div>
                        <div>
                            <Label htmlFor='p-is_active'>Is active</Label>

                            <Input
                                id='p-is_active'
                                checked={editForm.data.is_active}
                                type='checkbox'
                                onChange={e => editForm.setData('is_active', e.target.checked)}
                                autoFocus
                            />
                            <InputError message={editForm.errors.is_active} />
                        </div>

                        <div className='flex justify-end gap-2 pt-1'>
                            <Button type='button' variant='outline' onClick={() => { setShowCreate(false); editForm.reset(); }}>
                                cancel
                            </Button>
                            <Button type='submit' disabled={editForm.processing}>
                                {editForm.processing ? 'Creating ...' : 'Create'}
                            </Button>
                        </div>
                    </form>
                </DialogContent>

            </Dialog>
        </AppLayout>
    );
}
ProdctsIndex.layout = { breadcrumbs: [{ title: 'Products', href: '/products' }] };
