'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import { searchProfiles, SearchFilters } from '@/lib/marketplace/typesenseClient';
import { createClient } from '@/lib/supabase/client';
import { Suspense } from 'react';

const SKILL_OPTIONS = [
  'Director of Photography',
  'Camera Operator',
  'DIT',
  'Gaffer',
  'Grip',
  'Production Sound Mixer',
  'Boom Operator',
  'Sound Designer',
  'Director',
  'Producer',
  'Editor',
  'Colorist',
  'VFX Artist',
  'Technical Director',
  'Broadcast Engineer',
  'Livestream Producer',
];

const VENDOR_CATEGORIES = [
  'Full-Service Production Company',
  'Equipment Rental House',
  'Studio / Stage Rental',
  'Post Production Facility',
  'Animation Studio',
  'Drone Services Company',
];

interface ProfileCard {
  id: string;
  slug: string;
  type: 'crew' | 'vendor';
  name: string;
  location: string;
  category?: string;
  skills?: string[];
  day_rate?: number;
  bio?: string;
  headshot_url?: string;
  logo_url?: string;
  featured: boolean;
  union_status?: string;
}

export default function MarketplaceSearchPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-[#F8FAFC] flex items-center justify-center">
          <div className="w-8 h-8 border-4 border-[#CC0000] border-t-transparent rounded-full animate-spin" />
        </div>
      }
    >
      <SearchPageInner />
    </Suspense>
  );
}

