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 { Ride, Company } from '@/types/database';
import { RideSubmissionData } from '@/types/submission-data';
import { supabase } from '@/integrations/supabase/client';
import { RideCard } from '@/components/rides/RideCard';
import { RideForm } from '@/components/admin/RideForm';
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';

export default function ManufacturerRides() {
  const { manufacturerSlug } = useParams<{ manufacturerSlug: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { requireAuth } = useAuthModal();
  const [manufacturer, setManufacturer] = useState<Company | null>(null);
  const [rides, setRides] = useState<Ride[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filterCategory, setFilterCategory] = useState('all');
  const [filterStatus, setFilterStatus] = useState('all');
  
  // Update document title when manufacturer changes
  useDocumentTitle(manufacturer ? `${manufacturer.name} - Rides` : 'Manufacturer Rides');
  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 rides manufactured by this company
        let query = supabase
          .from('rides')
          .select(`
            *, 
            park:parks!inner(name, slug, location:locations(*)),
            manufacturer:companies!rides_manufacturer_id_fkey(*)
          `)
          .eq('manufacturer_id', manufacturerData.id);

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

        switch (sortBy) {
          case 'rating':
            query = query.order('average_rating', { ascending: false });
            break;
          case 'speed':
            query = query.order('max_speed_kmh', { ascending: false, nullsFirst: false });
            break;
      case 'height':
        query = query.order('height_meters', { ascending: false, nullsFirst: false });
        break;
          case 'reviews':
            query = query.order('review_count', { ascending: false });
            break;
          default:
            query = query.order('name');
        }

        const { data: ridesData, error: ridesError } = await query;
        if (ridesError) throw ridesError;
        // Supabase returns nullable types, but our Ride type uses undefined
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        setRides((ridesData || []) as any);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  }, [manufacturerSlug, sortBy, filterCategory, filterStatus]);

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

  const filteredRides = rides.filter(ride =>
    ride.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    ride.park?.name?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  useOpenGraph({
    title: manufacturer ? `${manufacturer.name} - Rides` : 'Manufacturer Rides',
    description: manufacturer 
      ? `Explore ${filteredRides.length} rides manufactured by ${manufacturer.name}` 
      : undefined,
    imageUrl: manufacturer?.banner_image_url ?? filteredRides[0]?.banner_image_url ?? undefined,
    imageId: manufacturer?.banner_image_id ?? filteredRides[0]?.banner_image_id ?? undefined,
    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: RideSubmissionData = {
        ...data,
        manufacturer_id: manufacturer.id,
        description: data.description ?? undefined,
      };

      const { submitRideCreation } = await import('@/lib/entitySubmissionHelpers');
      // Type assertion needed: RideForm returns RideFormData with undefined for optional fields,
      // but submitRideCreation expects specific form data structure
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      await submitRideCreation(submissionData as any, user!.id);
      
      toast({
        title: "Ride Submitted",
        description: "Your ride submission has been sent for review."
      });
      
      setIsCreateModalOpen(false);
      fetchData();
    } catch (error) {
      const message = error instanceof Error ? error.message : "Failed to submit ride.";
      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' }
  ];

  const statusOptions = [
    { value: 'all', label: 'All Status' },
    { value: 'operating', label: 'Operating' },
    { value: 'seasonal', label: 'Seasonal' },
    { value: 'under_construction', label: 'Under Construction' },
    { value: 'closed', label: 'Closed' }
  ];

  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">Rides by {manufacturer.name}</h1>
            </div>
            <Button 
              onClick={() => requireAuth(() => setIsCreateModalOpen(true), "Sign in to add a new ride")}
            >
              <Plus className="w-4 h-4 mr-2" />
              Add Ride
            </Button>
          </div>
          <p className="text-lg text-muted-foreground mb-4">
            Explore all rides manufactured by {manufacturer.name}
          </p>
          
          <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
            <Badge variant="secondary" className="text-sm sm:text-base px-2 py-0.5 sm:px-3 sm:py-1">
              {filteredRides.length} rides
            </Badge>
            <Badge variant="outline" className="text-xs sm:text-sm px-2 py-0.5">
              {rides.filter(r => r.category === 'roller_coaster').length} coasters
            </Badge>
          </div>
        </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 rides by name or park..."
                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>
                  <SelectItem value="rating">Highest Rated</SelectItem>
                  <SelectItem value="speed">Fastest</SelectItem>
                  <SelectItem value="height">Tallest</SelectItem>
                  <SelectItem value="reviews">Most Reviews</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>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-[140px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {statusOptions.map(status => (
                    <SelectItem key={status.value} value={status.value}>
                      {status.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>

        {filteredRides.length > 0 ? (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-6">
            {filteredRides.map((ride) => (
              <RideCard key={ride.id} ride={ride} showParkName={true} />
            ))}
          </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 rides found</h3>
            <p className="text-muted-foreground">
              {manufacturer.name} hasn't manufactured any rides matching your criteria
            </p>
          </div>
        )}
      </main>

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