import { useState, useMemo } from 'react';
import { useMyTracks } from '@/features/library/hooks/useMyTracks';
import { useAudio } from '@/context/AudioContext';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Search, Grid, List as ListIcon, Plus, MoreVertical, Play, Clock, FileAudio, Download, Trash2, CheckCircle2, Circle
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { formatDistanceToNow } from 'date-fns';

import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { UploadModal } from '@/features/upload/components/UploadModal';
import { useSearchParams } from 'react-router-dom';
import type { Track } from '@/types';
import { Card } from '@/components/ui/card';
import { parseISO, isValid } from 'date-fns';

const safeFormatDistanceToNow = (value: any, options?: any) => {
  try {
    let date: Date;
    if (typeof value === 'string') {
      date = parseISO(value);
    } else if (value instanceof Date) {
      date = value;
    } else if (typeof value === 'number') {
      date = new Date(value);
    } else {
      return '';
    }

    if (!isValid(date)) return 'unknown time';
    return formatDistanceToNow(date, options);
  } catch (e) {
    return '';
  }
};

export function LibraryPage() {
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedTracks, setSelectedTracks] = useState<Set<string>>(new Set());
  const [searchParams, setSearchParams] = useSearchParams();

  const { playTrack } = useAudio();

  const { data, isLoading } = useMyTracks(1, 100);
  const tracks = data?.tracks || [];

  const filteredTracks = useMemo(() => {
    if (!tracks) return [];
    return tracks.filter((t: Track) =>
      (t.title || '').toLowerCase().includes(searchQuery.toLowerCase()) ||
      String(typeof t.artist === 'string' ? t.artist : t.artist?.name || '').toLowerCase().includes(searchQuery.toLowerCase())
    );
  }, [tracks, searchQuery]);

  const toggleSelection = (id: string) => {
    const newSet = new Set(selectedTracks);
    if (newSet.has(id)) newSet.delete(id);
    else newSet.add(id);
    setSelectedTracks(newSet);
  };

  const isUploadOpen = searchParams.get('action') === 'upload';
  const closeUpload = () => {
    searchParams.delete('action');
    setSearchParams(searchParams);
  };

  const getArtistName = (track: any) => {
    return typeof track.artist === 'string' ? track.artist : track.artist?.name || 'Unknown Artist';
  };

  const formatDuration = (duration: string | number) => {
    const totalSeconds = typeof duration === 'number' ? duration : 0;
    if (totalSeconds === 0 && typeof duration === 'string') return duration;
    return `${Math.floor(totalSeconds / 60)}:${(totalSeconds % 60).toString().padStart(2, '0')}`;
  };

  return (
    <div className="h-full flex flex-col space-y-6 animate-fade-in pb-24">

      {/* 1. Toolbar Sticky */}
      <div className="sticky top-0 z-20 bg-background/80 backdrop-blur-xl border-b border-border py-4 -mx-4 px-4 md:-mx-8 md:px-8 flex flex-col md:flex-row gap-4 justify-between items-center transition-all">
        <div className="flex items-center gap-4 w-full md:w-auto">
          <h1 className="text-2xl font-display font-bold text-foreground hidden md:block">Library</h1>
          <div className="relative flex-1 md:w-80">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="Search..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9 bg-muted/20 border-transparent focus:bg-background focus:ring-1 focus:ring-primary/50 transition-all rounded-xl"
            />
          </div>
        </div>

        <div className="flex items-center gap-3 w-full md:w-auto justify-end">
          <div className="bg-muted/20 p-1 rounded-lg border border-border flex items-center h-10">
            <button
              onClick={() => setViewMode('grid')}
              className={cn("h-8 w-8 flex items-center justify-center rounded-md transition-all", viewMode === 'grid' ? "bg-background text-primary shadow-sm" : "text-muted-foreground hover:text-foreground")}
            >
              <Grid className="w-4 h-4" />
            </button>
            <button
              onClick={() => setViewMode('list')}
              className={cn("h-8 w-8 flex items-center justify-center rounded-md transition-all", viewMode === 'list' ? "bg-background text-primary shadow-sm" : "text-muted-foreground hover:text-foreground")}
            >
              <ListIcon className="w-4 h-4" />
            </button>
          </div>

          <Button
            onClick={() => setSearchParams({ action: 'upload' })}
            className="shadow-[0_0_20px_rgba(var(--cyan-500),0.3)] hover:shadow-[0_0_30px_rgba(var(--cyan-500),0.5)] transition-all bg-primary text-primary-foreground"
          >
            <Plus className="w-4 h-4 mr-2" /> New
          </Button>
        </div>
      </div>

      {/* 2. Content Area */}
      {isLoading ? (
        <div className="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-5 gap-4">
          {Array(10).fill(0).map((_, i) => (
            <div key={i} className="aspect-square bg-muted/10 rounded-2xl animate-pulse" />
          ))}
        </div>
      ) : filteredTracks.length === 0 ? (
        <div className="flex-1 flex flex-col items-center justify-center text-center opacity-60 min-h-[400px]">
          <div className="w-24 h-24 bg-muted/10 rounded-full flex items-center justify-center mb-6 border border-border">
            <FileAudio className="w-10 h-10 text-muted-foreground" />
          </div>
          <h3 className="text-xl font-display font-bold text-foreground mb-2">It's empty here</h3>
          <p className="text-muted-foreground max-w-sm mx-auto mb-8">
            Start by uploading your first audio files to populate your library.
          </p>
          <Button variant="outline" onClick={() => setSearchParams({ action: 'upload' })} className="border-primary/50 text-primary hover:bg-primary/10">
            Upload File
          </Button>
        </div>
      ) : viewMode === 'grid' ? (
        /* GRID VIEW PRO (Nebula Glass) */
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-6">
          {filteredTracks.map((track: Track) => {
            const isSelected = selectedTracks.has(track.id);
            return (
              <Card
                key={track.id}
                variant="glass"
                className={cn(
                  "group relative aspect-[4/5] overflow-hidden cursor-pointer hover:-translate-y-2 transition-transform duration-300",
                  isSelected ? "border-primary ring-1 ring-primary shadow-[0_0_20px_rgba(var(--cyan-500),0.2)]" : "hover:border-primary/30"
                )}
                onClick={() => toggleSelection(track.id)}
              >
                {/* Selection Circle */}
                <div className="absolute top-3 left-3 z-10 opacity-0 group-hover:opacity-100 transition-opacity">
                  {isSelected ? (
                    <CheckCircle2 className="w-6 h-6 text-primary fill-background drop-shadow-[0_0_5px_rgba(0,0,0,0.5)]" />
                  ) : (
                    <Circle className="w-6 h-6 text-white/70 hover:text-white drop-shadow-[0_0_5px_rgba(0,0,0,0.5)]" />
                  )}
                </div>

                {/* Cover Art Placeholder */}
                <div className="h-[60%] w-full bg-gradient-to-br from-background to-black/40 flex items-center justify-center relative group-hover:from-background/80 group-hover:to-black/60 transition-all">
                  {track.coverUrl ? (
                    <img src={track.coverUrl} alt={track.title} className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110" />
                  ) : (
                    <FileAudio className="w-12 h-12 text-muted-foreground/30 group-hover:text-primary/50 transition-colors duration-300" />
                  )}

                  {/* Play Button Overlay */}
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      playTrack(track);
                    }}
                    className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all scale-90 group-hover:scale-100"
                  >
                    <div className="w-14 h-14 rounded-full bg-primary text-primary-foreground flex items-center justify-center shadow-[0_0_30px_rgba(var(--cyan-500),0.6)] hover:scale-110 transition-transform">
                      <Play className="w-6 h-6 ml-1 fill-current" />
                    </div>
                  </button>
                </div>

                {/* Info */}
                <div className="p-4 flex flex-col justify-between h-[40%] bg-black/20 backdrop-blur-sm">
                  <div>
                    <h3 className="font-bold text-sm text-foreground truncate mb-1 group-hover:text-primary transition-colors" title={track.title}>
                      {track.title}
                    </h3>
                    <p className="text-xs text-muted-foreground truncate">
                      {getArtistName(track)}
                    </p>
                  </div>
                  <div className="flex items-center justify-between text-[10px] text-muted-foreground/70 font-mono mt-2">
                    <span className="flex items-center gap-1">
                      <Clock className="w-3 h-3" />
                      {formatDuration(track.duration)}
                    </span>
                    <span>
                      {safeFormatDistanceToNow(track.created_at)}
                    </span>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      ) : (
        /* LIST VIEW PRO */
        <div className="glass rounded-2xl overflow-hidden shadow-lg">
          <table className="w-full text-left text-sm">
            <thead className="bg-black/20 text-xs uppercase font-mono text-muted-foreground">
              <tr>
                <th className="px-6 py-4 w-12 text-center">#</th>
                <th className="px-6 py-4">Title</th>
                <th className="px-6 py-4 hidden md:table-cell">Artist</th>
                <th className="px-6 py-4 hidden sm:table-cell">Date</th>
                <th className="px-6 py-4 text-right">Duration</th>
                <th className="px-6 py-4 w-12"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/50">
              {filteredTracks.map((track: Track, i: number) => (
                <tr
                  key={track.id}
                  className="group hover:bg-white/5 transition-colors cursor-pointer"
                  onClick={() => playTrack(track)}
                >
                  <td className="px-6 py-4 text-center text-muted-foreground group-hover:text-primary">
                    <span className="group-hover:hidden">{i + 1}</span>
                    <Play className="w-4 h-4 hidden group-hover:inline-block fill-current" />
                  </td>
                  <td className="px-6 py-4 font-medium text-foreground group-hover:text-primary transition-colors">
                    {track.title}
                  </td>
                  <td className="px-6 py-4 text-muted-foreground hidden md:table-cell">
                    {getArtistName(track)}
                  </td>
                  <td className="px-6 py-4 text-muted-foreground hidden sm:table-cell font-mono text-xs">
                    {safeFormatDistanceToNow(track.created_at, { addSuffix: true })}
                  </td>
                  <td className="px-6 py-4 text-right text-muted-foreground font-mono text-xs">
                    {formatDuration(track.duration)}
                  </td>
                  <td className="px-6 py-4">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <button className="p-2 hover:bg-white/10 rounded-full transition-colors opacity-0 group-hover:opacity-100 text-muted-foreground">
                          <MoreVertical className="w-4 h-4" />
                        </button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end" className="bg-background/90 backdrop-blur-xl border-border">
                        <DropdownMenuItem className="cursor-pointer gap-2 focus:bg-primary/20">
                          <Download className="w-4 h-4" /> Download
                        </DropdownMenuItem>
                        <DropdownMenuItem className="cursor-pointer gap-2 text-destructive focus:bg-destructive/10 focus:text-destructive">
                          <Trash2 className="w-4 h-4" /> Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Upload Modal */}
      {isUploadOpen && <UploadModal isOpen={true} onClose={closeUpload} />}
    </div>
  );
}
