import { useState, useEffect, useCallback } 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 { Dialog, DialogContent } from '@/components/ui/dialog';
import { ArrowLeft, Filter, SlidersHorizontal, FerrisWheel, Plus } from 'lucide-react';
import { RideModel, Company, Park } from '@/types/database';
import { RideModelSubmissionData } from '@/types/submission-data';
import { supabase } from '@/integrations/supabase/client';
import { RideModelCard } from '@/components/rides/RideModelCard';
import { RideModelForm } from '@/components/admin/RideModelForm';
import { AutocompleteSearch } from '@/components/search/AutocompleteSearch';
import { useAuth } from '@/hooks/useAuth';
import { toast } from '@/hooks/use-toast';
import { useAuthModal } from '@/hooks/useAuthModal';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';
import { useOpenGraph } from '@/hooks/useOpenGraph';

interface RideModelWithCount extends RideModel {
  ride_count: number;
}

export default function ManufacturerModels() {
  const { manufacturerSlug } = useParams<{ manufacturerSlug: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { requireAuth } = useAuthModal();
  const [manufacturer, setManufacturer] = useState<Company | null>(null);
  const [models, setModels] = useState<RideModelWithCount[]>([]);
  const [loading, setLoading] = useState(true);
  
  // Update document title when manufacturer changes
  useDocumentTitle(manufacturer ? `${manufacturer.name} - Models` : 'Manufacturer Models');
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filterCategory, setFilterCategory] = useState('all');
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

  const fetchData = useCallback(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;
        
        // Transform data to include ride count
      const modelsWithCounts: RideModelWithCount[] = (modelsData || []).map(model => ({
        ...model,
        ride_count: Array.isArray(model.rides) ? model.rides[0]?.count || 0 : 0
      })) as RideModelWithCount[];

      setModels(modelsWithCounts);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  }, [manufacturerSlug, sortBy, filterCategory]);

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

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

  useOpenGraph({
    title: manufacturer ? `${manufacturer.name} - Ride Models` : 'Manufacturer Models',
    description: manufacturer 
      ? `Browse ${filteredModels.length} ride models by ${manufacturer.name}` 
      : undefined,
    imageUrl: manufacturer?.banner_image_url || filteredModels[0]?.banner_image_url,
    imageId: manufacturer?.banner_image_id || filteredModels[0]?.banner_image_id,
    type: 'website',
    enabled: !!manufacturer && !loading
  });

  const handleCreateSubmit = async (data: any) => {
    try {
      if (!manufacturer) {
        toast({
          title: "Error",
          description: "Manufacturer information is missing.",
          variant: "destructive"
        });
        return;
      }

      const submissionData: RideModelSubmissionData = {
        ...data,
        manufacturer_id: manufacturer.id,
        ride_type: data.ride_type ?? undefined,
      };

      const { submitRideModelCreation } = await import('@/lib/entitySubmissionHelpers');
      await submitRideModelCreation(submissionData as any, user!.id);
      
      toast({
        title: "Ride Model Submitted",
        description: "Your ride model submission has been sent for review."
      });
      
      setIsCreateModalOpen(false);
      fetchData();
    } catch (error) {
      const message = error instanceof Error ? error.message : "Failed to submit ride model.";
      toast({
        title: "Error",
        description: message,
        variant: "destructive"
      });
    }
  };

  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 justify-between mb-4">
            <div className="flex items-center gap-3">
              <FerrisWheel className="w-8 h-8 text-primary" />
              <h1 className="text-4xl font-bold">Models by {manufacturer.name}</h1>
            </div>
            <Button 
              onClick={() => requireAuth(() => setIsCreateModalOpen(true), "Sign in to add a ride model")}
            >
              <Plus className="w-4 h-4 mr-2" />
              Add Ride Model
            </Button>
          </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>

      <Dialog open={isCreateModalOpen} onOpenChange={setIsCreateModalOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <RideModelForm
            manufacturerName={manufacturer.name}
            onSubmit={handleCreateSubmit}
            onCancel={() => setIsCreateModalOpen(false)}
          />
        </DialogContent>
      </Dialog>
    </div>
  );
}
