
'use client';

import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { games as initialGames, Game } 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 {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogClose,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";

import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { ScrollArea } from '../ui/scroll-area';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { uploadService } from '@/servicios/upload-service';
import { useToast } from '@/hooks/use-toast';


export function GamesAdminTab() {
    const [games, setGames] = useState(initialGames);
    const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
    const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
    const [selectedGame, setSelectedGame] = useState<Game | null>(null);
    const [editedGame, setEditedGame] = useState<Partial<Game> | null>(null);
    const [newGame, setNewGame] = useState<Partial<Game>>({ title: '', console: 'PlayStation 5', coverUrl: '' });
    const [previewImage, setPreviewImage] = useState<string | null>(null);
    const [isUploading, setIsUploading] = useState(false);
    const { toast } = useToast();

    const handleEditClick = (game: Game) => {
        setSelectedGame(game);
        setEditedGame({ ...game });
        setPreviewImage(game.coverUrl);
        setIsEditDialogOpen(true);
    };

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        if (editedGame) {
            setEditedGame({ ...editedGame, [e.target.name]: e.target.value });
        }
    };
    
    const handleNewGameInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setNewGame({ ...newGame, [e.target.name]: e.target.value });
    };

    const handleConsoleChange = (value: Game['console']) => {
        if (editedGame) {
            setEditedGame({ ...editedGame, console: value });
        }
    };
    
    const handleNewGameConsoleChange = (value: Game['console']) => {
        setNewGame({ ...newGame, console: value });
    };

    const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            setIsUploading(true);
            try {
                // Subir imagen al servidor
                const uploadResponse = await uploadService.uploadImage(file);
                
                // Actualizar preview y datos del juego
                setPreviewImage(uploadResponse.url);
                if (isEditDialogOpen && editedGame) {
                    setEditedGame({ ...editedGame, coverUrl: uploadResponse.url });
                } else if (isAddDialogOpen) {
                    setNewGame({ ...newGame, coverUrl: uploadResponse.url });
                }
                
                toast({
                    title: '¡Imagen subida!',
                    description: 'La imagen 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 (selectedGame && editedGame) {
            const updatedGames = games.map(g =>
                g.id === selectedGame.id ? { ...g, ...editedGame } as Game : g
            );
            setGames(updatedGames);
        }
        handleDialogClose(setIsEditDialogOpen, false);
    };
    
    const handleAddGame = () => {
        if (newGame.title && newGame.console && newGame.coverUrl) {
            const gameToAdd: Game = {
                id: Math.max(...games.map(g => g.id), 0) + 1,
                title: newGame.title,
                console: newGame.console,
                coverUrl: newGame.coverUrl,
                imageHint: 'custom game',
            };
            setGames([gameToAdd, ...games]);
        }
        handleDialogClose(setIsAddDialogOpen, false);
    };
    
    const handleDeleteGame = (gameId: number) => {
        setGames(games.filter(g => g.id !== gameId));
    };

    const handleDialogClose = (setOpen: React.Dispatch<React.SetStateAction<boolean>>, open: boolean) => {
        if (!open) {
            setSelectedGame(null);
            setEditedGame(null);
            setNewGame({ title: '', console: 'PlayStation 5', coverUrl: '' });
            setPreviewImage(null);
        }
        setOpen(open);
    };


    return (
        <>
            <Card>
                <CardHeader>
                    <div className="flex justify-between items-center">
                        <div>
                            <CardTitle>Gestionar Juegos</CardTitle>
                            <CardDescription>Añade, edita o elimina juegos disponibles.</CardDescription>
                        </div>
                        <Button onClick={() => handleDialogClose(setIsAddDialogOpen, true)}>
                            <PlusCircle className="mr-2" /> Añadir Juego
                        </Button>
                    </div>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead className="w-20">Carátula</TableHead>
                                <TableHead>Título</TableHead>
                                <TableHead>Consola</TableHead>
                                <TableHead className="text-right">Acciones</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {games.map(game => (
                                <TableRow key={game.id}>
                                    <TableCell>
                                        <Image src={game.coverUrl} alt={game.title} width={40} height={50} className="rounded-md object-cover aspect-[4/5]" unoptimized/>
                                    </TableCell>
                                    <TableCell className="font-medium">{game.title}</TableCell>
                                    <TableCell>{game.console}</TableCell>
                                    <TableCell className="text-right">
                                        <AlertDialog>
                                            <DropdownMenu>
                                                <DropdownMenuTrigger asChild>
                                                    <Button variant="ghost" size="icon"><MoreHorizontal /></Button>
                                                </DropdownMenuTrigger>
                                                <DropdownMenuContent align="end">
                                                    <DropdownMenuItem onClick={() => handleEditClick(game)}>
                                                        <Pencil className="mr-2 h-4 w-4" />
                                                        Editar
                                                    </DropdownMenuItem>
                                                    <AlertDialogTrigger asChild>
                                                        <DropdownMenuItem className="text-red-400 focus:text-red-400">
                                                            <Trash2 className="mr-2 h-4 w-4" />
                                                            Eliminar
                                                        </DropdownMenuItem>
                                                    </AlertDialogTrigger>
                                                </DropdownMenuContent>
                                            </DropdownMenu>
                                            <AlertDialogContent>
                                                <AlertDialogHeader>
                                                    <AlertDialogTitle>¿Estás seguro?</AlertDialogTitle>
                                                    <AlertDialogDescription>
                                                        Esta acción no se puede deshacer. Esto eliminará permanentemente el juego de la lista.
                                                    </AlertDialogDescription>
                                                </AlertDialogHeader>
                                                <AlertDialogFooter>
                                                    <AlertDialogCancel>Cancelar</AlertDialogCancel>
                                                    <AlertDialogAction onClick={() => handleDeleteGame(game.id)} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
                                                        Sí, eliminar
                                                    </AlertDialogAction>
                                                </AlertDialogFooter>
                                            </AlertDialogContent>
                                        </AlertDialog>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </CardContent>
            </Card>

            {/* Edit Game Dialog */}
            <Dialog open={isEditDialogOpen} onOpenChange={(open) => handleDialogClose(setIsEditDialogOpen, open)}>
                <DialogContent className="sm:max-w-[625px] max-h-[90vh] flex flex-col">
                    <DialogHeader>
                        <DialogTitle>Editar Juego</DialogTitle>
                        <DialogDescription>
                            Realiza cambios en los detalles del juego. Haz clic en guardar cuando termines.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="flex-grow overflow-y-auto -mx-6 px-6">
                        {editedGame && (
                            <div className="grid gap-4 py-4">
                                <div className="grid grid-cols-4 items-center gap-4">
                                    <Label htmlFor="title" className="text-right">Título</Label>
                                    <Input id="title" name="title" value={editedGame.title || ''} onChange={handleInputChange} className="col-span-3" />
                                </div>
                                <div className="grid grid-cols-4 items-center gap-4">
                                    <Label htmlFor="console" className="text-right">Consola</Label>
                                     <Select onValueChange={handleConsoleChange} value={editedGame.console}>
                                        <SelectTrigger className="col-span-3">
                                            <SelectValue placeholder="Selecciona una consola" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="PlayStation 5">PlayStation 5</SelectItem>
                                            <SelectItem value="PlayStation 4">PlayStation 4</SelectItem>
                                            <SelectItem value="Nintendo Switch">Nintendo Switch</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div className="grid grid-cols-4 items-start gap-4">
                                    <Label htmlFor="coverUrl" className="text-right pt-2">Carátula</Label>
                                    <div className="col-span-3 space-y-2">
                                        <Input 
                                            id="coverUrl" 
                                            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-32 h-40 rounded-md overflow-hidden border">
                                                <Image src={previewImage} alt="Vista previa de la carátula" layout="fill" objectFit="cover" unoptimized/>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>
                    <DialogFooter className="pt-4 border-t border-border mt-auto -mx-6 px-6">
                        <Button type="button" variant="secondary" onClick={() => handleDialogClose(setIsEditDialogOpen, false)}>Cancelar</Button>
                        <Button type="button" onClick={handleSaveChanges}><Save className="mr-2 h-4 w-4" />Guardar Cambios</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Add Game Dialog */}
            <Dialog open={isAddDialogOpen} onOpenChange={(open) => handleDialogClose(setIsAddDialogOpen, open)}>
                <DialogContent className="sm:max-w-[625px] max-h-[90vh] flex flex-col">
                    <DialogHeader>
                        <DialogTitle>Añadir Nuevo Juego</DialogTitle>
                        <DialogDescription>
                            Completa los detalles para añadir un nuevo juego a la lista.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="flex-grow overflow-y-auto -mx-6 px-6">
                        <div className="grid gap-4 py-4">
                            <div className="grid grid-cols-4 items-center gap-4">
                                <Label htmlFor="new-title" className="text-right">Título</Label>
                                <Input id="new-title" name="title" value={newGame.title || ''} onChange={handleNewGameInputChange} className="col-span-3" />
                            </div>
                            <div className="grid grid-cols-4 items-center gap-4">
                                <Label htmlFor="new-console" className="text-right">Consola</Label>
                                <Select onValueChange={handleNewGameConsoleChange} value={newGame.console}>
                                    <SelectTrigger className="col-span-3">
                                        <SelectValue placeholder="Selecciona una consola" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="PlayStation 5">PlayStation 5</SelectItem>
                                        <SelectItem value="PlayStation 4">PlayStation 4</SelectItem>
                                        <SelectItem value="Nintendo Switch">Nintendo Switch</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="grid grid-cols-4 items-start gap-4">
                                <Label htmlFor="new-coverUrl" className="text-right pt-2">Carátula</Label>
                                <div className="col-span-3 space-y-2">
                                    <Input 
                                        id="new-coverUrl" 
                                        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-32 h-40 rounded-md overflow-hidden border">
                                            <Image src={previewImage} alt="Vista previa de la carátula" layout="fill" objectFit="cover" unoptimized/>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                    <DialogFooter className="pt-4 border-t border-border mt-auto -mx-6 px-6">
                        <Button type="button" variant="secondary" onClick={() => handleDialogClose(setIsAddDialogOpen, false)}>Cancelar</Button>
                        <Button type="button" onClick={handleAddGame}><PlusCircle className="mr-2 h-4 w-4" />Añadir Juego</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </>
    );
}
    