'use client';

/**
 * Client-side Stations Page Component
 * 
 * This component handles the interactive parts of the stations page
 * using the new charge point service and hooks architecture with infinite scrolling.
 */

import { useEffect, useState, useMemo } from 'react';
import { useSearchParams } from 'next/navigation';
import { ChevronUp } from 'lucide-react';
import ChargePointCard from '@/modules/chargepointModule/list/components/ChargePointCard';
import { useChargePoints } from '@/modules/chargepointModule/list/hooks/useChargePoints';
import { ChargePoint } from '@/types/chargepoint/chargepoint';
import type { ChargepointFilters } from '../types/chargepoint.type';
import { PaginationInfo } from '@/types/api/api_response';

interface ChargepointListProps {
  readonly initialChargepoints?: ChargePoint[];
  readonly initialPagination?: PaginationInfo;
  readonly defaultFilters: ChargepointFilters;
}

export default function ChargepointList({
  initialChargepoints,
  initialPagination,
  defaultFilters,
}: ChargepointListProps) {
  const searchParams = useSearchParams();
  const [showBackToTop, setShowBackToTop] = useState(false);
  // Get current search parameters
  const query = searchParams.get('query') || defaultFilters.query;
  const status = searchParams.get('status') || defaultFilters.status;
  const connectorType = searchParams.get('connector_type') || '';
  const minPower = Number(searchParams.get('min_power')) || defaultFilters.min_power || 0;
  const maxPower = Number(searchParams.get('max_power')) || defaultFilters.max_power || 350;
  const organizationCode = defaultFilters.organization_code;

  // Create stable parameters object to prevent unnecessary re-fetches
  const filterParams = useMemo(() => ({
    query,
    status,
    connector_type: connectorType,
    min_power: minPower,
    max_power: maxPower,
    organization_code: organizationCode, // Use the initial organization code
    // Remove paginate_limit from here since it's handled in the hook
  }), [query, status, connectorType, minPower, maxPower, organizationCode]);

  // Use the hook with filter parameters - it will automatically refetch when params change
  const {
    chargePoints,
    isLoading,
    isLoadingMore,
    hasNextPage,
    totalResults,
    currentPage,
    loadMoreChargePoints,
    refreshChargePoints,
    goToPage,
    error
  } = useChargePoints(initialChargepoints, filterParams, initialPagination);

  // Handle scroll for back-to-top button and infinite scroll
  useEffect(() => {
    const handleScroll = () => {
      setShowBackToTop(window.scrollY > 400);

      // Check if user scrolled near bottom for infinite scroll
      const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
      const scrolledToBottom = scrollTop + clientHeight >= scrollHeight - 1000; // Load more 1000px before bottom

      if (scrolledToBottom && hasNextPage && !isLoading && !isLoadingMore) {
        loadMoreChargePoints();
      }
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [hasNextPage, isLoading, isLoadingMore, loadMoreChargePoints]);

  // Back to top function - now also refreshes the charge points
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
    // Refresh charge points when going back to top
    refreshChargePoints();
  };

  if (error) return <ErrorChargepointList error={error} />;

  return (
    <div className="space-y-6">
      {chargePoints.length > 0 ? (
        <>
          <div className="flex items-center justify-between">
            <p className="text-sm text-slate-600 dark:text-slate-400">
              Showing {chargePoints.length} of {totalResults} charging station{totalResults === 1 ? '' : 's'}
              {hasNextPage && (
                <span className="ml-2 text-primary">• Scroll for more</span>
              )}
            </p>
            <div className="text-sm text-slate-500 dark:text-slate-400">
              Page {currentPage} of {Math.max(1, Math.ceil(totalResults / 9))}
            </div>
          </div>
          {Boolean(query || status || connectorType || minPower > 0 || maxPower < 350) && (
            <p className="text-sm text-slate-500 dark:text-slate-400">
              Filtered results{query && ` for "${query}"`}
            </p>
          )}

          {/* Grid */}
          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {chargePoints.map((chargePoint) => (
              <ChargePointCard key={chargePoint.id || chargePoint.name} chargePoint={chargePoint} />
            ))}
          </div>

          {/* Loading More Indicator */}
          {isLoadingMore && (
            <div className="flex justify-center py-8">
              <div className="flex items-center gap-3 text-sm text-slate-600 dark:text-slate-400">
                <div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"></div>
                Loading more charging stations...
              </div>
            </div>
          )}

          {/* End of Results Indicator */}
          {!hasNextPage && chargePoints.length > 9 && (
            <div className="flex justify-center py-8">
              <p className="text-sm text-slate-500 dark:text-slate-400">
                You&apos;ve reached the end of the results
              </p>
            </div>
          )}
          
        </>
      ) : (
        <div className="flex h-60 flex-col items-center justify-center rounded-lg border border-dashed border-stroke dark:border-strokedark">
          <div className="text-center">
            <h3 className="text-lg font-medium text-slate-900 dark:text-slate-100">
              No charging stations found
            </h3>
            <p className="mt-1 text-slate-500 dark:text-slate-400">
              {query || status || connectorType || minPower > 0 || maxPower < 350
                ? 'Try adjusting your filters or search terms'
                : 'No charging stations are currently available'
              }
            </p>
          </div>
        </div>
      )}

      {/* Back to Top Button */}
      {showBackToTop && (
        <button
          onClick={scrollToTop}
          className="fixed bottom-6 right-6 z-50 flex h-12 w-12 items-center justify-center rounded-full bg-primary text-white shadow-lg transition-all hover:bg-primary/90 hover:shadow-xl"
          aria-label="Back to top and refresh"
          title="Back to top and refresh"
        >
          <ChevronUp className="h-6 w-6" />
        </button>
      )}
    </div>
  );
}

function ErrorChargepointList({ error }: { error: string }) {
  return (
    <div className="space-y-6">
      <div className="flex h-60 flex-col items-center justify-center rounded-lg border border-dashed border-red-300 bg-red-50 dark:border-red-800 dark:bg-red-950">
        <div className="text-center">
          <h3 className="text-lg font-medium text-red-900 dark:text-red-100">
            Error Loading Charging Stations
          </h3>
          <p className="mt-1 text-red-600 dark:text-red-400">
            {error}
          </p>
        </div>
      </div>
    </div>
  );

}