import { 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 { Badge } from '@/components/ui/badge';
import { Search, SlidersHorizontal, Factory, Plus } from 'lucide-react';
import { Company } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { ManufacturerCard } from '@/components/manufacturers/ManufacturerCard';
import { ManufacturerForm } from '@/components/admin/ManufacturerForm';
import { useAuth } from '@/hooks/useAuth';
import { useUserRole } from '@/hooks/useUserRole';
import { toast } from '@/hooks/use-toast';
import { submitCompanyCreation } from '@/lib/companyHelpers';

export default function Manufacturers() {
  const navigate = useNavigate();
  const { user } = useAuth();
  const { isModerator } = useUserRole();
  const [companies, setCompanies] = useState<Company[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  

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

  const fetchCompanies = async () => {
    try {
      let query = supabase
        .from('companies')
        .select('*');

        // Filter only manufacturers
        query = query.eq('company_type', 'manufacturer');

      // 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 = companies.filter(company =>
    company.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    company.headquarters_location?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    company.description?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleCreateSubmit = async (data: any) => {
    try {
      if (!user) {
        navigate('/auth');
        return;
      }

      await submitCompanyCreation(
        data,
        'manufacturer',
        user.id
      );

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

      setIsCreateModalOpen(false);
    } catch (error: any) {
      toast({
        title: "Error",
        description: error.message || "Failed to submit manufacturer.",
        variant: "destructive"
      });
    }
  };



  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 py-8">
        {/* Page Header */}
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <Factory className="w-8 h-8 text-primary" />
            <h1 className="text-4xl font-bold">Manufacturers</h1>
          </div>
          <p className="text-lg text-muted-foreground mb-4">
            Explore the manufacturers 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} manufacturers
              </Badge>
            </div>

            <div className="flex items-center gap-2">
              <Button 
                onClick={() => {
                  if (!user) {
                    navigate('/auth');
                  } else {
                    setIsCreateModalOpen(true);
                  }
                }}
                className="gap-2"
              >
                <Plus className="w-4 h-4" />
                Add Manufacturer
              </Button>
            </div>
          </div>
        </div>

        {/* Search and Filters */}
        <div className="space-y-3 mb-6">
          <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 manufacturers..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 h-11"
            />
          </div>
          
          <Select value={sortBy} onValueChange={setSortBy}>
            <SelectTrigger className="w-full h-10">
              <SlidersHorizontal className="h-4 w-4 mr-2" />
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="name">Name A-Z</SelectItem>
              <SelectItem value="founded">Founded (Newest)</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* Companies Grid */}
        {filteredCompanies.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 md:gap-6">
            {filteredCompanies.map((company) => (
              <ManufacturerCard key={company.id} company={company} />
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <Factory className="w-16 h-16 mb-4 mx-auto text-muted-foreground" />
            <h3 className="text-xl font-semibold mb-2">No manufacturers found</h3>
            <p className="text-muted-foreground">
              Try adjusting your search criteria
            </p>
          </div>
        )}
      </main>

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