'use client';

import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { useSearchParams } from 'next/navigation';
import { ActivityFilters, NotificationActivity } from "@alga-psa/types";
import { Button } from "@alga-psa/ui/components/Button";
import { Card } from "@alga-psa/ui/components/Card";
import { fetchNotificationActivities } from "@alga-psa/client-portal/actions";
import { Filter, XCircle } from 'lucide-react';
import { getUnreadCountAction } from "@alga-psa/notifications/actions";
import { NotificationDetailView } from "@alga-psa/notifications/components";
import { getCurrentUser } from "@alga-psa/user-composition/actions";
import { Badge } from "@alga-psa/ui/components/Badge";
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';
import CustomTabs from '@alga-psa/ui/components/CustomTabs';
import { useDrawer } from '@alga-psa/ui';
import { ClientNotificationCard } from './ClientNotificationCard';
import { ClientNotificationFiltersDialog } from './ClientNotificationFiltersDialog';

const NOTIFICATION_TAB_IDS = ['unread', 'all', 'read'] as const;
const DEFAULT_NOTIFICATION_TAB = 'unread';

export function ClientNotificationsList() {
  const { t: tProfile } = useTranslation('client-portal');
  const { t: tCommon } = useTranslation('common');
  const searchParams = useSearchParams();
  const tabParam = searchParams?.get('tab');

  // Get translated tab labels
  const unreadTabLabel = tProfile('notifications.tabs.unread', 'Unread');
  const allTabLabel = tProfile('notifications.tabs.all', 'All');
  const readTabLabel = tProfile('notifications.tabs.read', 'Read');

  // Determine initial tab from URL or default to "unread"
  const initialTab = useMemo(() => {
    const requestedTab = tabParam?.toLowerCase();
    if (requestedTab && NOTIFICATION_TAB_IDS.includes(requestedTab as typeof NOTIFICATION_TAB_IDS[number])) {
      return requestedTab;
    }
    return DEFAULT_NOTIFICATION_TAB;
  }, [tabParam]);

  const [activities, setActivities] = useState<NotificationActivity[]>([]);
  const [loading, setLoading] = useState(true);
  const { openDrawer, closeDrawer } = useDrawer();
  const [error, setError] = useState<string | null>(null);
  const [isFilterDialogOpen, setIsFilterDialogOpen] = useState(false);
  const [activeTab, setActiveTab] = useState<string>(initialTab);
  const [notificationFilters, setNotificationFilters] = useState<Partial<ActivityFilters>>(() => {
    // Set initial filters based on URL tab parameter
    const requestedTab = tabParam?.toLowerCase();
    if (requestedTab === 'read') {
        return { isClosed: true };
    }
    if (requestedTab === 'all') {
        return {};
    }
    return { isClosed: false }; // Default: show unread only
  });
  const [unreadCount, setUnreadCount] = useState<number>(0);

  // Update active tab when URL parameter changes
  useEffect(() => {
    const requestedTab = tabParam?.toLowerCase();
    const targetTab = requestedTab && NOTIFICATION_TAB_IDS.includes(requestedTab as typeof NOTIFICATION_TAB_IDS[number])
      ? requestedTab
      : DEFAULT_NOTIFICATION_TAB;

    if (targetTab !== activeTab) {
      setActiveTab(targetTab);
      if (targetTab === 'read') {
        setNotificationFilters(prev => ({ ...prev, isClosed: true }));
      } else if (targetTab === 'all') {
        setNotificationFilters(prev => {
          const { isClosed, ...rest } = prev;
          return rest;
        });
      } else {
        setNotificationFilters(prev => ({ ...prev, isClosed: false }));
      }
    }
  }, [tabParam, activeTab]);

  // Fetch initial activities
  const loadActivities = useCallback(async (filters: Partial<ActivityFilters>) => {
    try {
      setLoading(true);
      setError(null);

      // Fetch notification activities using current filters
      const result = await fetchNotificationActivities(filters);

      // Sort by creation date (newest first)
      const sortedActivities = result.sort((a: NotificationActivity, b: NotificationActivity) => {
        return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
      });

      setActivities(sortedActivities);
    } catch (err) {
      console.error('Error loading notification activities:', err);
      setError(tProfile('notifications.preferences.loadError', 'Failed to load notifications'));
    } finally {
      setLoading(false);
    }
  }, [tProfile]);

  // Fetch unread count
  const loadUnreadCount = useCallback(async () => {
    try {
      const user = await getCurrentUser();
      if (user) {
        const result = await getUnreadCountAction(user.tenant, user.user_id);
        setUnreadCount(result.unread_count);
      }
    } catch (err) {
      console.error('Error loading unread count:', err);
    }
  }, []);

  // Load activities initially and when filters change
  useEffect(() => {
    loadActivities(notificationFilters);
    loadUnreadCount();
  }, [notificationFilters, loadActivities, loadUnreadCount]);

  const handleRefresh = () => {
    // Reload activities with the current filters
    loadActivities(notificationFilters);
    loadUnreadCount();
  };

  const handleOpenNotification = useCallback((activity: NotificationActivity) => {
    openDrawer(
      <NotificationDetailView
        notification={activity}
        onClose={() => closeDrawer()}
      />
    );
  }, [closeDrawer, openDrawer]);

  const handleApplyFilters = (newFilters: Partial<ActivityFilters>) => {
    setNotificationFilters(prevFilters => ({
      ...prevFilters,
      ...newFilters,
    }));
  };

  // Function to check if filters are active (beyond the default)
  const isFiltersActive = useCallback(() => {
    const defaultFilters: Partial<ActivityFilters> = { isClosed: false };
    // Check if any filter key exists beyond the default 'isClosed'
    const hasExtraKeys = Object.keys(notificationFilters).some(key => !(key in defaultFilters));
    // Check if 'isClosed' is different from the default
    const isClosedChanged = notificationFilters.isClosed !== defaultFilters.isClosed;
    // Check if any filter value is actually set
    const hasSetValues = Object.entries(notificationFilters).some(([key, value]) => {
      if (key === 'isClosed') return value !== false;
      if (Array.isArray(value)) return value.length > 0;
      return value !== undefined && value !== null && value !== '';
    });

    return hasExtraKeys || isClosedChanged || hasSetValues;
  }, [notificationFilters]);

  const handleResetFilters = () => {
    setNotificationFilters({ isClosed: false }); // Reset to default filters
  };

  // Handle tab change to update filters and URL
  const handleTabChange = (tabId: string) => {
    setActiveTab(tabId);

    // Update filters based on tab
    if (tabId === 'unread') {
      // Show unread notifications
      setNotificationFilters(prev => ({ ...prev, isClosed: false }));
    } else if (tabId === 'read') {
      // Show read notifications
      setNotificationFilters(prev => ({ ...prev, isClosed: true }));
    } else if (tabId === 'all') {
      // Show all notifications
      const { isClosed, ...rest } = notificationFilters;
      setNotificationFilters(rest);
    }

    // Update URL with the new tab
    if (typeof window !== 'undefined') {
      const params = new URLSearchParams(window.location.search);

      if (tabId === DEFAULT_NOTIFICATION_TAB) {
        // Default tab - remove from URL
        params.delete('tab');
      } else {
        params.set('tab', tabId);
      }

      const basePath = window.location.pathname;
      const newUrl = params.toString()
        ? `${basePath}?${params.toString()}`
        : basePath;
      window.history.pushState({}, '', newUrl);
    }
  };

  // Render notifications content
  const renderNotifications = () => {
    if (loading) {
      return (
        <div className="flex justify-center items-center h-40">
          <p className="text-gray-500">{tCommon('common.loading')}</p>
        </div>
      );
    }

    if (error) {
      return (
        <div className="flex justify-center items-center h-40">
          <p className="text-red-500">{error}</p>
        </div>
      );
    }

    if (activities.length === 0) {
      return (
        <div className="flex justify-center items-center h-40">
          <p className="text-gray-500">{tProfile('notifications.noNotifications')}</p>
        </div>
      );
    }

    return (
      <div className="grid grid-cols-1 gap-4">
        {activities.map(activity => (
          <ClientNotificationCard
            key={activity.id}
            activity={activity}
            onActionComplete={handleRefresh}
            onOpen={handleOpenNotification}
          />
        ))}
      </div>
    );
  };

  const tabContent = [
    {
      id: 'unread',
      label: unreadTabLabel,
      content: renderNotifications()
    },
    {
      id: 'all',
      label: allTabLabel,
      content: renderNotifications()
    },
    {
      id: 'read',
      label: readTabLabel,
      content: renderNotifications()
    }
  ];

  const tabStyles = {
    trigger: "px-4 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:outline-none focus:text-gray-700 focus:border-gray-300 border-b-2 border-transparent",
    activeTrigger: "data-[state=active]:border-blue-500 data-[state=active]:text-blue-600"
  };

  return (
    <Card className="bg-white">
      <div className="p-6 space-y-4">
        {/* Header with filters */}
        <div className="flex flex-row items-center justify-between">
          <div className="flex items-center gap-2">
            <h3 className="text-lg font-semibold">{tProfile('notifications.title')}</h3>
            {unreadCount > 0 && (
              <Badge variant="default" className="bg-blue-500">
                {unreadCount}
              </Badge>
            )}
          </div>
          <div className="flex items-center gap-2">
            <Button
              id="refresh-notifications-button"
              variant="outline"
              size="sm"
              onClick={handleRefresh}
              disabled={loading}
              aria-label={tCommon('common.refresh', 'Refresh')}
            >
              {tCommon('common.refresh', 'Refresh')}
            </Button>
            {isFiltersActive() ? (
              <Button
                id="reset-notification-filters-button"
                variant="outline"
                size="sm"
                onClick={handleResetFilters}
                disabled={loading}
                className="gap-1"
              >
                <XCircle className="h-4 w-4" />
                {tCommon('common.resetFilters', 'Reset')}
              </Button>
            ) : (
              <Button
                id="filter-notifications-button"
                variant="outline"
                size="sm"
                onClick={() => setIsFilterDialogOpen(true)}
                disabled={loading}
                aria-label={tCommon('common.filter', 'Filter')}
              >
                <Filter size={16} className="mr-1" /> {tCommon('common.filter', 'Filter')}
              </Button>
            )}
          </div>
        </div>

        {/* Tabs for filtering notifications */}
        <CustomTabs
          tabs={tabContent}
          defaultTab={activeTab}
          onTabChange={handleTabChange}
          tabStyles={tabStyles}
        />

        {isFilterDialogOpen && (
          <ClientNotificationFiltersDialog
            isOpen={isFilterDialogOpen}
            onOpenChange={setIsFilterDialogOpen}
            initialFilters={notificationFilters}
            onApplyFilters={handleApplyFilters}
          />
        )}
      </div>
    </Card>
  );
}
