import { useState } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { Search, Filter, Plus, Eye, Edit, Trash2, Star } from 'lucide-react';
import { Game } from '@/types';

// Datos simulados para la lista de juegos
const mockGames: Game[] = [
  {
    id: 1,
    title: 'The Legend of Zelda: Breath of the Wild',
    description: 'Un juego de acción-aventura desarrollado por Nintendo',
    platformId: 1,
    platform: { id: 1, name: 'Nintendo Switch', description: 'Consola híbrida de Nintendo' },
    releaseYear: 2017,
    rating: 9.5,
    tags: [{ id: 1, name: 'Aventura', color: '#3B82F6', description: 'Juegos de aventura' }],
    romFile: {
      id: 1,
      filename: 'zelda_botw.nsp',
      path: '/roms/nintendo-switch',
      size: 14485760,
      checksum: 'abc123',
    },
    metadataSource: 'manual',
    createdAt: new Date('2024-01-10'),
    updatedAt: new Date('2024-01-10'),
  },
  {
    id: 2,
    title: 'God of War',
    description: 'Un juego de acción-aventura basado en la mitología nórdica',
    platformId: 2,
    platform: { id: 2, name: 'PlayStation 4', description: 'Consola de Sony' },
    releaseYear: 2018,
    rating: 9.2,
    tags: [{ id: 2, name: 'Acción', color: '#EF4444', description: 'Juegos de acción' }],
    romFile: {
      id: 2,
      filename: 'god_of_war.iso',
      path: '/roms/ps4',
      size: 45234120,
      checksum: 'def456',
    },
    metadataSource: 'igdb',
    createdAt: new Date('2024-01-09'),
    updatedAt: new Date('2024-01-09'),
  },
  {
    id: 3,
    title: 'Cyberpunk 2077',
    description: 'Un RPG de acción en mundo abierto ambientado en Night City',
    platformId: 3,
    platform: { id: 3, name: 'PC', description: 'Plataforma de computadora personal' },
    releaseYear: 2020,
    rating: 8.7,
    tags: [{ id: 3, name: 'RPG', color: '#10B981', description: 'Juegos de rol' }],
    romFile: undefined,
    metadataSource: 'rawg',
    createdAt: new Date('2024-01-08'),
    updatedAt: new Date('2024-01-08'),
  },
];

const platforms = [
  { id: 1, name: 'Nintendo Switch' },
  { id: 2, name: 'PlayStation 4' },
  { id: 3, name: 'PC' },
  { id: 4, name: 'Xbox One' },
];

const tags = [
  { id: 1, name: 'Aventura', color: '#3B82F6' },
  { id: 2, name: 'Acción', color: '#EF4444' },
  { id: 3, name: 'RPG', color: '#10B981' },
  { id: 4, name: 'Estrategia', color: '#F59E0B' },
];

