import React, { useState } 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 { Search, Filter, Building2, Plus } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import ParkOwnerCard from '@/components/park-owners/ParkOwnerCard';
import { PropertyOwnerForm } from '@/components/admin/PropertyOwnerForm';
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 ParkOwners = () => {
  useDocumentTitle('Property Owners');
  const navigate = useNavigate();
  const { user } = useAuth();
  const { isModerator } = useUserRole();
  const { requireAuth } = useAuthModal();
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState('name');
  const [filterBy, setFilterBy] = useState('all');
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

  const { data: parkOwners, isLoading } = useQuery({
    queryKey: ['park-owners'],
    queryFn: async () => {
      // Get companies that are property owners with park counts
      const { data, error } = await supabase
        .from('companies')
        .select(`
          *,
          parks:parks!property_owner_id(count)
        `)
        .in('id', 
          await supabase
            .from('parks')
            .select('property_owner_id')
            .not('property_owner_id', 'is', null)
            .then(({ data }) => data?.map(park => park.property_owner_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,
        'property_owner',
        user!.id
      );

      toast({
        title: "Property Owner 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 filteredAndSortedOwners = React.useMemo(() => {
    if (!parkOwners) return [];

    let filtered = parkOwners.filter(owner => {
      const matchesSearch = owner.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          (owner.description && owner.description.toLowerCase().includes(searchTerm.toLowerCase()));
      
      if (filterBy === 'all') return matchesSearch;
      if (filterBy === 'with-rating') return matchesSearch && (owner.average_rating ?? 0) > 0;
      if (filterBy === 'established') return matchesSearch && owner.founded_year;
      
      return matchesSearch;
    });

    // 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;
  }, [parkOwners, searchTerm, sortBy, filterBy]);

  useOpenGraph({
    title: 'Property Owners - ThrillWiki',
    description: `Browse ${filteredAndSortedOwners.length} theme park property owners worldwide`,
    imageUrl: filteredAndSortedOwners[0]?.banner_image_url ?? undefined,
    imageId: filteredAndSortedOwners[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 py-8">
        {/* Page Header */}
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <Building2 className="w-8 h-8 text-primary" />
            <h1 className="text-4xl font-bold">Property Owners</h1>
          </div>
          <p className="text-lg text-muted-foreground mb-4">
            Discover companies that own and manage 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">
                {filteredAndSortedOwners?.length || 0} owners
              </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 a property owner")}
                className="gap-2"
              >
                <Plus className="w-4 h-4" />
                Add Property Owner
              </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 property owners..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 h-11"
            />
          </div>
          
          <div className="flex gap-2">
            <Select value={sortBy} onValueChange={setSortBy}>
              <SelectTrigger className="flex-1 h-10">
                <SelectValue placeholder="Sort by" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="name">Name</SelectItem>
                <SelectItem value="rating">Rating</SelectItem>
                <SelectItem value="founded">Founded Year</SelectItem>
                <SelectItem value="reviews">Review Count</SelectItem>
              </SelectContent>
            </Select>

            <Select value={filterBy} onValueChange={setFilterBy}>
              <SelectTrigger className="flex-1 h-10">
                <Filter className="h-4 w-4 mr-2" />
                <SelectValue placeholder="Filter" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All</SelectItem>
                <SelectItem value="with-rating">Rated</SelectItem>
                <SelectItem value="established">Est.</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>


        {/* 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 property owners...</p>
          </div>
        )}

        {/* Property Owners Grid */}
        {!isLoading && filteredAndSortedOwners && (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
            {filteredAndSortedOwners.map((owner) => (
              <ParkOwnerCard key={owner.id} company={owner} />
            ))}
          </div>
        )}

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

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

export default ParkOwners;