'use client';

import { useState, useMemo } from 'react';
import { Service, ServiceCategory, ServiceStatus } from '@/lib/data';
import { FilterBar } from './FilterBar';
import { ServiceGrid } from './ServiceGrid';

interface ServiceSectionProps {
  services: Service[];
}

/**
 * ServiceSection - Verwaltet Filterlogik und rendert FilterBar + ServiceGrid
 * @param services - Array aller verfügbaren Services
 */
export function ServiceSection({ services }: ServiceSectionProps) {
  const [selectedCategories, setSelectedCategories] = useState<
    ServiceCategory[]
  >([]);
  const [selectedStatuses, setSelectedStatuses] = useState<ServiceStatus[]>([]);

  // Extrahiere eindeutige Kategorien und Status aus Services
  const categories = useMemo(
    () => Array.from(new Set(services.map((s) => s.category))).sort(),
    [services]
  );

  const statuses = useMemo(
    () =>
      (['online', 'warning', 'offline'] as ServiceStatus[]).filter((status) =>
        services.some((s) => s.status === status)
      ),
    [services]
  );

  // Filtere Services basierend auf ausgewählten Filtern
  const filteredServices = useMemo(() => {
    return services.filter((service) => {
      const categoryMatch =
        selectedCategories.length === 0 ||
        selectedCategories.includes(service.category);

      const statusMatch =
        selectedStatuses.length === 0 ||
        selectedStatuses.includes(service.status);

      return categoryMatch && statusMatch;
    });
  }, [services, selectedCategories, selectedStatuses]);

  const handleCategoryChange = (category: ServiceCategory) => {
    setSelectedCategories((prev) =>
      prev.includes(category)
        ? prev.filter((c) => c !== category)
        : [...prev, category]
    );
  };

  const handleStatusChange = (status: ServiceStatus) => {
    setSelectedStatuses((prev) =>
      prev.includes(status) ? prev.filter((s) => s !== status) : [...prev, status]
    );
  };

  const handleReset = () => {
    setSelectedCategories([]);
    setSelectedStatuses([]);
  };

  return (
    <>
      <FilterBar
        categories={categories}
        statuses={statuses}
        selectedCategories={selectedCategories}
        selectedStatuses={selectedStatuses}
        onCategoryChange={handleCategoryChange}
        onStatusChange={handleStatusChange}
        onReset={handleReset}
      />
      <ServiceGrid services={filteredServices} />
    </>
  );
}
