import { useState } from 'react';
import { useAssets, useDeleteAsset, useBulkDeleteAssets } from '@/hooks/useAssets';
import { useBrands } from '@/hooks/useBrands';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Card,
  CardContent,
} from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Plus,
  Search,
  Image,
  Video,
  FileText,
  Music,
  File,
  Trash2,
  Download,
  Eye,
  Grid,
  List,
  Check,
} from 'lucide-react';
import { Asset } from '@/services/api/assets.api';

const assetTypeIcons: Record<string, typeof Image> = {
  image: Image,
  video: Video,
  document: FileText,
  audio: Music,
  other: File,
};

const assetTypeLabels: Record<string, string> = {
  image: 'Imágenes',
  video: 'Videos',
  document: 'Documentos',
  audio: 'Audio',
  other: 'Otros',
};

function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

export default function AssetsPage() {
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [brandFilter, setBrandFilter] = useState<string>('all');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [selectedAssets, setSelectedAssets] = useState<string[]>([]);

  const { data: brandsData } = useBrands({ limit: 100 });
  const { data, isLoading } = useAssets({
    search,
    page,
    limit: 24,
    type: typeFilter !== 'all' ? typeFilter : undefined,
    brandId: brandFilter !== 'all' ? brandFilter : undefined,
  });
  const deleteAsset = useDeleteAsset();
  const bulkDeleteAssets = useBulkDeleteAssets();

  const handleSelectAsset = (id: string) => {
    setSelectedAssets((prev) =>
      prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id]
    );
  };

  const handleSelectAll = () => {
    if (data?.data) {
      if (selectedAssets.length === data.data.length) {
        setSelectedAssets([]);
      } else {
        setSelectedAssets(data.data.map((a) => a.id));
      }
    }
  };

  const handleDelete = (id: string) => {
    if (confirm('¿Está seguro de eliminar este asset?')) {
      deleteAsset.mutate(id);
    }
  };

  const handleBulkDelete = () => {
    if (confirm(`¿Está seguro de eliminar ${selectedAssets.length} assets?`)) {
      bulkDeleteAssets.mutate(selectedAssets);
      setSelectedAssets([]);
    }
  };

  const renderAssetPreview = (asset: Asset) => {
    if (asset.type === 'image' && asset.url) {
      return (
        <img
          src={asset.thumbnail_url || asset.url}
          alt={asset.alt_text || asset.name}
          className="w-full h-full object-cover"
        />
      );
    }

    const Icon = assetTypeIcons[asset.type] || File;
    return (
      <div className="w-full h-full flex items-center justify-center bg-muted">
        <Icon className="h-12 w-12 text-muted-foreground/50" />
      </div>
    );
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Assets</h1>
          <p className="text-muted-foreground">
            Gestiona imágenes, videos y documentos
          </p>
        </div>
        <Button>
          <Plus className="mr-2 h-4 w-4" />
          Subir Asset
        </Button>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-4">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Buscar assets..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9"
          />
        </div>

        <Select value={typeFilter} onValueChange={setTypeFilter}>
          <SelectTrigger className="w-[150px]">
            <SelectValue placeholder="Tipo" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Todos los tipos</SelectItem>
            {Object.entries(assetTypeLabels).map(([value, label]) => (
              <SelectItem key={value} value={value}>
                {label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Select value={brandFilter} onValueChange={setBrandFilter}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Marca" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Todas las marcas</SelectItem>
            {brandsData?.data?.map((brand) => (
              <SelectItem key={brand.id} value={brand.id}>
                {brand.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <div className="flex items-center gap-1 border rounded-md">
          <Button
            variant={viewMode === 'grid' ? 'secondary' : 'ghost'}
            size="icon"
            className="h-9 w-9"
            onClick={() => setViewMode('grid')}
          >
            <Grid className="h-4 w-4" />
          </Button>
          <Button
            variant={viewMode === 'list' ? 'secondary' : 'ghost'}
            size="icon"
            className="h-9 w-9"
            onClick={() => setViewMode('list')}
          >
            <List className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {/* Selection Actions */}
      {selectedAssets.length > 0 && (
        <div className="flex items-center gap-4 p-3 bg-muted rounded-lg">
          <span className="text-sm font-medium">
            {selectedAssets.length} seleccionados
          </span>
          <Button variant="outline" size="sm" onClick={handleSelectAll}>
            {selectedAssets.length === data?.data?.length
              ? 'Deseleccionar todos'
              : 'Seleccionar todos'}
          </Button>
          <Button
            variant="destructive"
            size="sm"
            onClick={handleBulkDelete}
          >
            <Trash2 className="mr-2 h-4 w-4" />
            Eliminar seleccionados
          </Button>
        </div>
      )}

      {/* Grid/List View */}
      {isLoading ? (
        <div
          className={
            viewMode === 'grid'
              ? 'grid gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6'
              : 'space-y-2'
          }
        >
          {[...Array(12)].map((_, i) => (
            <Card key={i} className="animate-pulse">
              <div
                className={
                  viewMode === 'grid' ? 'aspect-square bg-muted' : 'h-16 bg-muted'
                }
              />
            </Card>
          ))}
        </div>
      ) : data?.data?.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <Image className="h-12 w-12 text-muted-foreground mb-4" />
            <h3 className="text-lg font-semibold">No hay assets</h3>
            <p className="text-muted-foreground mb-4">
              Comienza subiendo tu primer archivo
            </p>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              Subir Asset
            </Button>
          </CardContent>
        </Card>
      ) : viewMode === 'grid' ? (
        <div className="grid gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6">
          {data?.data?.map((asset) => (
            <Card
              key={asset.id}
              className={`group cursor-pointer hover:shadow-md transition-all overflow-hidden ${
                selectedAssets.includes(asset.id) ? 'ring-2 ring-primary' : ''
              }`}
              onClick={() => handleSelectAsset(asset.id)}
            >
              <div className="aspect-square relative">
                {renderAssetPreview(asset)}
                {/* Selection Checkbox */}
                <div
                  className={`absolute top-2 left-2 h-6 w-6 rounded-md border-2 flex items-center justify-center transition-all ${
                    selectedAssets.includes(asset.id)
                      ? 'bg-primary border-primary'
                      : 'bg-white/80 border-gray-300 opacity-0 group-hover:opacity-100'
                  }`}
                >
                  {selectedAssets.includes(asset.id) && (
                    <Check className="h-4 w-4 text-white" />
                  )}
                </div>
                {/* Actions */}
                <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex gap-1">
                  <Button
                    variant="secondary"
                    size="icon"
                    className="h-8 w-8 shadow"
                    onClick={(e) => {
                      e.stopPropagation();
                      window.open(asset.url, '_blank');
                    }}
                  >
                    <Eye className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="secondary"
                    size="icon"
                    className="h-8 w-8 shadow"
                    onClick={(e) => {
                      e.stopPropagation();
                      const a = document.createElement('a');
                      a.href = asset.url;
                      a.download = asset.original_name;
                      a.click();
                    }}
                  >
                    <Download className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="secondary"
                    size="icon"
                    className="h-8 w-8 shadow text-destructive"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDelete(asset.id);
                    }}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>
              <CardContent className="p-3">
                <p className="text-sm font-medium truncate" title={asset.name}>
                  {asset.name}
                </p>
                <p className="text-xs text-muted-foreground">
                  {formatFileSize(asset.size)}
                </p>
              </CardContent>
            </Card>
          ))}
        </div>
      ) : (
        <div className="space-y-2">
          {data?.data?.map((asset) => {
            const Icon = assetTypeIcons[asset.type] || File;
            return (
              <Card
                key={asset.id}
                className={`group cursor-pointer hover:shadow-sm transition-all ${
                  selectedAssets.includes(asset.id) ? 'ring-2 ring-primary' : ''
                }`}
                onClick={() => handleSelectAsset(asset.id)}
              >
                <CardContent className="flex items-center gap-4 p-3">
                  <div
                    className={`h-6 w-6 rounded-md border-2 flex items-center justify-center ${
                      selectedAssets.includes(asset.id)
                        ? 'bg-primary border-primary'
                        : 'border-gray-300'
                    }`}
                  >
                    {selectedAssets.includes(asset.id) && (
                      <Check className="h-4 w-4 text-white" />
                    )}
                  </div>
                  <div className="h-12 w-12 rounded overflow-hidden bg-muted flex-shrink-0">
                    {asset.type === 'image' && asset.thumbnail_url ? (
                      <img
                        src={asset.thumbnail_url}
                        alt={asset.name}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center">
                        <Icon className="h-6 w-6 text-muted-foreground" />
                      </div>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="font-medium truncate">{asset.name}</p>
                    <p className="text-sm text-muted-foreground">
                      {assetTypeLabels[asset.type]} - {formatFileSize(asset.size)}
                    </p>
                  </div>
                  {asset.brand && (
                    <span className="px-2 py-1 bg-muted rounded-md text-xs">
                      {asset.brand.name}
                    </span>
                  )}
                  <div className="opacity-0 group-hover:opacity-100 transition-opacity flex gap-1">
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8"
                      onClick={(e) => {
                        e.stopPropagation();
                        window.open(asset.url, '_blank');
                      }}
                    >
                      <Eye className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8"
                      onClick={(e) => {
                        e.stopPropagation();
                        const a = document.createElement('a');
                        a.href = asset.url;
                        a.download = asset.original_name;
                        a.click();
                      }}
                    >
                      <Download className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8 text-destructive"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleDelete(asset.id);
                      }}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {/* Pagination */}
      {data?.meta && data.meta.totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={!data.meta.hasPreviousPage}
            onClick={() => setPage(page - 1)}
          >
            Anterior
          </Button>
          <span className="text-sm text-muted-foreground">
            Página {data.meta.page} de {data.meta.totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            disabled={!data.meta.hasNextPage}
            onClick={() => setPage(page + 1)}
          >
            Siguiente
          </Button>
        </div>
      )}
    </div>
  );
}
