import React, { useState } from 'react';
import { SearchBar } from '../search/SearchBar';
import { Button } from '../ui/button';
import { UserCard } from '../user/UserCard';
import { CourseCard } from '../education/CourseCard';
import {
  SlidersHorizontal,
  Music,
  User,
  Grid,
  List,
  Loader2,
  Disc,
} from 'lucide-react';
import { Track, User as UserType, Course } from '../../types';
import { searchService } from '../../services/searchService';
import { logger } from '@/utils/logger';

interface SearchPageViewProps {
  onNavigate: (view: string, param?: any) => void;
}

export const SearchPageView: React.FC<SearchPageViewProps> = ({
  onNavigate,
}) => {
  const [query, setQuery] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('list');
  const [showFilters, setShowFilters] = useState(true);
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<{
    tracks: Track[];
    users: UserType[];
    courses: Course[];
  }>({
    tracks: [],
    users: [],
    courses: [],
  });

  // Mock Filters
  const [filters, setFilters] = useState({
    genre: 'All',
    bpmMin: 0,
    bpmMax: 200,
    key: 'Any',
    price: 'All',
  });

  const handleSearch = async (q: string) => {
    setQuery(q);
    setLoading(true);
    try {
      const res = await searchService.global(q);
      setResults({
        tracks: res.tracks,
        users: res.users,
        courses: res.courses || [],
      });
    } catch (e) {
      logger.error('Search failed', {
        error: e instanceof Error ? e.message : String(e),
        stack: e instanceof Error ? e.stack : undefined,
        query: q,
      });
    } finally {
      setLoading(false);
    }
  };

  const tabs = [
    { id: 'all', label: 'All Results' },
    { id: 'tracks', label: 'Tracks', icon: <Music className="w-4 h-4" /> },
    { id: 'artists', label: 'Artists', icon: <User className="w-4 h-4" /> },
    { id: 'courses', label: 'Courses', icon: <Disc className="w-4 h-4" /> },
  ];

  return (
    <div className="animate-fadeIn min-h-screen pb-20">
      {/* Top Bar */}
      <div className="sticky top-16 bg-kodo-void/95 backdrop-blur z-30 pt-6 pb-4 border-b border-kodo-steel/50 mb-6">
        <div className="max-w-3xl mx-auto mb-6">
          <SearchBar onSearch={handleSearch} initialQuery={query} />
        </div>

        <div className="flex justify-between items-center px-4">
          <div className="flex gap-6 overflow-x-auto no-scrollbar">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-2 pb-3 text-sm font-bold uppercase tracking-wider border-b-2 transition-colors whitespace-nowrap ${activeTab === tab.id ? 'border-kodo-cyan text-white' : 'border-transparent text-gray-500 hover:text-gray-300'}`}
              >
                {tab.icon} {tab.label}
              </button>
            ))}
          </div>

          <div className="flex gap-2">
            <Button
              variant={showFilters ? 'primary' : 'ghost'}
              size="sm"
              onClick={() => setShowFilters(!showFilters)}
              icon={<SlidersHorizontal className="w-4 h-4" />}
            >
              Filters
            </Button>
            <div className="bg-kodo-ink p-1 rounded border border-kodo-steel flex">
              <button
                onClick={() => setViewMode('list')}
                className={`p-1.5 rounded ${viewMode === 'list' ? 'bg-kodo-slate text-white' : 'text-gray-500'}`}
              >
                <List className="w-4 h-4" />
              </button>
              <button
                onClick={() => setViewMode('grid')}
                className={`p-1.5 rounded ${viewMode === 'grid' ? 'bg-kodo-slate text-white' : 'text-gray-500'}`}
              >
                <Grid className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="flex gap-8 items-start">
        {/* Sidebar Filters */}
        {showFilters && (
          <div className="w-64 flex-shrink-0 hidden lg:block sticky top-48 space-y-6 animate-slideInLeft">
            <div className="pb-4 border-b border-kodo-steel">
              <h3 className="font-bold text-white mb-4 text-sm uppercase">
                Genre
              </h3>
              <div className="space-y-2">
                {['All', 'Techno', 'House', 'Synthwave', 'Ambient', 'Trap'].map(
                  (g) => (
                    <label
                      key={g}
                      className="flex items-center gap-2 text-sm text-gray-400 hover:text-white cursor-pointer"
                    >
                      <input
                        type="radio"
                        name="genre"
                        checked={filters.genre === g}
                        onChange={() => setFilters({ ...filters, genre: g })}
                        className="bg-transparent border-kodo-steel text-kodo-cyan focus:ring-0"
                      />
                      {g}
                    </label>
                  ),
                )}
              </div>
            </div>

            <div className="pb-4 border-b border-kodo-steel">
              <h3 className="font-bold text-white mb-4 text-sm uppercase">
                BPM Range
              </h3>
              <div className="flex items-center gap-2 text-sm text-gray-400">
                <input
                  className="w-16 bg-kodo-ink border border-kodo-steel rounded px-2 py-1"
                  value={filters.bpmMin}
                  onChange={(e) =>
                    setFilters({ ...filters, bpmMin: Number(e.target.value) })
                  }
                />
                <span>-</span>
                <input
                  className="w-16 bg-kodo-ink border border-kodo-steel rounded px-2 py-1"
                  value={filters.bpmMax}
                  onChange={(e) =>
                    setFilters({ ...filters, bpmMax: Number(e.target.value) })
                  }
                />
              </div>
            </div>

            <div className="pb-4 border-b border-kodo-steel">
              <h3 className="font-bold text-white mb-4 text-sm uppercase">
                Key
              </h3>
              <select className="w-full bg-kodo-ink border border-kodo-steel rounded px-3 py-2 text-sm text-white">
                <option>Any Key</option>
                <option>C Minor</option>
                <option>F# Major</option>
              </select>
            </div>
          </div>
        )}

        {/* Results Area */}
        <div className="flex-1 space-y-8">
          {loading && (
            <div className="flex justify-center py-20">
              <Loader2 className="w-10 h-10 text-kodo-cyan animate-spin" />
            </div>
          )}

          {!query && !loading && (
            <div className="text-center py-20 text-gray-500">
              <p>Enter a search term to begin.</p>
            </div>
          )}

          {!loading && query && (
            <>
              {(activeTab === 'all' || activeTab === 'tracks') &&
                results.tracks.length > 0 && (
                  <div className="space-y-4">
                    <h3 className="text-sm font-bold text-gray-400 uppercase tracking-widest">
                      Tracks
                    </h3>
                    {/* Reusing the layout of TrackList but injecting our results would require refactoring TrackList or duplicating the loop here. 
                                    For simplicity, let's render a basic list here using the results. 
                                */}
                    {results.tracks.map((track) => (
                      <div
                        key={track.id}
                        className="bg-kodo-ink p-3 rounded-lg border border-kodo-steel flex items-center gap-4"
                      >
                        <img
                          src={track.coverUrl}
                          className="w-10 h-10 rounded"
                        />
                        <div className="flex-1">
                          <div className="text-white font-bold">
                            {track.title}
                          </div>
                          <div className="text-gray-400 text-xs">
                            {track.artist}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}

              {(activeTab === 'all' || activeTab === 'artists') &&
                results.users.length > 0 && (
                  <div className="space-y-4">
                    <h3 className="text-sm font-bold text-gray-400 uppercase tracking-widest">
                      Artists
                    </h3>
                    <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                      {results.users.map((user) => (
                        <UserCard
                          key={user.id}
                          user={user}
                          onView={() => onNavigate('profile', user.id)}
                        />
                      ))}
                    </div>
                  </div>
                )}

              {(activeTab === 'all' || activeTab === 'courses') &&
                results.courses.length > 0 && (
                  <div className="space-y-4">
                    <h3 className="text-sm font-bold text-gray-400 uppercase tracking-widest">
                      Courses
                    </h3>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {results.courses.map((course) => (
                        <CourseCard
                          key={course.id}
                          course={course}
                          onClick={(c) => onNavigate('course-detail', c)}
                        />
                      ))}
                    </div>
                  </div>
                )}

              {!loading &&
                query &&
                results.tracks.length === 0 &&
                results.users.length === 0 &&
                results.courses.length === 0 && (
                  <div className="text-center py-20 text-gray-500">
                    <p>No results found for "{query}".</p>
                  </div>
                )}
            </>
          )}
        </div>
      </div>
    </div>
  );
};
