'use client';

import { useState, useCallback, useRef } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Separator } from '@/components/ui/separator';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Upload,
  Search,
  Grid3X3,
  List,
  Folder,
  FolderPlus,
  Star,
  Trash2,
  Download,
  Copy,
  MoreVertical,
  Image,
  Volume2,
  Box,
  FileCode,
  Sparkles,
  Database,
  Play,
  Package,
  Palette,
  Layout,
  Filter,
  SortAsc,
  SortDesc,
  X,
  Heart,
  Tag,
  Info,
  Music,
} from 'lucide-react';
import { toast } from 'sonner';

import { useAssetStore } from '@/stores/asset-store';
import {
  Asset,
  AssetType,
  AssetCategory,
  ASSET_TYPE_ICONS,
  ASSET_TYPE_COLORS,
  CATEGORY_LABELS,
  formatFileSize,
  getAcceptedFileTypes,
} from '@/lib/assets/types';

interface AssetLibraryProps {
  isOpen: boolean;
  onClose: () => void;
  onAssetSelect?: (asset: Asset) => void;
}

// Asset type icons mapping
const TypeIcon: Record<AssetType, React.ReactNode> = {
  model: <Box className="h-4 w-4" />,
  texture: <Image className="h-4 w-4" />,
  audio: <Volume2 className="h-4 w-4" />,
  animation: <Play className="h-4 w-4" />,
  script: <FileCode className="h-4 w-4" />,
  prefab: <Package className="h-4 w-4" />,
  material: <Palette className="h-4 w-4" />,
  particle: <Sparkles className="h-4 w-4" />,
  ui: <Layout className="h-4 w-4" />,
  data: <Database className="h-4 w-4" />,
};

