import React, { useState, useEffect } from 'react';
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 { 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 { Badge } from '@/components/ui/badge';
import { Search, SlidersHorizontal, Ruler, Plus, ChevronDown, Filter, PanelLeftClose, PanelLeftOpen, Grid3X3, List } from 'lucide-react';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { cn } from '@/lib/utils';
import { DesignerFilters, DesignerFilterState, defaultDesignerFilters } from '@/components/designers/DesignerFilters';
import { Company } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { DesignerCard } from '@/components/designers/DesignerCard';
import { DesignerListView } from '@/components/designers/DesignerListView';
import { DesignerForm } from '@/components/admin/DesignerForm';
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';

export default function Designers() {
  useDocumentTitle('Designers');
  const navigate = useNavigate();
  const { user } = useAuth();
  const { isModerator } = useUserRole();
  const { requireAuth } = useAuthModal();
  const [companies, setCompanies] = useState<Company[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filters, setFilters] = useState<DesignerFilterState>(defaultDesignerFilters);
  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('designers-sidebar-collapsed');
    return saved ? JSON.parse(saved) : false;
  });

  const handleCreateSubmit = async (data: any) => {
    try {
      await submitCompanyCreation(data, 'designer', user.id);
      toast({
        title: "Designer Submitted",
        description: "Your submission has been sent for review."
      });
      setIsCreateModalOpen(false);
    } catch (error) {
      const errorMsg = getErrorMessage(error);
      toast({ title: "Error", description: errorMsg, variant: "destructive" });
    }
  };

  useEffect(() => {
    fetchCompanies();
  }, [sortBy]);

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

  const fetchCompanies = async () => {
    try {
      let query = supabase
        .from('companies')
        .select('id, name, slug, description, company_type, person_type, logo_url, card_image_url, headquarters_location, founded_year, founded_date, founded_date_precision, average_rating, review_count');

      // Filter only designers
      query = query.eq('company_type', 'designer');

      // Apply sorting
      switch (sortBy) {
        case 'founded':
          query = query.order('founded_year', { ascending: false, nullsFirst: false });
          break;
        default:
          query = query.order('name');
      }

      const { data } = await query;
      setCompanies(data || []);
    } catch (error) {
      console.error('Error fetching companies:', error);
    } finally {
      setLoading(false);
    }
  };

  const filteredCompanies = React.useMemo(() => {
    return companies.filter(company => {
      // Search filter
      const matchesSearch = company.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          company.headquarters_location?.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          company.description?.toLowerCase().includes(searchQuery.toLowerCase());
      
      if (!matchesSearch) return false;

      // Person type filter
      if (filters.personType !== 'all') {
        if (filters.personType === 'individual' && company.person_type !== 'individual') {
          return false;
        }
        if (filters.personType === 'company' && company.person_type === 'individual') {
          return false;
        }
      }

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

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

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

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

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

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

      // Is individual filter
      if (filters.isIndividual && company.person_type !== 'individual') {
        return false;
      }
      
      return true;
    });
  }, [companies, searchQuery, filters]);

  useOpenGraph({
    title: 'Ride Designers - ThrillWiki',
    description: `Browse ${filteredCompanies.length} ride designers worldwide`,
    imageUrl: filteredCompanies[0]?.banner_image_url,
    imageId: filteredCompanies[0]?.banner_image_id,
    type: 'website',
    enabled: !loading
  });

  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>
    );
  }

  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">
            <Ruler className="w-8 h-8 text-primary" />
            <h1 className="text-4xl font-bold">Designers</h1>
          </div>
          <p className="text-lg text-muted-foreground mb-4">
            Explore the designers behind your favorite rides and attractions
          </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">
                {filteredCompanies.length} designers
              </Badge>
            </div>

            <div className="flex items-center gap-2">
              <Button 
                onClick={() => requireAuth(() => setIsCreateModalOpen(true), "Sign in to add a designer")}
                className="gap-2"
              >
                <Plus className="w-4 h-4" />
                Add Designer
              </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 designers..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(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">
                  <SlidersHorizontal className="h-4 w-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="name">Name</SelectItem>
                  <SelectItem value="founded">Founded</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">
                    <DesignerFilters filters={filters} onFiltersChange={setFilters} designers={companies} />
                  </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>
                    <DesignerFilters filters={filters} onFiltersChange={setFilters} designers={companies} />
                  </CardContent>
                </Card>
              </div>
            </aside>
          )}

          {/* Results Area */}
          <div className="flex-1 min-w-0">
            {filteredCompanies.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">
                  {filteredCompanies.map((company) => (
                    <DesignerCard key={company.id} company={company} />
                  ))}
                </div>
              ) : (
                <DesignerListView designers={filteredCompanies} onDesignerClick={(d) => navigate(`/designers/${d.slug}`)} />
              )
            ) : (
              <div className="text-center py-12">
                <Ruler className="w-16 h-16 mb-4 mx-auto text-muted-foreground" />
                <h3 className="text-xl font-semibold mb-2">No designers found</h3>
                <p className="text-muted-foreground">
                  Try adjusting your search criteria
                </p>
              </div>
            )}
          </div>
        </div>
      </main>
      <Dialog open={isCreateModalOpen} onOpenChange={setIsCreateModalOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DesignerForm onSubmit={handleCreateSubmit} onCancel={() => setIsCreateModalOpen(false)} />
        </DialogContent>
      </Dialog>
    </div>
  );
}