
'use client';

import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { fastFood, koreanFood, drinks, MenuItem } from "@/lib/data";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { MoreHorizontal, PlusCircle, Pencil, Trash2, Save } from "lucide-react";
import Image from "next/image";
import { useToast } from '@/hooks/use-toast';
import { uploadService } from '@/servicios/upload-service';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { ScrollArea } from '../ui/scroll-area';

export function MenuAdminTab() {
    const { toast } = useToast();
    const [menuItems, setMenuItems] = useState<MenuItem[]>([...fastFood, ...koreanFood, ...drinks]);
    const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
    const [selectedItem, setSelectedItem] = useState<MenuItem | null>(null);
    const [editedItem, setEditedItem] = useState<Partial<MenuItem> | null>(null);
    const [previewImage, setPreviewImage] = useState<string | null>(null);
    const [isUploading, setIsUploading] = useState(false);

    const handleEditClick = (item: MenuItem) => {
        setSelectedItem(item);
        setEditedItem({ ...item });
        setPreviewImage(item.imageUrl);
        setIsEditDialogOpen(true);
    };

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        if (editedItem) {
            const { name, value } = e.target;
            const newValue = name === 'price' ? parseFloat(value) : value;
            setEditedItem({ ...editedItem, [name]: newValue });
        }
    };
    
    const handleCategoryChange = (value: MenuItem['category']) => {
        if (editedItem) {
            setEditedItem({ ...editedItem, category: value });
        }
    };

    const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            setIsUploading(true);
            try {
                const uploadResponse = await uploadService.uploadImage(file);
                setPreviewImage(uploadResponse.url);
                if (editedItem) {
                    setEditedItem({ ...editedItem, imageUrl: uploadResponse.url });
                }
                toast({
                    title: '¡Imagen subida!',
                    description: 'La imagen del menú se ha guardado correctamente.',
                });
            } catch (error: any) {
                console.error("Error uploading image:", error);
                toast({
                    title: 'Error',
                    description: error.message || 'No se pudo subir la imagen.',
                    variant: 'destructive',
                });
            } finally {
                setIsUploading(false);
            }
        }
    };

    const handleSaveChanges = () => {
        if (selectedItem && editedItem) {
            const updatedItems = menuItems.map(item =>
                item.id === selectedItem.id ? { ...item, ...editedItem } as MenuItem : item
            );
            setMenuItems(updatedItems);
        }
        setIsEditDialogOpen(false);
    };

    const handleDialogClose = (open: boolean) => {
        if (!open) {
            setSelectedItem(null);
            setEditedItem(null);
            setPreviewImage(null);
        }
        setIsEditDialogOpen(open);
    }


    return (
        <>
            <Card>
                <CardHeader>
                    <div className="flex justify-between items-center">
                        <div>
                            <CardTitle>Gestionar Menú</CardTitle>
                            <CardDescription>Añade, edita o elimina platos del menú.</CardDescription>
                        </div>
                        <Button><PlusCircle className="mr-2" /> Añadir Plato</Button>
                    </div>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead className="w-20">Imagen</TableHead>
                                <TableHead>Nombre</TableHead>
                                <TableHead>Categoría</TableHead>
                                <TableHead>Precio</TableHead>
                                <TableHead className="text-right">Acciones</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {menuItems.map(item => (
                                <TableRow key={item.id}>
                                    <TableCell>
                                        <Image src={item.imageUrl} alt={item.name} width={60} height={45} className="rounded-md object-cover aspect-video" />
                                    </TableCell>
                                    <TableCell className="font-medium">{item.name}</TableCell>
                                    <TableCell>{item.category}</TableCell>
                                    <TableCell>S/ {item.price.toFixed(2)}</TableCell>
                                    <TableCell className="text-right">
                                        <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button variant="ghost" size="icon"><MoreHorizontal /></Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="end">
                                                <DropdownMenuItem onClick={() => handleEditClick(item)}>
                                                    <Pencil className="mr-2 h-4 w-4" />
                                                    Editar
                                                </DropdownMenuItem>
                                                <DropdownMenuItem className="text-red-400 focus:text-red-400">
                                                    <Trash2 className="mr-2 h-4 w-4" />
                                                    Eliminar
                                                </DropdownMenuItem>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </CardContent>
            </Card>

            <Dialog open={isEditDialogOpen} onOpenChange={handleDialogClose}>
                <DialogContent className="sm:max-w-[625px]">
                    <DialogHeader>
                        <DialogTitle>Editar Plato del Menú</DialogTitle>
                        <DialogDescription>
                            Realiza cambios en los detalles del plato. Haz clic en guardar cuando termines.
                        </DialogDescription>
                    </DialogHeader>
                    <ScrollArea className="max-h-[60vh] pr-6 -mr-6">
                        {editedItem && (
                            <div className="grid gap-4 py-4 pr-6">
                                <div className="grid grid-cols-4 items-center gap-4">
                                    <Label htmlFor="name" className="text-right">Nombre</Label>
                                    <Input id="name" name="name" value={editedItem.name || ''} onChange={handleInputChange} className="col-span-3" />
                                </div>
                                <div className="grid grid-cols-4 items-center gap-4">
                                    <Label htmlFor="category" className="text-right">Categoría</Label>
                                    <Select onValueChange={handleCategoryChange} value={editedItem.category}>
                                        <SelectTrigger className="col-span-3">
                                            <SelectValue placeholder="Selecciona una categoría" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="Comida Rápida">Comida Rápida</SelectItem>
                                            <SelectItem value="Comida Coreana">Comida Coreana</SelectItem>
                                            <SelectItem value="Bebidas">Bebidas</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div className="grid grid-cols-4 items-start gap-4">
                                    <Label htmlFor="description" className="text-right pt-2">Descripción</Label>
                                    <Textarea id="description" name="description" value={editedItem.description || ''} onChange={handleInputChange} className="col-span-3 min-h-[100px]" />
                                </div>
                                <div className="grid grid-cols-4 items-center gap-4">
                                    <Label htmlFor="price" className="text-right">Precio</Label>
                                    <Input id="price" name="price" type="number" value={editedItem.price || ''} onChange={handleInputChange} className="col-span-3" />
                                </div>
                                <div className="grid grid-cols-4 items-start gap-4">
                                <Label htmlFor="imageUrl" className="text-right pt-2">Imagen</Label>
                                    <div className="col-span-3 space-y-2">
                                        <Input 
                                            id="imageUrl" 
                                            type="file" 
                                            accept="image/*" 
                                            onChange={handleFileChange}
                                            disabled={isUploading}
                                            className="col-span-3" 
                                        />
                                        {isUploading && <p className="text-sm text-gray-500">Subiendo imagen...</p>}
                                        {previewImage && (
                                            <div className="relative w-40 h-32 rounded-md overflow-hidden border">
                                                <Image src={previewImage} alt="Vista previa del plato" layout="fill" objectFit="cover" />
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        )}
                    </ScrollArea>
                    <DialogFooter>
                        <Button type="button" variant="secondary" onClick={() => setIsEditDialogOpen(false)}>Cancelar</Button>
                        <Button type="button" onClick={handleSaveChanges}><Save className="mr-2 h-4 w-4" />Guardar Cambios</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </>
    )
}
