import React, { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Collapsible, CollapsibleContent } from '@/components/ui/collapsible';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Search, Filter, Building, Plus, ChevronDown, PanelLeftClose, PanelLeftOpen, Grid3X3, List } from 'lucide-react';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { cn } from '@/lib/utils';
import { supabase } from '@/integrations/supabase/client';
import OperatorCard from '@/components/operators/OperatorCard';
import { OperatorListView } from '@/components/operators/OperatorListView';
import { OperatorForm } from '@/components/admin/OperatorForm';
import { OperatorFilters, OperatorFilterState, defaultOperatorFilters } from '@/components/operators/OperatorFilters';
import { Company } from '@/types/database';
import { useAuth } from '@/hooks/useAuth';
import { useUserRole } from '@/hooks/useUserRole';
import { toast } from '@/hooks/use-toast';
import { submitCompanyCreation } from '@/lib/companyHelpers';
import { useAuthModal } from '@/hooks/useAuthModal';
import { getErrorMessage } from '@/lib/errorHandler';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';
import { useOpenGraph } from '@/hooks/useOpenGraph';

const Operators = () => {
  useDocumentTitle('Operators');
  const navigate = useNavigate();
  const { user } = useAuth();
  const { isModerator } = useUserRole();
  const { requireAuth } = useAuthModal();
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filters, setFilters] = useState<OperatorFilterState>(defaultOperatorFilters);
  const [showFilters, setShowFilters] = useState(false);
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
    const saved = localStorage.getItem('operators-sidebar-collapsed');
    return saved ? JSON.parse(saved) : false;
  });

  useEffect(() => {
    localStorage.setItem('operators-sidebar-collapsed', JSON.stringify(sidebarCollapsed));
  }, [sidebarCollapsed]);

  const { data: operators, isLoading } = useQuery({
    queryKey: ['operators'],
    queryFn: async () => {
      // Get companies that are park operators with park counts
      const { data, error } = await supabase
        .from('companies')
        .select(`
          *,
          parks:parks!operator_id(count)
        `)
        .in('id', 
          await supabase
            .from('parks')
            .select('operator_id')
            .not('operator_id', 'is', null)
            .then(({ data }) => data?.map(park => park.operator_id).filter((id): id is string => id !== null) || [])
        )
        .order('name');

      if (error) throw error;
      
      // Transform the data to include park_count
      const transformedData = data?.map(company => ({
        ...company,
        park_count: company.parks?.[0]?.count || 0
      })) || [];
      
      return transformedData as (Company & { park_count: number })[];
    },
  });

  const handleCreateSubmit = async (data: any) => {
    try {
      await submitCompanyCreation(
        data,
        'operator',
        user!.id
      );

      toast({
        title: "Operator Submitted",
        description: "Your submission has been sent for review."
      });

      setIsCreateModalOpen(false);
    } catch (error) {
      const errorMsg = getErrorMessage(error);
      toast({
        title: "Error",
        description: errorMsg,
        variant: "destructive"
      });
    }
  };

  const filteredAndSortedOperators = React.useMemo(() => {
    if (!operators) return [];

    let filtered = operators.filter(operator => {
      // Search filter
      const matchesSearch = operator.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          (operator.description && operator.description.toLowerCase().includes(searchTerm.toLowerCase()));
      
      if (!matchesSearch) return false;

      // Country filter
      if (filters.countries.length > 0) {
        if (!operator.headquarters_location || !filters.countries.some(c => operator.headquarters_location?.includes(c))) {
          return false;
        }
      }

      // Rating filter
      const rating = operator.average_rating || 0;
      if (rating < filters.minRating || rating > filters.maxRating) {
        return false;
      }

      // Review count filter
      const reviewCount = operator.review_count || 0;
      if (reviewCount < filters.minReviewCount || reviewCount > filters.maxReviewCount) {
        return false;
      }

      // Park count filter
      const parkCount = operator.park_count || 0;
      if (parkCount < filters.minParkCount || parkCount > filters.maxParkCount) {
        return false;
      }

      // Founded date filter
      if (filters.foundedDateFrom || filters.foundedDateTo) {
        if (!operator.founded_year) {
          return false;
        }
        if (filters.foundedDateFrom && operator.founded_year < filters.foundedDateFrom.getFullYear()) {
          return false;
        }
        if (filters.foundedDateTo && operator.founded_year > filters.foundedDateTo.getFullYear()) {
          return false;
        }
      }

      // Has rating filter
      if (filters.hasRating && !operator.average_rating) {
        return false;
      }

      // Has founded date filter
      if (filters.hasFoundedDate && !operator.founded_year) {
        return false;
      }
      
      return true;
    });

    // Sort
    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'name':
          return a.name.localeCompare(b.name);
        case 'rating':
          return (b.average_rating || 0) - (a.average_rating || 0);
        case 'founded':
          return (b.founded_year || 0) - (a.founded_year || 0);
        case 'reviews':
          return (b.review_count || 0) - (a.review_count || 0);
        default:
          return 0;
      }
    });

    return filtered;
  }, [operators, searchTerm, sortBy, filters]);

  useOpenGraph({
    title: 'Park Operators - ThrillWiki',
    description: `Browse ${filteredAndSortedOperators.length} theme park operators worldwide`,
    imageUrl: filteredAndSortedOperators[0]?.banner_image_url ?? undefined,
    imageId: filteredAndSortedOperators[0]?.banner_image_id ?? undefined,
    type: 'website',
    enabled: !isLoading
  });

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <main className="container mx-auto px-4 md:px-6 lg:px-8 xl:px-8 2xl:px-10 py-6 xl:py-8">
        {/* Page Header */}
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <Building className="w-8 h-8 text-primary" />
            <h1 className="text-4xl font-bold">Park Operators</h1>
          </div>
          <p className="text-lg text-muted-foreground mb-4">
            Discover companies that operate theme parks
          </p>
          
          <div className="flex items-center justify-between">
            <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
              <Badge variant="secondary" className="flex items-center justify-center text-sm sm:text-base px-2 py-0.5 sm:px-3 sm:py-1 whitespace-nowrap">
                {filteredAndSortedOperators?.length || 0} operators
              </Badge>
              {searchTerm && (
                <Badge variant="outline" className="flex items-center justify-center text-xs sm:text-sm px-2 py-0.5 whitespace-nowrap">
                  Searching: "{searchTerm}"
                </Badge>
              )}
            </div>

            <div className="flex items-center gap-2">
              <Button 
                onClick={() => requireAuth(() => setIsCreateModalOpen(true), "Sign in to add an operator")}
                className="gap-2"
              >
                <Plus className="w-4 h-4" />
                Add Operator
              </Button>
            </div>
          </div>
        </div>

        {/* Search and Filters */}
        <div className="mb-6 space-y-4">
          <div className="flex flex-col lg:flex-row gap-4">
            {/* Desktop: Filter toggle on the left */}
            <Button
              variant="outline"
              onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
              className="shrink-0 gap-2 hidden lg:flex"
              title={sidebarCollapsed ? "Show filters" : "Hide filters"}
            >
              {sidebarCollapsed ? (
                <PanelLeftOpen className="w-4 h-4" />
              ) : (
                <PanelLeftClose className="w-4 h-4" />
              )}
              <span>Filters</span>
            </Button>

            {/* Search bar takes remaining space */}
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
                <Input
                  placeholder="Search park operators..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10 h-11"
                />
              </div>
            </div>
            
            {/* Sort controls - more compact */}
            <div className="flex gap-2 w-full lg:w-auto">
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="w-[160px] h-10">
                  <SelectValue placeholder="Sort by" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="name">Name</SelectItem>
                  <SelectItem value="rating">Rating</SelectItem>
                  <SelectItem value="founded">Founded</SelectItem>
                  <SelectItem value="reviews">Reviews</SelectItem>
                </SelectContent>
              </Select>

              {/* Mobile filter toggle */}
              <Button 
                variant={showFilters ? "default" : "outline"}
                onClick={() => setShowFilters(!showFilters)} 
                className="gap-2 lg:hidden"
              >
                <Filter className="w-4 h-4" />
                <span className="hidden sm:inline">Filters</span>
                <ChevronDown className={`w-4 h-4 transition-transform ${showFilters ? 'rotate-180' : ''}`} />
              </Button>
              <Tabs value={viewMode} onValueChange={(v) => setViewMode(v as 'grid' | 'list')} className="hidden md:inline-flex">
                <TabsList>
                  <TabsTrigger value="grid"><Grid3X3 className="w-4 h-4" /></TabsTrigger>
                  <TabsTrigger value="list"><List className="w-4 h-4" /></TabsTrigger>
                </TabsList>
              </Tabs>
            </div>
          </div>
          
          {/* Mobile Filters */}
          <div className="lg:hidden">
            <Collapsible open={showFilters} onOpenChange={setShowFilters}>
              <CollapsibleContent>
                <Card className="mt-4">
                  <CardContent className="pt-6">
                    <OperatorFilters filters={filters} onFiltersChange={setFilters} operators={operators || []} />
                  </CardContent>
                </Card>
              </CollapsibleContent>
            </Collapsible>
          </div>
        </div>

        {/* Main Content Area with Sidebar */}
        <div className="flex flex-col lg:flex-row gap-6">
          {/* Desktop Filter Sidebar */}
          {!sidebarCollapsed && (
            <aside className="hidden lg:block flex-shrink-0 transition-all duration-300 lg:w-[340px] xl:w-[380px] 2xl:w-[420px]">
              <div className="sticky top-24">
                <Card>
                  <CardHeader className="flex flex-row items-center justify-between pb-2">
                    <CardTitle className="text-base">Filters</CardTitle>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setSidebarCollapsed(true)}
                      title="Hide filters"
                    >
                      <PanelLeftClose className="w-4 h-4" />
                    </Button>
                  </CardHeader>
                  <CardContent>
                    <OperatorFilters filters={filters} onFiltersChange={setFilters} operators={operators || []} />
                  </CardContent>
                </Card>
              </div>
            </aside>
          )}

          {/* Results Area */}
          <div className="flex-1 min-w-0">
            {/* Loading State */}
            {isLoading && (
              <div className="text-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
                <p className="text-muted-foreground mt-4">Loading park operators...</p>
              </div>
            )}

            {/* Operators Grid/List */}
            {!isLoading && filteredAndSortedOperators && filteredAndSortedOperators.length > 0 && (
              viewMode === 'grid' ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 3xl:grid-cols-7 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
                  {filteredAndSortedOperators.map((operator) => (
                    <OperatorCard key={operator.id} company={operator} />
                  ))}
                </div>
              ) : (
                <OperatorListView operators={filteredAndSortedOperators} onOperatorClick={(op) => navigate(`/operators/${op.slug}`)} />
              )
            )}

            {/* Empty State */}
            {!isLoading && filteredAndSortedOperators?.length === 0 && (
              <div className="text-center py-12">
                <Building className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                <h3 className="text-lg font-semibold mb-2">No park operators found</h3>
                <p className="text-muted-foreground">
                  {searchTerm 
                    ? "Try adjusting your search terms or filters"
                    : "No park operators are currently available"
                  }
                </p>
              </div>
            )}
          </div>
        </div>

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

export default Operators;
