'use client';

import React, { useCallback, useRef } from 'react';
import { AlertCircle, Battery, RefreshCw, CheckCircle2 } from 'lucide-react';
import SessionCard from '@/modules/sessionModule/list/components/SessionCard';
import SessionCardSkeleton from '@/modules/sessionModule/list/components/SessionCardSkeleton';
import { useSessions } from '@/modules/sessionModule/list/hooks/useSessions';
import type { SessionQueryParams } from '@/services/session/sessionService';
import type { Session } from '@/types/session/session';
import type { PaginationInfo } from '@/types/api/api_response';

type InfiniteSessionListProps = {
  readonly params?: Partial<SessionQueryParams>;
  readonly className?: string;
  readonly initialSessions?: Session[];
  readonly initialPagination?: PaginationInfo;
  readonly containerHeight?: string;
};

export default function InfiniteSessionList({
  params,
  className,
  initialSessions,
  initialPagination,
  containerHeight,
}: InfiniteSessionListProps) {
  const {
    sessions,
    isLoading,
    isLoadingMore,
    error,
    hasNextPage,
    totalResults,
    loadMoreSessions,
    refreshSessions,
    clearError,
  } = Array.isArray(initialSessions)
    ? useSessions(initialSessions, {
        paginate_limit: 10,
        sort_order: 'desc',
        sort_by: 'updated_at',
        status: 'Started,Ended',
        ...(params || {}),
      }, initialPagination)
    : useSessions({
        paginate_limit: 10,
        sort_order: 'desc',
        sort_by: 'updated_at',
        status: 'Started,Ended',
        ...(params || {}),
      });

  // Meniru behavior WalletHistorySection: observe elemen terakhir dalam container scroll
  const observer = useRef<IntersectionObserver | null>(null);
  const lastSessionElementRef = useCallback((node: HTMLDivElement | null) => {
    if (isLoading || isLoadingMore) return;
    if (observer.current) observer.current.disconnect();

    observer.current = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting && hasNextPage) {
        void loadMoreSessions();
      }
    });

    if (node) observer.current.observe(node);
  }, [isLoading, isLoadingMore, hasNextPage, loadMoreSessions]);

  // Default height: responsive based on viewport
  const defaultHeight = containerHeight || 'max-h-[calc(100vh-24rem)] md:max-h-[calc(100vh-20rem)]';

  const handleRetry = useCallback(() => {
    clearError();
    if (sessions.length > 0) {
      void loadMoreSessions();
    } else {
      void refreshSessions();
    }
  }, [clearError, loadMoreSessions, refreshSessions, sessions.length]);

  return (
    <div className={className}>
      <div 
        className={`${defaultHeight} overflow-y-auto space-y-3 pr-2 custom-scrollbar`}
      >
        {sessions.length > 0 ? (
          <>
            {sessions.map((session: Session, index: number) => {
              const isLastItem = sessions.length === index + 1;
              return (
                <div 
                  ref={isLastItem ? lastSessionElementRef : undefined} 
                  key={session._id}
                  className="mb-3 last:mb-0 p-2"
                >
                  <SessionCard session={session} />
                </div>
              );
            })}

            {isLoadingMore && (
              <div className="space-y-3 py-4">
                <SessionCardSkeleton />
                <SessionCardSkeleton />
                <SessionCardSkeleton />
              </div>
            )}
            
            {error && (
              <div className="py-4">
                <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
                  <div className="flex items-start space-x-3">
                    <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
                    <div className="flex-1">
                      <h3 className="text-sm font-semibold text-red-800 dark:text-red-300 mb-1">
                        Failed to load sessions
                      </h3>
                      <p className="text-sm text-red-600 dark:text-red-400 mb-3">
                        {error}
                      </p>
                      <button
                        onClick={handleRetry}
                        className="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-800 rounded-md transition-colors"
                      >
                        <RefreshCw className="w-4 h-4 mr-2" />
                        Retry
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )}
            
            {!hasNextPage && !isLoadingMore && !error && (
              <div className="py-6 text-center">
                <div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-green-100 dark:bg-green-900/30 mb-3">
                  <CheckCircle2 className="w-6 h-6 text-green-600 dark:text-green-400" />
                </div>
                <p className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  All {totalResults} session{totalResults !== 1 ? 's' : ''} loaded
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  You've reached the end of your session history
                </p>
              </div>
            )}
          </>
        ) : (
          <>
            {isLoading ? (
              <div className="space-y-3 py-4">
                <SessionCardSkeleton />
                <SessionCardSkeleton />
                <SessionCardSkeleton />
                <SessionCardSkeleton />
                <SessionCardSkeleton />
              </div>
            ) : (
              <div className="py-12 text-center">
                <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-800 mb-4">
                  <Battery className="w-8 h-8 text-gray-400 dark:text-gray-500" />
                </div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                  No sessions found
                </h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4 max-w-md mx-auto">
                  You haven't started any charging sessions yet. Start your first session to see it here.
                </p>
              </div>
            )}
            
            {error && (
              <div className="py-4">
                <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
                  <div className="flex items-start space-x-3">
                    <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
                    <div className="flex-1">
                      <h3 className="text-sm font-semibold text-red-800 dark:text-red-300 mb-1">
                        Failed to load sessions
                      </h3>
                      <p className="text-sm text-red-600 dark:text-red-400 mb-3">
                        {error}
                      </p>
                      <button
                        onClick={handleRetry}
                        className="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-800 rounded-md transition-colors"
                      >
                        <RefreshCw className="w-4 h-4 mr-2" />
                        Retry
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}


