import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ArrowLeft, Filter, SlidersHorizontal, FerrisWheel } from 'lucide-react';
import { RideModel, Company } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { RideModelCard } from '@/components/rides/RideModelCard';
import { AutocompleteSearch } from '@/components/search/AutocompleteSearch';

export default function ManufacturerModels() {
  const { manufacturerSlug } = useParams<{ manufacturerSlug: string }>();
  const navigate = useNavigate();
  const [manufacturer, setManufacturer] = useState<Company | null>(null);
  const [models, setModels] = useState<RideModel[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filterCategory, setFilterCategory] = useState('all');

  useEffect(() => {
    if (manufacturerSlug) {
      fetchData();
    }
  }, [manufacturerSlug, sortBy, filterCategory]);

  const fetchData = async () => {
    try {
      // Fetch manufacturer
      const { data: manufacturerData, error: manufacturerError } = await supabase
        .from('companies')
        .select('*')
        .eq('slug', manufacturerSlug)
        .eq('company_type', 'manufacturer')
        .maybeSingle();

      if (manufacturerError) throw manufacturerError;
      setManufacturer(manufacturerData);

      if (manufacturerData) {
        // Fetch ride models with ride count
        let query = supabase
          .from('ride_models')
          .select(`
            *,
            rides:rides(count)
          `)
          .eq('manufacturer_id', manufacturerData.id);

        if (filterCategory !== 'all') {
          query = query.eq('category', filterCategory);
        }

        switch (sortBy) {
          case 'name':
            query = query.order('name');
            break;
          default:
            query = query.order('name');
        }

        const { data: modelsData, error: modelsError } = await query;
        if (modelsError) throw modelsError;
        setModels((modelsData || []) as any);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };

  const filteredModels = models.filter(model =>
    model.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    model.description?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const categories = [
    { value: 'all', label: 'All Categories' },
    { value: 'roller_coaster', label: 'Roller Coasters' },
    { value: 'flat_ride', label: 'Flat Rides' },
    { value: 'water_ride', label: 'Water Rides' },
    { value: 'dark_ride', label: 'Dark Rides' },
    { value: 'kiddie_ride', label: 'Kiddie Rides' },
    { value: 'transportation', label: 'Transportation' }
  ];

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="animate-pulse space-y-6">
            <div className="h-12 bg-muted rounded w-1/3"></div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {[...Array(8)].map((_, i) => (
                <div key={i} className="h-64 bg-muted rounded-lg"></div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!manufacturer) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="text-center py-12">
            <h1 className="text-2xl font-bold mb-4">Manufacturer Not Found</h1>
            <Button onClick={() => navigate('/manufacturers')}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back to Manufacturers
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <main className="container mx-auto px-4 py-8">
        <div className="mb-6">
          <Button variant="ghost" onClick={() => navigate(`/manufacturers/${manufacturerSlug}`)}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to {manufacturer.name}
          </Button>
        </div>

        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <FerrisWheel className="w-8 h-8 text-primary" />
            <h1 className="text-4xl font-bold">Models by {manufacturer.name}</h1>
          </div>
          <p className="text-lg text-muted-foreground mb-4">
            Explore all ride models manufactured by {manufacturer.name}
          </p>
          
          <Badge variant="secondary" className="text-sm sm:text-base px-2 py-0.5 sm:px-3 sm:py-1">
            {filteredModels.length} models
          </Badge>
        </div>

        <div className="mb-8 space-y-4">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1">
              <AutocompleteSearch
                placeholder="Search models by name..."
                types={['ride']}
                limit={8}
                onSearch={(query) => setSearchQuery(query)}
                showRecentSearches={false}
              />
            </div>
            <div className="flex gap-2">
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="w-[180px]">
                  <SlidersHorizontal className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="name">Name A-Z</SelectItem>
                </SelectContent>
              </Select>
              
              <Select value={filterCategory} onValueChange={setFilterCategory}>
                <SelectTrigger className="w-[160px]">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {categories.map(category => (
                    <SelectItem key={category.value} value={category.value}>
                      {category.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>

        {filteredModels.length > 0 ? (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-6">
            {filteredModels.map((model) => (
              <RideModelCard 
                key={model.id} 
                model={model}
                manufacturerSlug={manufacturerSlug || ''}
              />
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <FerrisWheel className="w-16 h-16 mb-4 mx-auto text-muted-foreground" />
            <h3 className="text-xl font-semibold mb-2">No models found</h3>
            <p className="text-muted-foreground">
              {manufacturer.name} doesn't have any models matching your criteria
            </p>
          </div>
        )}
      </main>
    </div>
  );
}
