import { useParams, useNavigate } from "react-router-dom";
import { useEffect, useState, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Header } from "@/components/layout/Header";
import { RideCard } from "@/components/rides/RideCard";
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, Plus, FerrisWheel } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { AutocompleteSearch } from '@/components/search/AutocompleteSearch';
import { RideForm } from '@/components/admin/RideForm';
import { useAuth } from '@/hooks/useAuth';
import { useAuthModal } from '@/hooks/useAuthModal';
import { toast } from '@/hooks/use-toast';
import type { Ride, Company, RideModel } from "@/types/database";

export default function RideModelRides() {
  const { manufacturerSlug, modelSlug } = useParams<{ manufacturerSlug: string; modelSlug: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { requireAuth } = useAuthModal();
  const [model, setModel] = useState<RideModel | null>(null);
  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');
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      
      // Fetch manufacturer from companies table
      const { data: manufacturerData, error: mfgError } = await supabase
        .from("companies")
        .select("*")
        .eq("slug", manufacturerSlug)
        .eq("company_type", "manufacturer")
        .maybeSingle();

      if (mfgError) throw mfgError;
      if (!manufacturerData) {
        setLoading(false);
        return;
      }

      // Fetch ride model
      const { data: modelData, error: modelError } = await supabase
        .from("ride_models")
        .select("*")
        .eq("slug", modelSlug)
        .eq("manufacturer_id", manufacturerData.id)
        .maybeSingle();

      if (modelError) throw modelError;
      if (!modelData) {
        setLoading(false);
        return;
      }

      // Enhanced query with filters and sort
      let query = supabase
        .from("rides")
        .select(`
          *, 
          park:parks!inner(name, slug, location:locations(*)),
          manufacturer:companies!rides_manufacturer_id_fkey(*),
          ride_model:ride_models(id, name, slug, manufacturer_id, category)
        `)
        .eq("ride_model_id", modelData.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;

      setManufacturer(manufacturerData);
      setModel(modelData as RideModel);
      setRides(ridesData as Ride[] || []);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  }, [manufacturerSlug, modelSlug, sortBy, filterCategory, filterStatus]);

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

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

  const handleCreateSubmit = async (data: any) => {
    try {
      if (!user || !model) return;

      const submissionData = {
        ...data,
        ride_model_id: model.id,
        manufacturer_id: manufacturer!.id,
      };

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

  if (loading) {
    return (
      <>
        <Header />
        <div className="container mx-auto px-4 py-8">
          <Skeleton className="h-8 w-64 mb-4" />
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-6">
            {[...Array(8)].map((_, i) => (
              <Skeleton key={i} className="h-64" />
            ))}
          </div>
        </div>
      </>
    );
  }

  if (!model || !manufacturer) {
    return (
      <>
        <Header />
        <div className="container mx-auto px-4 py-8">
          <p className="text-muted-foreground">Model not found</p>
        </div>
      </>
    );
  }

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

        <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">{model.name} Installations</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">
            All rides using the {model.name} by {manufacturer.name}
          </p>
          <Badge variant="secondary">{filteredRides.length} rides</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 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>
                  <SelectItem value="all">All Categories</SelectItem>
                  <SelectItem value="roller_coaster">Roller Coasters</SelectItem>
                  <SelectItem value="flat_ride">Flat Rides</SelectItem>
                  <SelectItem value="water_ride">Water Rides</SelectItem>
                  <SelectItem value="dark_ride">Dark Rides</SelectItem>
                  <SelectItem value="kiddie_ride">Kiddie Rides</SelectItem>
                  <SelectItem value="transportation">Transportation</SelectItem>
                </SelectContent>
              </Select>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-[140px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="operating">Operating</SelectItem>
                  <SelectItem value="seasonal">Seasonal</SelectItem>
                  <SelectItem value="under_construction">Under Construction</SelectItem>
                  <SelectItem value="closed">Closed</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">
              No rides match your search criteria for the {model.name}
            </p>
          </div>
        )}

        {/* Create Modal */}
        <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>
    </>
  );
}