import { useState, useEffect } from 'react';
import { Header } from '@/components/layout/Header';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Search, Filter, SlidersHorizontal, Globe, MapPin, Factory, FerrisWheel, Ruler, Hammer, Building2 } from 'lucide-react';
import { Company } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { useNavigate } from 'react-router-dom';

export default function Manufacturers() {
  const [companies, setCompanies] = useState<Company[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filterType, setFilterType] = useState('all');
  const navigate = useNavigate();

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

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

      // Apply filters
      if (filterType !== 'all') {
        query = query.eq('company_type', filterType);
      }

      // 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 getCompanyIcon = (type: string) => {
    switch (type) {
      case 'manufacturer': return <Factory className="w-5 h-5" />;
      case 'operator': return <FerrisWheel className="w-5 h-5" />;
      case 'designer': return <Ruler className="w-5 h-5" />;
      case 'contractor': return <Hammer className="w-5 h-5" />;
      default: return <Building2 className="w-5 h-5" />;
    }
  };

  const formatCompanyType = (type: string) => {
    return type.split('_').map(word => 
      word.charAt(0).toUpperCase() + word.slice(1)
    ).join(' ');
  };

  const companyTypes = [
    { value: 'all', label: 'All Types' },
    { value: 'manufacturer', label: 'Manufacturers' },
    { value: 'operator', label: 'Operators' },
    { value: 'designer', label: 'Designers' },
    { value: 'contractor', label: 'Contractors' }
  ];

  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-10 h-10 text-primary" />
            <h1 className="text-4xl font-bold">Manufacturers & Companies</h1>
          </div>
          <p className="text-lg text-muted-foreground">
            Explore the companies behind your favorite rides and attractions
          </p>
          <div className="flex items-center gap-2 mt-2">
            <Badge variant="secondary">{filteredCompanies.length} companies found</Badge>
            <Badge variant="outline">{companies.filter(c => c.company_type === 'manufacturer').length} manufacturers</Badge>
          </div>
        </div>

        {/* Search and Filters */}
        <div className="mb-8 space-y-4">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
              <Input
                placeholder="Search companies by name, location, or description..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </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="founded">Founded (Newest)</SelectItem>
                </SelectContent>
              </Select>
              
              <Select value={filterType} onValueChange={setFilterType}>
                <SelectTrigger className="w-[160px]">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {companyTypes.map(type => (
                    <SelectItem key={type.value} value={type.value}>
                      {type.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>

        {/* Companies Grid */}
        {filteredCompanies.length > 0 ? (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {filteredCompanies.map((company) => (
              <Card 
                key={company.id}
                className="group overflow-hidden border-border/50 bg-gradient-to-br from-card via-card to-card/80 hover:shadow-2xl hover:shadow-primary/20 transition-all duration-300 cursor-pointer hover:scale-[1.02]"
              >
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <span className="flex items-center">{getCompanyIcon(company.company_type)}</span>
                        <Badge variant="outline" className="text-xs">
                          {formatCompanyType(company.company_type)}
                        </Badge>
                      </div>
                      <CardTitle className="text-lg group-hover:text-primary transition-colors line-clamp-2">
                        {company.name}
                      </CardTitle>
                    </div>
                    {company.logo_url && (
                      <div className="w-12 h-12 bg-muted rounded-lg overflow-hidden flex-shrink-0">
                        <img 
                          src={company.logo_url} 
                          alt={`${company.name} logo`}
                          className="w-full h-full object-cover"
                        />
                      </div>
                    )}
                  </div>
                </CardHeader>

                <CardContent className="space-y-3">
                  {company.description && (
                    <p className="text-sm text-muted-foreground line-clamp-3">
                      {company.description}
                    </p>
                  )}

                  <div className="space-y-2 text-sm">
                    {company.founded_year && (
                      <div className="flex items-center gap-2">
                        <span className="text-muted-foreground">Founded:</span>
                        <span className="font-medium">{company.founded_year}</span>
                      </div>
                    )}
                    
                    {company.headquarters_location && (
                      <div className="flex items-center gap-2">
                        <MapPin className="w-3 h-3 text-muted-foreground" />
                        <span className="text-muted-foreground text-xs">
                          {company.headquarters_location}
                        </span>
                      </div>
                    )}
                  </div>

                  {company.website_url && (
                    <Button 
                      variant="outline" 
                      size="sm" 
                      className="w-full"
                      onClick={(e) => {
                        e.stopPropagation();
                        window.open(company.website_url, '_blank');
                      }}
                    >
                      <Globe className="w-4 h-4 mr-2" />
                      Visit Website
                    </Button>
                  )}
                </CardContent>
              </Card>
            ))}
          </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 companies found</h3>
            <p className="text-muted-foreground">
              Try adjusting your search criteria or filters
            </p>
          </div>
        )}
      </main>
    </div>
  );
}