'use client';

import { useEffect, useState, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/use-toast';
import { Plus, Edit, Trash2, Search, X, Package, Filter, Upload, Loader2, Eye } from 'lucide-react';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { Pagination } from '@/components/ui/pagination';
import {
    getInventoryItems,
    createInventoryItem,
    updateInventoryItem,
    deleteInventoryItem,
    getUniqueCategoriesAndTypes,
} from '../actions/inventory-actions';
import { InventoryItem } from '@prisma/client';
import { Badge } from '@/components/ui/badge';
import { ConfirmDeleteDialog } from '@/components/ConfirmDeleteDialog';
import { Card, CardContent, CardFooter, CardHeader } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useSession } from 'next-auth/react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { checkOdooIntegration } from '../../actions/odoo-sync';

export default function InventoryPage() {
    const router = useRouter();
    const { data: session, status } = useSession();
    const [items, setItems] = useState<InventoryItem[]>([]);
    const [loading, setLoading] = useState(true);
    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState<InventoryItem | null>(null);
    const [uploading, setUploading] = useState(false);
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const [preview, setPreview] = useState<string>('');
    const { toast } = useToast();
    const [hasOdoo, setHasOdoo] = useState(false);
    const [isSyncing, setIsSyncing] = useState(false);

    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [deleteTarget, setDeleteTarget] = useState<InventoryItem | null>(null);

    const [searchTerm, setSearchTerm] = useState('');
    const [selectedCategory, setSelectedCategory] = useState('all');

    const [selectedType, setSelectedType] = useState('all');
    const [availableCategories, setAvailableCategories] = useState<string[]>([]);
    const [availableTypes, setAvailableTypes] = useState<string[]>([]);

    const [currentPage, setCurrentPage] = useState(1);
    const itemsPerPage = 10;

    const [formData, setFormData] = useState({
        name: '',
        quantity: 0,
        description: '',
        sku: '',
        category: '',
        type: '',
        location: '',
        imageUrl: '',
    });

    const fetchItems = useCallback(async () => {
        if (status === 'loading') return;

        if (status === 'unauthenticated' || !session?.user) {
            setLoading(false);
            return;
        }

        const orgId = (session.user as any).organizationId;

        if (!orgId) {
            setLoading(false);
            return;
        }

        setLoading(true);
        try {
            const res = await getInventoryItems(orgId);
            if (Array.isArray(res)) {
                setItems(res);
            } else {
                toast({
                    title: 'Erro',
                    description: 'Falha ao carregar itens',
                    variant: 'destructive',
                });
            }
        } catch (error) {
            toast({
                title: 'Erro',
                description: 'Erro ao procurar itens',
                variant: 'destructive',
            });
        } finally {
            setLoading(false);
        }
    }, [toast, session, status]);

    useEffect(() => {
        if (status === 'authenticated') {
            if (session?.user) {
                const orgId = (session.user as any).organizationId;
                getUniqueCategoriesAndTypes(orgId).then((res) => {
                    setAvailableCategories(res.categories);
                    setAvailableTypes(res.types);
                });
                checkOdooIntegration(orgId).then((res) => {
                    setHasOdoo(res);
                });
            }
            fetchItems();
        } else if (status === 'unauthenticated') {
            setLoading(false);
        }
    }, [status, session, fetchItems]);

    const filteredItems = items.filter((item) => {
        const matchesSearch =
            searchTerm === '' ||
            item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            (item.description && item.description.toLowerCase().includes(searchTerm.toLowerCase())) ||
            (item.sku && item.sku.toLowerCase().includes(searchTerm.toLowerCase()));

        const matchesCategory = selectedCategory === 'all' || item.category === selectedCategory;
        const matchesType = selectedType === 'all' || (item as any).type === selectedType;

        let showTool = true;
        if (item.category === 'Ferramentas') {
            if (selectedCategory !== 'Ferramentas' && !searchTerm) {
                showTool = false;
            }
        }

        return matchesSearch && matchesCategory && matchesType && showTool;
    });

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            if (file.size > 5 * 1024 * 1024) {
                toast({
                    title: 'Erro',
                    description: 'Ficheiro muito grande (máx 5MB)',
                    variant: 'destructive',
                });
                return;
            }
            if (!file.type.startsWith('image/')) {
                toast({
                    title: 'Erro',
                    description: 'Apenas imagens são permitidas',
                    variant: 'destructive',
                });
                return;
            }
            setSelectedFile(file);
            const reader = new FileReader();
            reader.onloadend = () => {
                setPreview(reader.result as string);
            };
            reader.readAsDataURL(file);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!formData.name) {
            toast({ title: 'Erro', description: 'Nome é obrigatório', variant: 'destructive' });
            return;
        }

        if (!session?.user) return;
        const orgId = (session.user as any).organizationId;

        try {
            let imageUrl = formData.imageUrl;

            if (selectedFile) {
                setUploading(true);
                try {
                    const { uploadFileDirect } = await import('@/lib/upload');
                    imageUrl = await uploadFileDirect(selectedFile, 'image');
                } catch (error: any) {
                    toast({
                        title: 'Erro no upload',
                        description: error.message,
                        variant: 'destructive',
                    });
                    setUploading(false);
                    return;
                }
                setUploading(false);
            }

            let res;
            if (editing) {
                res = await updateInventoryItem(editing.id, { ...formData, imageUrl });
            } else {
                res = await createInventoryItem({
                    ...formData,
                    imageUrl,
                    organizationId: orgId,
                });
            }

            if (res.success) {
                toast({
                    title: 'Sucesso',
                    description: editing ? 'Item atualizado' : 'Item criado',
                });
                setOpen(false);
                resetForm();
                fetchItems();
            } else {
                toast({
                    title: 'Erro',
                    description: res.error || 'Erro ao guardar',
                    variant: 'destructive',
                });
            }
        } catch (error) {
            toast({
                title: 'Erro',
                description: 'Erro inesperado',
                variant: 'destructive',
            });
        }
    };

    const handleDelete = async (id: string) => {
        const res = await deleteInventoryItem(id);
        if (res.success) {
            toast({ title: 'Sucesso', description: 'Item excluído' });
            fetchItems();
        } else {
            toast({ title: 'Erro', description: 'Erro ao excluir', variant: 'destructive' });
        }
    };

    const resetForm = () => {
        setEditing(null);
        setFormData({
            name: '',
            quantity: 0,
            description: '',
            sku: '',
            category: '',
            type: '',
            location: '',
            imageUrl: '',
        });
        setSelectedFile(null);
        setPreview('');
        setUploading(false);
    };

    const handleEdit = (item: InventoryItem) => {
        setEditing(item);
        setFormData({
            name: item.name,
            quantity: item.quantity,
            description: item.description || '',
            sku: item.sku || '',
            category: item.category || '',
            type: (item as any).type || '',
            location: (item as any).location || '',
            imageUrl: item.imageUrl || '',
        });
        setPreview(item.imageUrl || '');
        setSelectedFile(null);
        setOpen(true);
    };

    const categories = availableCategories;
    const types = availableTypes;

    useEffect(() => {
        setCurrentPage(1);
    }, [searchTerm, selectedCategory, selectedType]);

    const totalPages = Math.ceil(filteredItems.length / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const paginatedItems = filteredItems.slice(startIndex, endIndex);

    if (loading && items.length === 0) return <LoadingSpinner />;

    return (
        <div className='space-y-6'>
            <div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4'>
                <div>
                    <h1 className='text-2xl sm:text-3xl font-bold dark:text-white'>Inventário</h1>
                    <p className='text-sm text-gray-600 dark:text-gray-400 mt-1'>
                        Faça a gestão do seu stock de equipamentos e consumíveis.
                    </p>
                </div>
                <div className='flex gap-2'>
                    {hasOdoo && (
                        <Button
                            variant='outline'
                            disabled={isSyncing}
                            onClick={async () => {
                                if (!session?.user) return;
                                const orgId = (session.user as any).organizationId;
                                setIsSyncing(true);
                                try {
                                    const { syncOdooInventory } = await import('../../actions/odoo-sync');
                                    const res = await syncOdooInventory(orgId);
                                    if (res.success) {
                                        toast({ title: 'Sucesso', description: res.message });
                                        fetchItems();
                                    } else {
                                        toast({
                                            title: 'Info',
                                            description: res.error || res.message,
                                            variant: res.success ? 'default' : 'destructive',
                                        });
                                    }
                                } catch (e) {
                                    toast({
                                        title: 'Erro',
                                        description: 'Falha na comunicação com o servidor.',
                                        variant: 'destructive',
                                    });
                                }
                                setIsSyncing(false);
                            }}
                        >
                            {isSyncing ? (
                                <Loader2 className='mr-2 h-4 w-4 animate-spin' />
                            ) : (
                                <Upload className='mr-2 h-4 w-4' />
                            )}
                            {isSyncing ? 'A sincronizar...' : 'Sincronizar Odoo'}
                        </Button>
                    )}
                    <Button
                        onClick={() => {
                            resetForm();
                            setOpen(true);
                        }}
                        className='shadow-sm'
                    >
                        <Plus className='mr-2 h-4 w-4' />
                        Novo Item
                    </Button>
                </div>
            </div>

            <div className='bg-white dark:bg-gray-800 rounded-lg shadow p-4 mb-4 border dark:border-gray-700'>
                <div className='flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 mb-4'>
                    <h2 className='text-base font-semibold flex items-center gap-2'>
                        <Filter className='h-4 w-4' />
                        Filtros de itens
                    </h2>
                    {(searchTerm || selectedCategory !== 'all' || selectedType !== 'all') && (
                        <Button
                            variant='outline'
                            size='sm'
                            onClick={() => {
                                setSearchTerm('');
                                setSelectedCategory('all');
                                setSelectedType('all');
                            }}
                            className='text-xs h-8'
                        >
                            <X className='h-3 w-3 mr-1' />
                            Limpar filtros
                        </Button>
                    )}
                </div>

                <div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3'>
                    <div className='lg:col-span-2'>
                        <div className='relative'>
                            <Input
                                placeholder='Procurar por nome, SKU, descrição...'
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className='pl-9 pr-9 h-9'
                            />
                            <Search className='absolute left-2.5 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400' />
                            {searchTerm && (
                                <Button
                                    variant='ghost'
                                    size='icon'
                                    className='absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6'
                                    onClick={() => setSearchTerm('')}
                                >
                                    <X className='h-3 w-3' />
                                </Button>
                            )}
                        </div>
                    </div>

                    <Select
                        value={selectedCategory}
                        onValueChange={setSelectedCategory}
                    >
                        <SelectTrigger className='h-9'>
                            <SelectValue placeholder='Categoria' />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value='all'>Todas as categorias</SelectItem>
                            {categories.map((cat) => (
                                <SelectItem
                                    key={cat as string}
                                    value={cat as string}
                                >
                                    {cat}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>

                    <Select
                        value={selectedType}
                        onValueChange={setSelectedType}
                    >
                        <SelectTrigger className='h-9'>
                            <SelectValue placeholder='Tipo' />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value='all'>Todos os tipos</SelectItem>
                            {types.map((t) => (
                                <SelectItem
                                    key={t as string}
                                    value={t as string}
                                >
                                    {t}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                </div>
            </div>

            <div className='bg-white dark:bg-gray-800 rounded-lg shadow border dark:border-gray-700 overflow-hidden relative'>
                <div className='overflow-x-auto'>
                    <Table>
                        <TableHeader className='bg-gray-50 dark:bg-gray-900/50'>
                            <TableRow>
                                <TableHead className='w-[80px]'>Foto</TableHead>
                                <TableHead>Item</TableHead>
                                <TableHead>SKU</TableHead>
                                <TableHead>Categoria / Tipo</TableHead>
                                <TableHead>Localização</TableHead>
                                <TableHead className='text-right'>Stock</TableHead>
                                <TableHead className='w-[80px] text-right'>Ações</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {filteredItems.length === 0 ? (
                                <TableRow>
                                    <TableCell
                                        colSpan={7}
                                        className='text-center py-12 text-muted-foreground'
                                    >
                                        <div className='flex flex-col items-center justify-center gap-2'>
                                            <Package className='h-8 w-8 text-gray-300' />
                                            <p>Nenhum item encontrado</p>
                                        </div>
                                    </TableCell>
                                </TableRow>
                            ) : (
                                paginatedItems.map((item) => (
                                    <TableRow
                                        key={item.id}
                                        className='hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors group'
                                    >
                                        <TableCell>
                                            <div className='relative h-12 w-12 rounded-md overflow-hidden bg-gray-100 dark:bg-gray-900 border dark:border-gray-700'>
                                                {item.imageUrl ? (
                                                    <Image
                                                        src={item.imageUrl}
                                                        alt={item.name}
                                                        fill
                                                        className='object-cover'
                                                    />
                                                ) : (
                                                    <div className='flex h-full w-full items-center justify-center text-gray-300'>
                                                        <Package className='h-6 w-6' />
                                                    </div>
                                                )}
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <div className='flex flex-col'>
                                                <span className='font-semibold text-gray-900 dark:text-white'>
                                                    {item.name}
                                                </span>
                                                {item.description && (
                                                    <span
                                                        className='text-xs text-muted-foreground truncate max-w-[200px]'
                                                        title={item.description}
                                                    >
                                                        {item.description}
                                                    </span>
                                                )}
                                            </div>
                                        </TableCell>
                                        <TableCell className='font-mono text-xs text-muted-foreground'>
                                            {item.sku || 'N/A'}
                                        </TableCell>
                                        <TableCell>
                                            <div className='flex flex-wrap gap-1.5 items-center'>
                                                {item.category && (
                                                    <Badge
                                                        variant='secondary'
                                                        className='px-2 py-0 h-5 text-[10px] font-semibold border-none bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300'
                                                    >
                                                        {item.category}
                                                    </Badge>
                                                )}
                                                {(item as any).type && (
                                                    <Badge
                                                        variant='outline'
                                                        className='px-2 py-0 h-5 text-[10px] font-medium border-gray-200 dark:border-gray-700 text-muted-foreground uppercase tracking-wider'
                                                    >
                                                        {(item as any).type}
                                                    </Badge>
                                                )}
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <span className='text-sm text-muted-foreground'>
                                                {(item as any).location || '---'}
                                            </span>
                                        </TableCell>
                                        <TableCell className='text-right font-medium'>
                                            {item.category === 'Ferramentas' ? (
                                                <span className='text-gray-400'>-</span>
                                            ) : (
                                                <div className='flex flex-col items-end'>
                                                    <span
                                                        className={`font-bold text-lg ${item.quantity <= 5 ? 'text-red-500' : ''}`}
                                                    >
                                                        {item.quantity}
                                                    </span>
                                                    {item.quantity <= 5 && (
                                                        <span className='text-[10px] font-bold text-red-500 uppercase tracking-tight'>
                                                            Stock baixo
                                                        </span>
                                                    )}
                                                </div>
                                            )}
                                        </TableCell>
                                        <TableCell className='text-right'>
                                            <div className='flex justify-end gap-2'>
                                                <Button
                                                    variant='outline'
                                                    size='icon'
                                                    className='h-8 w-8'
                                                    asChild
                                                    title='Ver Detalhes'
                                                >
                                                    <Link href={`/module-inventory/inventory/${item.id}`}>
                                                        <Eye className='h-4 w-4' />
                                                    </Link>
                                                </Button>
                                                <Button
                                                    variant='outline'
                                                    size='icon'
                                                    className='h-8 w-8'
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        handleEdit(item);
                                                    }}
                                                >
                                                    <Edit className='h-4 w-4' />
                                                </Button>
                                                <Button
                                                    variant='outline'
                                                    size='icon'
                                                    className='h-8 w-8'
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        setDeleteTarget(item);
                                                        setDeleteDialogOpen(true);
                                                    }}
                                                >
                                                    <Trash2 className='h-4 w-4' />
                                                </Button>
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                </div>
            </div>

            {filteredItems.length > 0 && totalPages > 1 && (
                <div className='mt-4'>
                    <Pagination
                        currentPage={currentPage}
                        totalPages={totalPages}
                        onPageChange={setCurrentPage}
                        itemsPerPage={itemsPerPage}
                        totalItems={filteredItems.length}
                    />
                </div>
            )}

            <Dialog
                open={open}
                onOpenChange={(val) => {
                    if (!val) resetForm();
                    setOpen(val);
                }}
            >
                <DialogContent className='max-w-3xl'>
                    <DialogHeader>
                        <DialogTitle>{editing ? 'Editar Item' : 'Novo Item de Inventário'}</DialogTitle>
                    </DialogHeader>
                    <form
                        onSubmit={handleSubmit}
                        className='space-y-6'
                    >
                        <div className='flex flex-col md:flex-row gap-6'>
                            <div className='w-full md:w-1/3 space-y-2'>
                                <Label className='text-base font-semibold'>Imagem</Label>
                                <div className='flex flex-col gap-2'>
                                    {preview ? (
                                        <div className='relative w-full aspect-square bg-gray-100 dark:bg-gray-800 rounded-lg overflow-hidden border dark:border-gray-700 group'>
                                            <Image
                                                src={preview}
                                                alt='Preview'
                                                fill
                                                className='object-cover'
                                            />
                                            <div className='absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2'>
                                                <Button
                                                    type='button'
                                                    variant='secondary'
                                                    size='sm'
                                                    onClick={() => {
                                                        const input = document.getElementById('image-upload');
                                                        if (input) input.click();
                                                    }}
                                                >
                                                    <Edit className='h-4 w-4 mr-2' /> Alterar
                                                </Button>
                                                <Button
                                                    type='button'
                                                    variant='destructive'
                                                    size='sm'
                                                    onClick={() => {
                                                        setPreview('');
                                                        setSelectedFile(null);
                                                        setFormData({ ...formData, imageUrl: '' });
                                                    }}
                                                >
                                                    <Trash2 className='h-4 w-4' />
                                                </Button>
                                            </div>
                                        </div>
                                    ) : (
                                        <div
                                            onClick={() => document.getElementById('image-upload')?.click()}
                                            className='w-full aspect-square border-2 border-dashed border-gray-300 dark:border-gray-700 rounded-lg flex flex-col items-center justify-center text-center hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors cursor-pointer'
                                        >
                                            <div className='bg-gray-100 dark:bg-gray-800 p-3 rounded-full mb-3'>
                                                <Upload className='h-6 w-6 text-gray-500' />
                                            </div>
                                            <span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
                                                Upload de Imagem
                                            </span>
                                            <span className='text-xs text-gray-400 mt-1 px-4'>
                                                Arraste ou clique (Max 5MB)
                                            </span>
                                        </div>
                                    )}
                                    <Input
                                        id='image-upload'
                                        type='file'
                                        accept='image/*'
                                        className='hidden'
                                        onChange={handleFileChange}
                                    />
                                </div>
                            </div>

                            <div className='flex-1 space-y-6'>
                                <div className='space-y-4'>
                                    <h3 className='text-sm font-medium text-muted-foreground border-b pb-2'>
                                        Identificação
                                    </h3>
                                    <div className='grid gap-4'>
                                        <div className='space-y-2'>
                                            <Label htmlFor='name'>Nome do Item *</Label>
                                            <Input
                                                id='name'
                                                value={formData.name}
                                                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                                placeholder="Ex: Monitor Dell 24''"
                                                required
                                            />
                                        </div>
                                        <div className='grid grid-cols-2 gap-4'>
                                            <div className='space-y-2'>
                                                <Label htmlFor='sku'>SKU / Código</Label>
                                                <Input
                                                    id='sku'
                                                    value={formData.sku}
                                                    onChange={(e) => setFormData({ ...formData, sku: e.target.value })}
                                                    placeholder='Ex: OFF-001'
                                                />
                                            </div>
                                            <div className='space-y-2'>
                                                <Label htmlFor='quantity'>Quantidade *</Label>
                                                <Input
                                                    id='quantity'
                                                    type='number'
                                                    value={formData.quantity}
                                                    onChange={(e) =>
                                                        setFormData({
                                                            ...formData,
                                                            quantity: parseInt(e.target.value) || 0,
                                                        })
                                                    }
                                                    required
                                                />
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div className='space-y-4'>
                                    <h3 className='text-sm font-medium text-muted-foreground border-b pb-2'>
                                        Detalhes
                                    </h3>
                                    <div className='grid grid-cols-2 gap-4'>
                                        <div className='space-y-2'>
                                            <Label htmlFor='category'>Categoria</Label>
                                            <Select
                                                value={formData.category}
                                                onValueChange={(val) => setFormData({ ...formData, category: val })}
                                            >
                                                <SelectTrigger id='category'>
                                                    <SelectValue placeholder='Selecione uma categoria' />
                                                </SelectTrigger>
                                                <SelectContent>
                                                    <SelectItem value='Stands Expositores'>
                                                        Stands Expositores
                                                    </SelectItem>
                                                    <SelectItem value='Digital e Tecnologia'>
                                                        Digital e Tecnologia
                                                    </SelectItem>
                                                    <SelectItem value='Outdoor'>Outdoor</SelectItem>
                                                    <SelectItem value='Mobiliário'>Mobiliário</SelectItem>
                                                    <SelectItem value='Postes Separadores'>
                                                        Postes Separadores
                                                    </SelectItem>
                                                    <SelectItem value='Ferramentas'>Ferramentas</SelectItem>
                                                </SelectContent>
                                            </Select>
                                        </div>
                                        <div className='space-y-2'>
                                            <Label htmlFor='type'>Tipo</Label>
                                            <Input
                                                id='type'
                                                value={formData.type}
                                                onChange={(e) => setFormData({ ...formData, type: e.target.value })}
                                                placeholder='Ex: Consumível'
                                                list='types-list'
                                            />
                                            <datalist id='types-list'>
                                                {types.map((t) => (
                                                    <option
                                                        key={t as string}
                                                        value={t as string}
                                                    />
                                                ))}
                                                <option value='Ferramenta' />
                                            </datalist>
                                        </div>
                                        <div className='col-span-2 space-y-2'>
                                            <Label htmlFor='location'>Localização</Label>
                                            <Input
                                                id='location'
                                                value={formData.location}
                                                onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                                                placeholder='Ex: Armazém A, Prateleira 3'
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className='space-y-2'>
                            <Label htmlFor='description'>Descrição / Observações</Label>
                            <Input
                                id='description'
                                value={formData.description}
                                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                                placeholder='Detalhes adicionais sobre o produto...'
                            />
                        </div>

                        <DialogFooter className='pt-4 border-t'>
                            <Button
                                type='button'
                                variant='outline'
                                onClick={() => {
                                    setOpen(false);
                                    resetForm();
                                }}
                            >
                                Cancelar
                            </Button>
                            <Button
                                type='submit'
                                disabled={uploading}
                                className='min-w-[120px]'
                            >
                                {uploading && <Loader2 className='mr-2 h-4 w-4 animate-spin' />}
                                {editing ? 'Guardar alterações' : 'Criar Item'}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            <ConfirmDeleteDialog
                open={deleteDialogOpen}
                onOpenChange={setDeleteDialogOpen}
                entityLabel='Item de Inventário'
                identifier={deleteTarget?.name || ''}
                onConfirm={async () => {
                    if (deleteTarget) {
                        await handleDelete(deleteTarget.id);
                        setDeleteTarget(null);
                    }
                }}
            />
        </div>
    );
}
