import { useState, useEffect, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { ArrowLeft, MapPin, Filter, FerrisWheel } from 'lucide-react';
import { Park, Company } from '@/types/database';
import { supabase } from '@/integrations/supabase/client';
import { ParkGridView } from '@/components/parks/ParkGridView';
import { ParkListView } from '@/components/parks/ParkListView';
import { ParkSearch } from '@/components/parks/ParkSearch';
import { ParkSortOptions } from '@/components/parks/ParkSortOptions';
import { ParkFilters } from '@/components/parks/ParkFilters';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Grid3X3, List } from 'lucide-react';
import { FilterState, SortState } from './Parks';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';
import { useOpenGraph } from '@/hooks/useOpenGraph';

const initialFilters: FilterState = {
  search: '',
  parkType: [],
  status: [],
  country: [],
  minRating: 0,
  maxRating: 5,
  minRides: 0,
  maxRides: 1000,
  openingYearStart: null,
  openingYearEnd: null,
};

const initialSort: SortState = {
  field: 'name',
  direction: 'asc'
};

export default function OwnerParks() {
  const { ownerSlug } = useParams<{ ownerSlug: string }>();
  const navigate = useNavigate();
  const [owner, setOwner] = useState<Company | null>(null);
  const [parks, setParks] = useState<Park[]>([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState<FilterState>(initialFilters);
  const [sort, setSort] = useState<SortState>(initialSort);
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [showFilters, setShowFilters] = useState(false);
  
  // Update document title when owner changes
  useDocumentTitle(owner ? `${owner.name} - Parks` : 'Owner Parks');

  useEffect(() => {
    if (ownerSlug) {
      fetchData();
    }
  }, [ownerSlug]);

  const fetchData = async () => {
    try {
      // Fetch owner
      const { data: ownerData, error: ownerError} = await supabase
        .from('companies')
        .select('*')
        .eq('slug', ownerSlug || '')
        .eq('company_type', 'property_owner')
        .maybeSingle();

      if (ownerError) throw ownerError;
      setOwner(ownerData);

      if (ownerData) {
        // Fetch parks owned by this property owner
        const { data: parksData, error: parksError } = await supabase
          .from('parks')
          .select(`
            *,
            location:locations(*),
            operator:companies!parks_operator_id_fkey(*),
            property_owner:companies!parks_property_owner_id_fkey(*)
          `)
          .eq('property_owner_id', ownerData.id)
          .order('name');

        if (parksError) throw parksError;
        setParks(parksData || []);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };

  const filteredAndSortedParks = useMemo(() => {
    let filtered = parks.filter(park => {
      if (filters.search) {
        const searchTerm = filters.search.toLowerCase();
        const matchesSearch = 
          park.name.toLowerCase().includes(searchTerm) ||
          park.description?.toLowerCase().includes(searchTerm) ||
          park.location?.city?.toLowerCase().includes(searchTerm) ||
          park.location?.country?.toLowerCase().includes(searchTerm);
        if (!matchesSearch) return false;
      }
      if (filters.parkType.length > 0 && !filters.parkType.includes(park.park_type)) return false;
      if (filters.status.length > 0 && !filters.status.includes(park.status)) return false;
      if (filters.country.length > 0 && !filters.country.includes(park.location?.country || '')) return false;
      
      const rating = park.average_rating || 0;
      if (rating < filters.minRating || rating > filters.maxRating) return false;
      
      const rideCount = park.ride_count || 0;
      if (rideCount < filters.minRides || rideCount > filters.maxRides) return false;
      
      return true;
    });

    filtered.sort((a, b) => {
      let aValue: any, bValue: any;
      
      switch (sort.field) {
        case 'name':
          aValue = a.name;
          bValue = b.name;
          break;
        case 'rating':
          aValue = a.average_rating || 0;
          bValue = b.average_rating || 0;
          break;
        case 'rides':
          aValue = a.ride_count || 0;
          bValue = b.ride_count || 0;
          break;
        default:
          aValue = a.name;
          bValue = b.name;
      }

      if (typeof aValue === 'string' && typeof bValue === 'string') {
        return sort.direction === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
      }
      return sort.direction === 'asc' ? aValue - bValue : bValue - aValue;
    });

    return filtered;
  }, [parks, filters, sort]);

  useOpenGraph({
    title: owner ? `Parks by ${owner.name} - ThrillWiki` : 'Owner Parks',
    description: owner 
      ? `Explore ${filteredAndSortedParks.length} theme parks owned by ${owner.name}` 
      : undefined,
    imageUrl: owner?.banner_image_url ?? filteredAndSortedParks[0]?.banner_image_url ?? undefined,
    imageId: owner?.banner_image_id ?? filteredAndSortedParks[0]?.banner_image_id ?? undefined,
    type: 'website',
    enabled: !!owner && !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>
    );
  }

  if (!owner) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 py-8">
          <div className="text-center py-12">
            <h1 className="text-2xl font-bold mb-4">Property Owner Not Found</h1>
            <Button onClick={() => navigate('/owners')}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back to Property Owners
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <main className="container mx-auto px-4 py-8">
        <div className="mb-6">
          <Button variant="ghost" onClick={() => navigate(`/owners/${ownerSlug}`)}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to {owner.name}
          </Button>
        </div>

        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <MapPin className="w-8 h-8 text-primary" />
            <h1 className="text-4xl font-bold">Parks Owned by {owner.name}</h1>
          </div>
          <p className="text-lg text-muted-foreground mb-4">
            Explore all theme parks owned by {owner.name}
          </p>
          
          <Badge variant="secondary" className="text-sm sm:text-base px-2 py-0.5 sm:px-3 sm:py-1">
            {filteredAndSortedParks.length} parks
          </Badge>
        </div>

        <div className="mb-6 space-y-4">
          <div className="flex flex-col lg:flex-row gap-4">
            <div className="flex-1">
              <ParkSearch 
                value={filters.search}
                onChange={(search) => setFilters(prev => ({ ...prev, search }))}
              />
            </div>
            
            <div className="flex gap-2 w-full lg:w-auto">
              <div className="flex-1 sm:flex-none">
                <ParkSortOptions 
                  sort={sort}
                  onSortChange={setSort}
                />
              </div>
              
              <Button
                variant={showFilters ? "default" : "outline"}
                onClick={() => setShowFilters(!showFilters)}
                className="shrink-0"
              >
                <Filter className="w-4 h-4 md:mr-2" />
                <span className="hidden md:inline">Filters</span>
              </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>

          {showFilters && (
            <Card>
              <CardContent className="p-6">
                <ParkFilters 
                  filters={filters}
                  onFiltersChange={setFilters}
                  parks={parks}
                />
              </CardContent>
            </Card>
          )}
        </div>

        {filteredAndSortedParks.length > 0 ? (
          viewMode === 'grid' ? (
            <ParkGridView parks={filteredAndSortedParks} />
          ) : (
            <ParkListView 
              parks={filteredAndSortedParks} 
              onParkClick={(park) => navigate(`/parks/${park.slug}`)}
            />
          )
        ) : (
          <div className="text-center py-12">
            <FerrisWheel className="w-16 h-16 mb-4 opacity-50 mx-auto" />
            <h3 className="text-xl font-semibold mb-2">No parks found</h3>
            <p className="text-muted-foreground">
              {owner.name} doesn't own any parks matching your criteria
            </p>
          </div>
        )}
      </main>
    </div>
  );
}