export function GamesPage() {
  const navigate = useNavigate();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedPlatform, setSelectedPlatform] = useState<string>('');
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [sortBy, setSortBy] = useState<string>('title');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
  const [currentPage, setCurrentPage] = useState(1);
  const [games] = useState<Game[]>(mockGames);

  // Filtrar y ordenar juegos
  const filteredGames = games
    .filter((game) => {
      const matchesSearch =
        game.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        game.description?.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesPlatform = !selectedPlatform || game.platformId.toString() === selectedPlatform;
      const matchesTags =
        selectedTags.length === 0 ||
        selectedTags.some((tagId) => game.tags.some((tag) => tag.id.toString() === tagId));

      return matchesSearch && matchesPlatform && matchesTags;
    })
    .sort((a, b) => {
      let aValue: string | number = '';
      let bValue: string | number = '';

      switch (sortBy) {
        case 'title':
          aValue = a.title?.toLowerCase() || '';
          bValue = b.title?.toLowerCase() || '';
          break;
        case 'platform':
          aValue = a.platform?.name?.toLowerCase() || '';
          bValue = b.platform?.name?.toLowerCase() || '';
          break;
        case 'releaseYear':
          aValue = a.releaseYear || 0;
          bValue = b.releaseYear || 0;
          break;
        case 'rating':
          aValue = a.rating || 0;
          bValue = b.rating || 0;
          break;
        default:
          aValue = a.title?.toLowerCase() || '';
          bValue = b.title?.toLowerCase() || '';
      }

      if (sortOrder === 'asc') {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });

  const handleSort = (field: string) => {
    if (sortBy === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(field);
      setSortOrder('asc');
    }
  };

  const handleTagToggle = (tagId: string) => {
    setSelectedTags((prev) =>
      prev.includes(tagId) ? prev.filter((id) => id !== tagId) : [...prev, tagId]
    );
  };

  const clearFilters = () => {
    setSearchTerm('');
    setSelectedPlatform('');
    setSelectedTags([]);
    setSortBy('title');
    setSortOrder('asc');
    setCurrentPage(1);
  };

  const handleGameClick = (gameId: number) => {
    navigate({ to: `/games/${gameId}` });
  };

  return (
    <div className="space-y-6">
      {/* Encabezado */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Juegos</h1>
          <p className="text-muted-foreground">Gestiona tu colección de videojuegos</p>
        </div>
        <Button onClick={() => navigate({ to: '/games/create' })}>
          <Plus className="mr-2 h-4 w-4" />
          Nuevo Juego
        </Button>
      </div>

      {/* Filtros */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Filter className="h-5 w-5" />
            Filtros y Búsqueda
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
            {/* Búsqueda */}
            <div className="space-y-2">
              <Label htmlFor="search">Buscar</Label>
              <div className="relative">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  id="search"
                  placeholder="Buscar juegos..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-8"
                />
              </div>
            </div>

            {/* Plataforma */}
            <div className="space-y-2">
              <Label htmlFor="platform">Plataforma</Label>
              <Select value={selectedPlatform} onValueChange={setSelectedPlatform}>
                <SelectTrigger>
                  <SelectValue placeholder="Todas las plataformas" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="">Todas las plataformas</SelectItem>
                  {platforms.map((platform) => (
                    <SelectItem key={platform.id} value={platform.id.toString()}>
                      {platform.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Ordenar por */}
            <div className="space-y-2">
              <Label htmlFor="sort">Ordenar por</Label>
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="title">Título</SelectItem>
                  <SelectItem value="releaseYear">Año de lanzamiento</SelectItem>
                  <SelectItem value="rating">Calificación</SelectItem>
                  <SelectItem value="platform">Plataforma</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Acciones */}
            <div className="space-y-2">
              <Label>&nbsp;</Label>
              <div className="flex gap-2">
                <Button variant="outline" onClick={clearFilters}>
                  Limpiar filtros
                </Button>
              </div>
            </div>
          </div>

          {/* Filtros de etiquetas */}
          <div className="mt-4 space-y-2">
            <Label>Etiquetas</Label>
            <div className="flex flex-wrap gap-2">
              {tags.map((tag) => (
                <Badge
                  key={tag.id}
                  variant={selectedTags.includes(tag.id.toString()) ? 'default' : 'outline'}
                  className="cursor-pointer"
                  style={
                    selectedTags.includes(tag.id.toString()) ? { backgroundColor: tag.color } : {}
                  }
                  onClick={() => handleTagToggle(tag.id.toString())}
                >
                  {tag.name}
                </Badge>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Tabla de juegos */}
      <Card>
        <CardHeader>
          <CardTitle>Lista de Juegos ({filteredGames.length})</CardTitle>
          <CardDescription>
            {filteredGames.length === 0 ? 'No se encontraron juegos' : 'Juegos en tu colección'}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead
                    className="cursor-pointer hover:bg-muted/50"
                    onClick={() => handleSort('title')}
                  >
                    Título {sortBy === 'title' && (sortOrder === 'asc' ? '↑' : '↓')}
                  </TableHead>
                  <TableHead>Plataforma</TableHead>
                  <TableHead
                    className="cursor-pointer hover:bg-muted/50"
                    onClick={() => handleSort('releaseYear')}
                  >
                    Año {sortBy === 'releaseYear' && (sortOrder === 'asc' ? '↑' : '↓')}
                  </TableHead>
                  <TableHead
                    className="cursor-pointer hover:bg-muted/50"
                    onClick={() => handleSort('rating')}
                  >
                    Calificación {sortBy === 'rating' && (sortOrder === 'asc' ? '↑' : '↓')}
                  </TableHead>
                  <TableHead>Etiquetas</TableHead>
                  <TableHead>ROM</TableHead>
                  <TableHead className="w-[100px]">Acciones</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredGames.map((game) => (
                  <TableRow
                    key={game.id}
                    className="cursor-pointer hover:bg-muted/50"
                    onClick={() => handleGameClick(game.id)}
                  >
                    <TableCell className="font-medium">{game.title}</TableCell>
                    <TableCell>{game.platform?.name}</TableCell>
                    <TableCell>{game.releaseYear || '-'}</TableCell>
                    <TableCell>
                      {game.rating ? (
                        <div className="flex items-center gap-1">
                          <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                          <span>{game.rating}</span>
                        </div>
                      ) : (
                        '-'
                      )}
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1">
                        {game.tags.map((tag) => (
                          <Badge
                            key={tag.id}
                            variant="secondary"
                            style={{ backgroundColor: tag.color }}
                            className="text-white"
                          >
                            {tag.name}
                          </Badge>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell>
                      {game.romFile ? (
                        <Badge variant="default">✓</Badge>
                      ) : (
                        <Badge variant="secondary">-</Badge>
                      )}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={(e) => {
                            e.stopPropagation();
                            navigate({ to: `/games/${game.id}` });
                          }}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={(e) => {
                            e.stopPropagation();
                            navigate({ to: `/games/${game.id}/edit` });
                          }}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={(e) => {
                            e.stopPropagation();
                            // TODO: Implementar eliminación
                          }}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {/* Paginación */}
          <div className="flex items-center justify-between space-x-2 py-4">
            <div className="text-sm text-muted-foreground">
              Mostrando {filteredGames.length} juegos
            </div>
            <div className="flex items-center space-x-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                disabled={currentPage === 1}
              >
                Anterior
              </Button>
              <span className="text-sm">Página {currentPage}</span>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(currentPage + 1)}
                disabled={filteredGames.length < 10}
              >
                Siguiente
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