function SearchPageInner() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const supabase = createClient();

  const [query, setQuery] = useState(searchParams.get('q') || '');
  const [filterType, setFilterType] = useState<'all' | 'crew' | 'vendor'>(
    (searchParams.get('type') as any) || 'all'
  );
  const [filterLocation, setFilterLocation] = useState(searchParams.get('location') || '');
  const [filterCategory, setFilterCategory] = useState(searchParams.get('category') || '');
  const [filterUnion, setFilterUnion] = useState('');
  const [filterRateMin, setFilterRateMin] = useState('');
  const [filterRateMax, setFilterRateMax] = useState('');
  const [featuredOnly, setFeaturedOnly] = useState(false);

  const [results, setResults] = useState<ProfileCard[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [typesenseAvailable, setTypesenseAvailable] = useState(true);

  const fetchFromSupabase = useCallback(async (filters: SearchFilters) => {
    // Fallback: query Supabase directly when Typesense is unavailable
    let crewQuery = supabase
      .from('marketplace_crew_details')
      .select(`
        *,
        marketplace_profiles!inner(id, slug, status, subscription_tier)
      `)
      .eq('marketplace_profiles.status', 'active');

    if (filters.query && filters.query !== '*') {
      crewQuery = crewQuery.ilike('name', `%${filters.query}%`);
    }
    if (filters.location) {
      crewQuery = crewQuery.ilike('location', `%${filters.location}%`);
    }

    let vendorQuery = supabase
      .from('marketplace_vendor_details')
      .select(`
        *,
        marketplace_profiles!inner(id, slug, status, subscription_tier)
      `)
      .eq('marketplace_profiles.status', 'active');

    if (filters.query && filters.query !== '*') {
      vendorQuery = vendorQuery.ilike('company_name', `%${filters.query}%`);
    }
    if (filters.category) {
      vendorQuery = vendorQuery.ilike('category', `%${filters.category}%`);
    }

    const cards: ProfileCard[] = [];

    if (filters.type === 'all' || filters.type === 'crew') {
      const { data: crewData } = await crewQuery.limit(20);
      (crewData || []).forEach((row: any) => {
        cards.push({
          id: row.marketplace_profiles?.id,
          slug: row.marketplace_profiles?.slug,
          type: 'crew',
          name: row.name,
          location: row.location,
          skills: row.skills || [],
          day_rate: row.day_rate,
          bio: row.bio,
          headshot_url: row.headshot_url,
          featured: row.marketplace_profiles?.subscription_tier === 'featured',
          union_status: row.union_status,
        });
      });
    }

    if (filters.type === 'all' || filters.type === 'vendor') {
      const { data: vendorData } = await vendorQuery.limit(20);
      (vendorData || []).forEach((row: any) => {
        cards.push({
          id: row.marketplace_profiles?.id,
          slug: row.marketplace_profiles?.slug,
          type: 'vendor',
          name: row.company_name,
          location: row.location,
          category: row.category,
          bio: row.description,
          logo_url: row.logo_url,
          featured: row.marketplace_profiles?.subscription_tier === 'featured',
        });
      });
    }

    return cards;
  }, [supabase]);

  const doSearch = useCallback(async () => {
    setLoading(true);
    setError('');

    const filters: SearchFilters = {
      query: query || '*',
      type: filterType,
      location: filterLocation || undefined,
      category: filterCategory || undefined,
      union_status: filterUnion || undefined,
      day_rate_min: filterRateMin ? parseInt(filterRateMin) : undefined,
      day_rate_max: filterRateMax ? parseInt(filterRateMax) : undefined,
      featured_only: featuredOnly,
      page,
      per_page: 20,
    };

    try {
      const { crew, vendors, error: tsError } = await searchProfiles(filters);

      if (tsError || (!crew && !vendors)) {
        // Typesense unavailable — fall back to Supabase
        setTypesenseAvailable(false);
        const cards = await fetchFromSupabase(filters);
        setResults(cards);
        setTotal(cards.length);
      } else {
        setTypesenseAvailable(true);
        const cards: ProfileCard[] = [];

        (crew?.hits || []).forEach((hit: any) => {
          const doc = hit.document;
          cards.push({
            id: doc.id,
            slug: doc.slug,
            type: 'crew',
            name: doc.name,
            location: doc.location,
            skills: doc.skills || [],
            day_rate: doc.day_rate,
            bio: doc.bio,
            headshot_url: doc.headshot_url,
            featured: doc.featured,
            union_status: doc.union_status,
          });
        });

        (vendors?.hits || []).forEach((hit: any) => {
          const doc = hit.document;
          cards.push({
            id: doc.id,
            slug: doc.slug,
            type: 'vendor',
            name: doc.company_name,
            location: doc.location,
            category: doc.category,
            bio: doc.description,
            logo_url: doc.logo_url,
            featured: doc.featured,
          });
        });

        setResults(cards);
        setTotal((crew?.found || 0) + (vendors?.found || 0));
      }
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [query, filterType, filterLocation, filterCategory, filterUnion, filterRateMin, filterRateMax, featuredOnly, page, fetchFromSupabase]);

  useEffect(() => {
    doSearch();
  }, [doSearch]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setPage(1);
    doSearch();
  };

  return (
    <div className="min-h-screen bg-[#F8FAFC] text-white">
      <Header />
      <div className="max-w-7xl mx-auto px-4 py-24">
        {/* Breadcrumb */}
        <div className="flex items-center gap-2 text-sm text-gray-500 mb-6">
          <Link href="/marketplace" className="hover:text-[#CC0000]">
            Marketplace
          </Link>
          <span>/</span>
          <span className="text-white">Search</span>
        </div>

        <h1 className="text-3xl font-black uppercase tracking-wide mb-8">
          Find Crew & Vendors
        </h1>

        {!typesenseAvailable && (
          <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-lg px-4 py-3 text-sm text-yellow-400 mb-6">
            ⚡ Search is running in basic mode. Connect Typesense for full-text search and advanced
            filtering.
          </div>
        )}

        <div className="flex flex-col lg:flex-row gap-8">
          {/* Sidebar filters */}
          <aside className="lg:w-64 flex-shrink-0">
            <form onSubmit={handleSearch} className="space-y-5">
              <div>
                <label className="block text-xs text-gray-400 uppercase tracking-wide mb-2">
                  Search
                </label>
                <input
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                  placeholder="Name, skill, company..."
                />
              </div>

              <div>
                <label className="block text-xs text-gray-400 uppercase tracking-wide mb-2">
                  Type
                </label>
                <div className="flex gap-2">
                  {(['all', 'crew', 'vendor'] as const).map((t) => (
                    <button
                      key={t}
                      type="button"
                      onClick={() => setFilterType(t)}
                      className={`flex-1 py-2 text-xs font-bold rounded-lg border transition-colors capitalize ${
                        filterType === t
                          ? 'bg-[#CC0000] border-[#CC0000] text-white'
                          : 'bg-transparent border-white/20 text-gray-400 hover:border-white/40'
                      }`}
                    >
                      {t}
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-xs text-gray-400 uppercase tracking-wide mb-2">
                  Location
                </label>
                <input
                  value={filterLocation}
                  onChange={(e) => setFilterLocation(e.target.value)}
                  className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                  placeholder="City, State..."
                />
              </div>

              {(filterType === 'all' || filterType === 'crew') && (
                <>
                  <div>
                    <label className="block text-xs text-gray-400 uppercase tracking-wide mb-2">
                      Union Status
                    </label>
                    <select
                      value={filterUnion}
                      onChange={(e) => setFilterUnion(e.target.value)}
                      className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                    >
                      <option value="">Any</option>
                      <option value="non_union">Non-Union</option>
                      <option value="iatse">IATSE</option>
                      <option value="sag_aftra">SAG-AFTRA</option>
                      <option value="teamsters">Teamsters</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs text-gray-400 uppercase tracking-wide mb-2">
                      Day Rate Range
                    </label>
                    <div className="flex gap-2">
                      <input
                        type="number"
                        value={filterRateMin}
                        onChange={(e) => setFilterRateMin(e.target.value)}
                        className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                        placeholder="Min $"
                      />
                      <input
                        type="number"
                        value={filterRateMax}
                        onChange={(e) => setFilterRateMax(e.target.value)}
                        className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                        placeholder="Max $"
                      />
                    </div>
                  </div>
                </>
              )}

              {(filterType === 'all' || filterType === 'vendor') && (
                <div>
                  <label className="block text-xs text-gray-400 uppercase tracking-wide mb-2">
                    Vendor Category
                  </label>
                  <select
                    value={filterCategory}
                    onChange={(e) => setFilterCategory(e.target.value)}
                    className="w-full bg-[#FFFFFF] border border-white/20 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:border-[#CC0000]"
                  >
                    <option value="">All Categories</option>
                    {VENDOR_CATEGORIES.map((c) => (
                      <option key={c} value={c}>
                        {c}
                      </option>
                    ))}
                  </select>
                </div>
              )}

              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id="featured"
                  checked={featuredOnly}
                  onChange={(e) => setFeaturedOnly(e.target.checked)}
                  className="accent-[#CC0000]"
                />
                <label htmlFor="featured" className="text-sm text-gray-400 cursor-pointer">
                  Featured only
                </label>
              </div>

              <button
                type="submit"
                className="w-full bg-[#CC0000] hover:bg-red-700 text-white font-bold py-2.5 rounded-lg text-sm transition-colors"
              >
                Search
              </button>
            </form>
          </aside>

          {/* Results */}
          <div className="flex-1">
            <div className="flex items-center justify-between mb-4">
              <p className="text-sm text-gray-400">
                {loading ? 'Searching...' : `${total} result${total !== 1 ? 's' : ''} found`}
              </p>
              <Link
                href="/marketplace/join"
                className="text-xs text-[#CC0000] hover:underline font-semibold"
              >
                + Add Your Profile
              </Link>
            </div>

            {error && (
              <div className="bg-red-500/10 border border-red-500/30 rounded-lg px-4 py-3 text-sm text-red-400 mb-4">
                {error}
              </div>
            )}

            {loading ? (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {[...Array(6)].map((_, i) => (
                  <div
                    key={i}
                    className="bg-[#FFFFFF] rounded-xl p-5 animate-pulse h-40"
                  />
                ))}
              </div>
            ) : results.length === 0 ? (
              <div className="text-center py-20 text-gray-500">
                <div className="text-4xl mb-4">🔍</div>
                <p className="text-lg font-semibold mb-2">No results found</p>
                <p className="text-sm">
                  Try adjusting your filters or{' '}
                  <Link href="/marketplace/join" className="text-[#CC0000] hover:underline">
                    add your profile
                  </Link>
                </p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {results.map((profile) => (
                  <Link
                    key={profile.id}
                    href={`/marketplace/profile/${profile.slug}`}
                    className="bg-[#FFFFFF] hover:bg-[#222] border border-white/10 hover:border-[#CC0000]/30 rounded-xl p-5 transition-all block"
                  >
                    <div className="flex items-start gap-4">
                      {/* Avatar */}
                      <div className="w-14 h-14 rounded-full bg-[#CC0000]/20 flex-shrink-0 overflow-hidden flex items-center justify-center text-xl font-bold text-[#CC0000]">
                        {profile.headshot_url || profile.logo_url ? (
                          <img
                            src={profile.headshot_url || profile.logo_url}
                            alt={`${profile.name} profile photo`}
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          profile.name.charAt(0).toUpperCase()
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="font-bold text-white truncate">{profile.name}</span>
                          {profile.featured && (
                            <span className="text-xs bg-yellow-500/20 text-yellow-400 border border-yellow-500/30 px-2 py-0.5 rounded-full font-semibold">
                              Featured
                            </span>
                          )}
                          <span
                            className={`text-xs px-2 py-0.5 rounded-full font-semibold ${
                              profile.type === 'crew' ?'bg-blue-500/20 text-blue-400' :'bg-purple-500/20 text-purple-400'
                            }`}
                          >
                            {profile.type === 'crew' ? 'Crew' : 'Vendor'}
                          </span>
                        </div>
                        <div className="text-sm text-gray-400 mt-0.5">
                          {profile.category ||
                            profile.skills?.slice(0, 2).join(', ') ||
                            'Broadcast Professional'}
                        </div>
                        <div className="text-xs text-gray-500 mt-0.5 flex items-center gap-3">
                          <span>📍 {profile.location}</span>
                          {profile.day_rate && (
                            <span>💵 ${profile.day_rate.toLocaleString()}/day</span>
                          )}
                          {profile.union_status && profile.union_status !== 'non_union' && (
                            <span className="uppercase">{profile.union_status}</span>
                          )}
                        </div>
                        {profile.bio && (
                          <p className="text-xs text-gray-500 mt-2 line-clamp-2">{profile.bio}</p>
                        )}
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            )}

            {/* Pagination */}
            {total > 20 && (
              <div className="flex justify-center gap-2 mt-8">
                <button
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  disabled={page === 1}
                  className="px-4 py-2 bg-[#FFFFFF] border border-white/20 rounded-lg text-sm disabled:opacity-40 hover:border-white/40 transition-colors"
                >
                  ← Prev
                </button>
                <span className="px-4 py-2 text-sm text-gray-400">Page {page}</span>
                <button
                  onClick={() => setPage((p) => p + 1)}
                  disabled={results.length < 20}
                  className="px-4 py-2 bg-[#FFFFFF] border border-white/20 rounded-lg text-sm disabled:opacity-40 hover:border-white/40 transition-colors"
                >
                  Next →
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
}