export default function AssetLibrary({
  isOpen,
  onClose,
  onAssetSelect,
}: AssetLibraryProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedType, setSelectedType] = useState<AssetType | 'all'>('all');
  const [isDragging, setIsDragging] = useState(false);

  const {
    assets,
    folders,
    selectedAssetId,
    viewMode,
    sort,
    addAsset,
    removeAsset,
    updateAsset,
    setSelectedAsset,
    setViewMode,
    setSort,
    setFilter,
    toggleFavorite,
    getFilteredAssets,
    getFavorites,
  } = useAssetStore();

  // Handle file upload
  const handleFileUpload = useCallback(
    async (files: FileList | File[]) => {
      const fileArray = Array.from(files);

      for (const file of fileArray) {
        try {
          await addAsset(file);
          toast.success(`Uploaded ${file.name}`);
        } catch (error) {
          toast.error(`Failed to upload ${file.name}`);
        }
      }
    },
    [addAsset]
  );

  // Handle drag and drop
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      setIsDragging(false);
      if (e.dataTransfer.files.length > 0) {
        handleFileUpload(e.dataTransfer.files);
      }
    },
    [handleFileUpload]
  );

  // Filter assets
  const filteredAssets = getFilteredAssets().filter((asset) => {
    const matchesSearch =
      !searchQuery ||
      asset.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      asset.tags.some((t) => t.toLowerCase().includes(searchQuery.toLowerCase()));

    const matchesType = selectedType === 'all' || asset.type === selectedType;

    return matchesSearch && matchesType;
  });

  const favorites = getFavorites();
  const selectedAsset = assets.find((a) => a.id === selectedAssetId);

  // Asset type counts
  const typeCounts = assets.reduce((acc, asset) => {
    acc[asset.type] = (acc[asset.type] || 0) + 1;
    return acc;
  }, {} as Record<AssetType, number>);

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="max-w-6xl max-h-[85vh] p-0 flex flex-col">
        <DialogHeader className="px-4 py-3 border-b">
          <DialogTitle className="flex items-center gap-2">
            <Package className="h-5 w-5 text-primary" />
            Asset Library
            <Badge variant="secondary" className="ml-2">
              {assets.length} assets
            </Badge>
          </DialogTitle>
        </DialogHeader>

        <div className="flex flex-1 min-h-0">
          {/* Sidebar */}
          <div className="w-56 border-r bg-muted/30 flex flex-col">
            {/* Upload Button */}
            <div className="p-3">
              <input
                ref={fileInputRef}
                type="file"
                multiple
                accept={getAcceptedFileTypes()}
                onChange={(e) => e.target.files && handleFileUpload(e.target.files)}
                className="hidden"
              />
              <Button
                className="w-full"
                onClick={() => fileInputRef.current?.click()}
              >
                <Upload className="h-4 w-4 mr-2" />
                Upload Assets
              </Button>
            </div>

            <Separator />

            {/* Quick Filters */}
            <ScrollArea className="flex-1">
              <div className="p-2 space-y-1">
                <button
                  onClick={() => setSelectedType('all')}
                  className={`w-full flex items-center gap-2 px-3 py-2 rounded-md text-sm transition-colors ${
                    selectedType === 'all'
                      ? 'bg-primary/10 text-primary'
                      : 'hover:bg-muted'
                  }`}
                >
                  <Grid3X3 className="h-4 w-4" />
                  <span>All Assets</span>
                  <span className="ml-auto text-xs text-muted-foreground">
                    {assets.length}
                  </span>
                </button>

                <button
                  onClick={() => setFilter({ favorite: true })}
                  className="w-full flex items-center gap-2 px-3 py-2 rounded-md text-sm hover:bg-muted transition-colors"
                >
                  <Star className="h-4 w-4 text-yellow-500" />
                  <span>Favorites</span>
                  <span className="ml-auto text-xs text-muted-foreground">
                    {favorites.length}
                  </span>
                </button>

                <Separator className="my-2" />

                <p className="px-3 py-1 text-xs font-medium text-muted-foreground uppercase">
                  By Type
                </p>

                {(Object.keys(TypeIcon) as AssetType[]).map((type) => (
                  <button
                    key={type}
                    onClick={() => setSelectedType(type)}
                    className={`w-full flex items-center gap-2 px-3 py-2 rounded-md text-sm transition-colors ${
                      selectedType === type
                        ? 'bg-primary/10 text-primary'
                        : 'hover:bg-muted'
                    }`}
                  >
                    <span style={{ color: ASSET_TYPE_COLORS[type] }}>
                      {TypeIcon[type]}
                    </span>
                    <span className="capitalize">{type}</span>
                    <span className="ml-auto text-xs text-muted-foreground">
                      {typeCounts[type] || 0}
                    </span>
                  </button>
                ))}
              </div>
            </ScrollArea>

            {/* Folders */}
            <Separator />
            <div className="p-2">
              <div className="flex items-center justify-between px-2 py-1">
                <span className="text-xs font-medium text-muted-foreground uppercase">
                  Folders
                </span>
                <Button variant="ghost" size="icon" className="h-6 w-6">
                  <FolderPlus className="h-3 w-3" />
                </Button>
              </div>
              {folders.map((folder) => (
                <button
                  key={folder.id}
                  className="w-full flex items-center gap-2 px-3 py-2 rounded-md text-sm hover:bg-muted transition-colors"
                >
                  <Folder className="h-4 w-4 text-yellow-500" />
                  <span>{folder.name}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Main Content */}
          <div className="flex-1 flex flex-col min-h-0">
            {/* Toolbar */}
            <div className="flex items-center gap-2 p-3 border-b">
              <div className="relative flex-1 max-w-md">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Search assets..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-9"
                />
              </div>

              <Select
                value={sort.field}
                onValueChange={(field: any) => setSort({ ...sort, field })}
              >
                <SelectTrigger className="w-[140px]">
                  <SelectValue placeholder="Sort by" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="createdAt">Date Added</SelectItem>
                  <SelectItem value="name">Name</SelectItem>
                  <SelectItem value="fileSize">Size</SelectItem>
                  <SelectItem value="type">Type</SelectItem>
                </SelectContent>
              </Select>

              <Button
                variant="ghost"
                size="icon"
                onClick={() =>
                  setSort({
                    ...sort,
                    direction: sort.direction === 'asc' ? 'desc' : 'asc',
                  })
                }
              >
                {sort.direction === 'asc' ? (
                  <SortAsc className="h-4 w-4" />
                ) : (
                  <SortDesc className="h-4 w-4" />
                )}
              </Button>

              <Separator orientation="vertical" className="h-6" />

              <Button
                variant={viewMode === 'grid' ? 'secondary' : 'ghost'}
                size="icon"
                onClick={() => setViewMode('grid')}
              >
                <Grid3X3 className="h-4 w-4" />
              </Button>
              <Button
                variant={viewMode === 'list' ? 'secondary' : 'ghost'}
                size="icon"
                onClick={() => setViewMode('list')}
              >
                <List className="h-4 w-4" />
              </Button>
            </div>

            {/* Drop Zone / Asset Grid */}
            <div
              className={`flex-1 min-h-0 relative ${
                isDragging ? 'bg-primary/5' : ''
              }`}
              onDragOver={handleDragOver}
              onDragLeave={handleDragLeave}
              onDrop={handleDrop}
            >
              {isDragging && (
                <div className="absolute inset-0 flex items-center justify-center bg-primary/10 border-2 border-dashed border-primary z-10">
                  <div className="text-center">
                    <Upload className="h-12 w-12 mx-auto text-primary mb-2" />
                    <p className="text-lg font-medium text-primary">
                      Drop files to upload
                    </p>
                  </div>
                </div>
              )}

              {filteredAssets.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-full text-center p-8">
                  <Package className="h-16 w-16 text-muted-foreground/50 mb-4" />
                  <h3 className="text-lg font-medium mb-2">No assets found</h3>
                  <p className="text-sm text-muted-foreground mb-4">
                    {searchQuery
                      ? `No results for "${searchQuery}"`
                      : 'Upload some assets to get started'}
                  </p>
                  <Button onClick={() => fileInputRef.current?.click()}>
                    <Upload className="h-4 w-4 mr-2" />
                    Upload Assets
                  </Button>
                </div>
              ) : (
                <ScrollArea className="h-full">
                  {viewMode === 'grid' ? (
                    <div className="grid grid-cols-4 gap-4 p-4">
                      {filteredAssets.map((asset) => (
                        <AssetCard
                          key={asset.id}
                          asset={asset}
                          isSelected={selectedAssetId === asset.id}
                          onSelect={() => setSelectedAsset(asset.id)}
                          onDoubleClick={() => onAssetSelect?.(asset)}
                          onFavorite={() => toggleFavorite(asset.id)}
                          onDelete={() => removeAsset(asset.id)}
                        />
                      ))}
                    </div>
                  ) : (
                    <div className="divide-y">
                      {filteredAssets.map((asset) => (
                        <AssetRow
                          key={asset.id}
                          asset={asset}
                          isSelected={selectedAssetId === asset.id}
                          onSelect={() => setSelectedAsset(asset.id)}
                          onDoubleClick={() => onAssetSelect?.(asset)}
                          onFavorite={() => toggleFavorite(asset.id)}
                          onDelete={() => removeAsset(asset.id)}
                        />
                      ))}
                    </div>
                  )}
                </ScrollArea>
              )}
            </div>
          </div>

          {/* Details Panel */}
          {selectedAsset && (
            <div className="w-72 border-l bg-muted/30 flex flex-col">
              <div className="p-4 border-b">
                <div className="flex items-start justify-between">
                  <h3 className="font-medium truncate pr-2">{selectedAsset.name}</h3>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-6 w-6"
                    onClick={() => setSelectedAsset(null)}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
                <Badge
                  variant="secondary"
                  className="mt-2"
                  style={{ color: ASSET_TYPE_COLORS[selectedAsset.type] }}
                >
                  {selectedAsset.type}
                </Badge>
              </div>

              {/* Preview */}
              <div className="p-4 border-b">
                <div className="aspect-square bg-muted rounded-lg flex items-center justify-center overflow-hidden">
                  {selectedAsset.thumbnailUrl ? (
                    <img
                      src={selectedAsset.thumbnailUrl}
                      alt={selectedAsset.name}
                      className="w-full h-full object-contain"
                    />
                  ) : selectedAsset.type === 'audio' ? (
                    <div className="text-center p-4">
                      <Music className="h-12 w-12 mx-auto text-muted-foreground mb-2" />
                      {selectedAsset.dataUrl && (
                        <audio controls className="w-full mt-2">
                          <source src={selectedAsset.dataUrl} />
                        </audio>
                      )}
                    </div>
                  ) : (
                    <div
                      className="text-muted-foreground"
                      style={{ color: ASSET_TYPE_COLORS[selectedAsset.type] }}
                    >
                      {TypeIcon[selectedAsset.type]}
                    </div>
                  )}
                </div>
              </div>

              {/* Metadata */}
              <ScrollArea className="flex-1">
                <div className="p-4 space-y-4">
                  <div>
                    <p className="text-xs text-muted-foreground uppercase mb-1">
                      File Info
                    </p>
                    <div className="space-y-1 text-sm">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">Size</span>
                        <span>{formatFileSize(selectedAsset.metadata.fileSize)}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">Format</span>
                        <span className="uppercase">
                          {selectedAsset.metadata.extension}
                        </span>
                      </div>
                      {selectedAsset.metadata.width && (
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">Dimensions</span>
                          <span>
                            {selectedAsset.metadata.width}×{selectedAsset.metadata.height}
                          </span>
                        </div>
                      )}
                      {selectedAsset.metadata.duration && (
                        <div className="flex justify-between">
                          <span className="text-muted-foreground">Duration</span>
                          <span>{selectedAsset.metadata.duration.toFixed(1)}s</span>
                        </div>
                      )}
                    </div>
                  </div>

                  {selectedAsset.tags.length > 0 && (
                    <div>
                      <p className="text-xs text-muted-foreground uppercase mb-2">
                        Tags
                      </p>
                      <div className="flex flex-wrap gap-1">
                        {selectedAsset.tags.map((tag) => (
                          <Badge key={tag} variant="outline" className="text-xs">
                            {tag}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}

                  <div>
                    <p className="text-xs text-muted-foreground uppercase mb-2">
                      Actions
                    </p>
                    <div className="flex flex-wrap gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => toggleFavorite(selectedAsset.id)}
                      >
                        <Star
                          className={`h-4 w-4 mr-1 ${
                            selectedAsset.favorite ? 'fill-yellow-500 text-yellow-500' : ''
                          }`}
                        />
                        {selectedAsset.favorite ? 'Unfavorite' : 'Favorite'}
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          // Copy asset reference
                          navigator.clipboard.writeText(selectedAsset.id);
                          toast.success('Asset ID copied!');
                        }}
                      >
                        <Copy className="h-4 w-4 mr-1" />
                        Copy ID
                      </Button>
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => {
                          removeAsset(selectedAsset.id);
                          toast.success('Asset deleted');
                        }}
                      >
                        <Trash2 className="h-4 w-4 mr-1" />
                        Delete
                      </Button>
                    </div>
                  </div>
                </div>
              </ScrollArea>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

// Asset Card Component (Grid View)
function AssetCard({
  asset,
  isSelected,
  onSelect,
  onDoubleClick,
  onFavorite,
  onDelete,
}: {
  asset: Asset;
  isSelected: boolean;
  onSelect: () => void;
  onDoubleClick: () => void;
  onFavorite: () => void;
  onDelete: () => void;
}) {
  return (
    <div
      className={`group relative rounded-lg border bg-card overflow-hidden cursor-pointer transition-all ${
        isSelected ? 'ring-2 ring-primary border-primary' : 'hover:border-primary/50'
      }`}
      onClick={onSelect}
      onDoubleClick={onDoubleClick}
    >
      {/* Thumbnail */}
      <div className="aspect-square bg-muted flex items-center justify-center overflow-hidden">
        {asset.thumbnailUrl ? (
          <img
            src={asset.thumbnailUrl}
            alt={asset.name}
            className="w-full h-full object-cover"
          />
        ) : (
          <div style={{ color: ASSET_TYPE_COLORS[asset.type] }}>
            {TypeIcon[asset.type]}
          </div>
        )}
      </div>

      {/* Info */}
      <div className="p-2">
        <p className="text-sm font-medium truncate">{asset.name}</p>
        <p className="text-xs text-muted-foreground">
          {formatFileSize(asset.metadata.fileSize)}
        </p>
      </div>

      {/* Favorite Badge */}
      {asset.favorite && (
        <Star className="absolute top-2 right-2 h-4 w-4 fill-yellow-500 text-yellow-500" />
      )}

      {/* Hover Actions */}
      <div className="absolute top-2 left-2 opacity-0 group-hover:opacity-100 transition-opacity">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="secondary" size="icon" className="h-6 w-6">
              <MoreVertical className="h-3 w-3" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent>
            <DropdownMenuItem onClick={onFavorite}>
              <Star className="h-4 w-4 mr-2" />
              {asset.favorite ? 'Unfavorite' : 'Favorite'}
            </DropdownMenuItem>
            <DropdownMenuItem>
              <Download className="h-4 w-4 mr-2" />
              Download
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem className="text-destructive" onClick={onDelete}>
              <Trash2 className="h-4 w-4 mr-2" />
              Delete
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {/* Type Badge */}
      <Badge
        variant="secondary"
        className="absolute bottom-2 right-2 text-xs"
        style={{ color: ASSET_TYPE_COLORS[asset.type] }}
      >
        {asset.type}
      </Badge>
    </div>
  );
}

// Asset Row Component (List View)
function AssetRow({
  asset,
  isSelected,
  onSelect,
  onDoubleClick,
  onFavorite,
  onDelete,
}: {
  asset: Asset;
  isSelected: boolean;
  onSelect: () => void;
  onDoubleClick: () => void;
  onFavorite: () => void;
  onDelete: () => void;
}) {
  return (
    <div
      className={`flex items-center gap-4 px-4 py-3 cursor-pointer transition-colors ${
        isSelected ? 'bg-primary/10' : 'hover:bg-muted/50'
      }`}
      onClick={onSelect}
      onDoubleClick={onDoubleClick}
    >
      {/* Thumbnail */}
      <div className="w-10 h-10 rounded bg-muted flex items-center justify-center overflow-hidden flex-shrink-0">
        {asset.thumbnailUrl ? (
          <img
            src={asset.thumbnailUrl}
            alt={asset.name}
            className="w-full h-full object-cover"
          />
        ) : (
          <div style={{ color: ASSET_TYPE_COLORS[asset.type] }}>
            {TypeIcon[asset.type]}
          </div>
        )}
      </div>

      {/* Name */}
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium truncate">{asset.name}</p>
        <p className="text-xs text-muted-foreground capitalize">{asset.type}</p>
      </div>

      {/* Size */}
      <span className="text-sm text-muted-foreground w-20 text-right">
        {formatFileSize(asset.metadata.fileSize)}
      </span>

      {/* Favorite */}
      <Button
        variant="ghost"
        size="icon"
        className="h-8 w-8"
        onClick={(e) => {
          e.stopPropagation();
          onFavorite();
        }}
      >
        <Star
          className={`h-4 w-4 ${
            asset.favorite ? 'fill-yellow-500 text-yellow-500' : ''
          }`}
        />
      </Button>

      {/* Actions */}
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="ghost" size="icon" className="h-8 w-8">
            <MoreVertical className="h-4 w-4" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuItem>
            <Download className="h-4 w-4 mr-2" />
            Download
          </DropdownMenuItem>
          <DropdownMenuItem>
            <Copy className="h-4 w-4 mr-2" />
            Copy ID
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem className="text-destructive" onClick={onDelete}>
            <Trash2 className="h-4 w-4 mr-2" />
            Delete
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
}
