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 DesignerRides() {
  const { designerSlug } = useParams<{ designerSlug: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { requireAuth } = useAuthModal();
  const [designer, setDesigner] = 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 designer changes
  useDocumentTitle(designer ? `${designer.name} - Rides` : 'Designer Rides');
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

  const fetchData = useCallback(async () => {
    try {
      // Fetch designer
      const { data: designerData, error: designerError } = await supabase
        .from('companies')
        .select('*')
        .eq('slug', designerSlug)
        .eq('company_type', 'designer')
        .maybeSingle();

      if (designerError) throw designerError;
      setDesigner(designerData);

      if (designerData) {
        // Fetch rides designed by this company
        let query = supabase
          .from('rides')
          .select(`
            *, 
            park:parks!inner(name, slug, location:locations(*)),
            manufacturer:companies!rides_manufacturer_id_fkey(*)
          `)
          .eq('designer_id', designerData.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;
        setRides(ridesData || []);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  }, [designerSlug, sortBy, filterCategory, filterStatus]);

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

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

  useOpenGraph({
    title: designer ? `${designer.name} - Rides` : 'Designer Rides',
    description: designer 
      ? `Explore ${filteredRides.length} rides designed by ${designer.name}` 
      : undefined,
    imageUrl: designer?.banner_image_url || filteredRides[0]?.banner_image_url,
    imageId: designer?.banner_image_id || filteredRides[0]?.banner_image_id,
    type: 'website',
    enabled: !!designer && !loading
  });

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

      const submissionData: RideSubmissionData = {
        ...data,
        designer_id: designer.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) {
      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 (!designer) {
    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">Designer Not Found</h1>
            <Button onClick={() => navigate('/designers')}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back to Designers
            </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(`/designers/${designerSlug}`)}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to {designer.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 {designer.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 designed by {designer.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">
              {designer.name} hasn't designed 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>
  );
}
