'use client';

/**
 * Project Activity Page
 *
 * Full-page view of real-time project activity with:
 * - Real-time SSE connection for project events
 * - Event filtering and search
 * - Time-based grouping
 * - Approval handling
 *
 * @module app/[locale]/(authenticated)/projects/[id]/activity/page
 */

import { use, useState, useCallback } from 'react';
import { useRouter } from '@/lib/i18n/routing';
import { ArrowLeft, RefreshCw, Bell, BellOff, AlertTriangle } from 'lucide-react';
import { useProjectEvents } from '@/lib/hooks/useProjectEvents';
import { ActivityFeed } from '@/components/activity';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { EventType, type ProjectEvent } from '@/lib/types/events';
import { toast } from 'sonner';

interface ProjectActivityPageProps {
  params: Promise<{
    locale: string;
    id: string;
  }>;
}

// Demo events for when SSE is not connected
function getDemoEvents(projectId: string): ProjectEvent[] {
  return [
    {
      id: 'demo-001',
      type: EventType.APPROVAL_REQUESTED,
      timestamp: new Date(Date.now() - 1000 * 60 * 5).toISOString(),
      project_id: projectId,
      actor_id: 'agent-001',
      actor_type: 'agent',
      payload: {
        approval_id: 'apr-001',
        approval_type: 'architecture_decision',
        description: 'Approval required for API design document for the checkout flow.',
        requested_by: 'Architect',
        timeout_minutes: 60,
      },
    },
    {
      id: 'demo-002',
      type: EventType.AGENT_MESSAGE,
      timestamp: new Date(Date.now() - 1000 * 60 * 10).toISOString(),
      project_id: projectId,
      actor_id: 'agent-002',
      actor_type: 'agent',
      payload: {
        agent_instance_id: 'agent-002',
        message: 'Completed JWT token generation and validation. Moving on to session management.',
        message_type: 'info',
        metadata: { progress: 65 },
      },
    },
    {
      id: 'demo-003',
      type: EventType.AGENT_STATUS_CHANGED,
      timestamp: new Date(Date.now() - 1000 * 60 * 20).toISOString(),
      project_id: projectId,
      actor_id: 'agent-003',
      actor_type: 'agent',
      payload: {
        agent_instance_id: 'agent-003',
        previous_status: 'idle',
        new_status: 'active',
        reason: 'Started working on product catalog component',
      },
    },
    {
      id: 'demo-004',
      type: EventType.ISSUE_UPDATED,
      timestamp: new Date(Date.now() - 1000 * 60 * 30).toISOString(),
      project_id: projectId,
      actor_id: 'agent-002',
      actor_type: 'agent',
      payload: {
        issue_id: 'issue-038',
        changes: { status: { from: 'in_progress', to: 'in_review' } },
      },
    },
    {
      id: 'demo-005',
      type: EventType.SPRINT_STARTED,
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString(),
      project_id: projectId,
      actor_id: null,
      actor_type: 'system',
      payload: {
        sprint_id: 'sprint-003',
        sprint_name: 'Sprint 3 - Checkout Flow',
        goal: 'Complete checkout and payment integration',
        issue_count: 15,
      },
    },
    {
      id: 'demo-006',
      type: EventType.ISSUE_CREATED,
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 4).toISOString(),
      project_id: projectId,
      actor_id: 'agent-001',
      actor_type: 'agent',
      payload: {
        issue_id: 'issue-050',
        title: 'Implement shopping cart persistence',
        priority: 'high',
        labels: ['feature', 'sprint-3'],
      },
    },
  ];
}

export default function ProjectActivityPage({ params }: ProjectActivityPageProps) {
  const { id: projectId } = use(params);
  const router = useRouter();
  const [notificationsEnabled, setNotificationsEnabled] = useState(true);

  // SSE hook for real-time events
  const {
    events: sseEvents,
    connectionState,
    reconnect,
    isConnected,
  } = useProjectEvents(projectId, {
    autoConnect: true,
    onEvent: (event) => {
      // Show notification for new events if enabled
      if (notificationsEnabled && event.type === EventType.APPROVAL_REQUESTED) {
        toast.info('New approval request', {
          description: 'An agent is requesting your approval.',
        });
      }
    },
  });

  // Use demo events when not connected or no events received
  const demoEvents = getDemoEvents(projectId);
  const events = isConnected && sseEvents.length > 0 ? sseEvents : demoEvents;

  const handleBack = useCallback(() => {
    router.push(`/projects/${projectId}`);
  }, [router, projectId]);

  // Approval handlers
  const handleApprove = useCallback((event: ProjectEvent) => {
    // TODO: Call API to approve the request
    toast.success('Approval granted', {
      description: `Approved request ${event.id}`,
    });
  }, []);

  const handleReject = useCallback((event: ProjectEvent) => {
    // TODO: Call API to reject the request
    toast.info('Approval rejected', {
      description: `Rejected request ${event.id}`,
    });
  }, []);

  const handleEventClick = useCallback(
    (event: ProjectEvent) => {
      // Navigate to relevant detail page based on event type
      if (event.type.startsWith('issue.')) {
        const payload = event.payload as Record<string, unknown>;
        if (payload.issue_id) {
          router.push(`/projects/${projectId}/issues/${payload.issue_id}`);
        }
      }
    },
    [router, projectId]
  );

  const pendingCount = events.filter((e) => e.type === EventType.APPROVAL_REQUESTED).length;

  return (
    <div className="container mx-auto px-4 py-6">
      <div className="mx-auto max-w-4xl space-y-6">
        {/* Page Header */}
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex items-center gap-4">
            <Button variant="ghost" size="icon" onClick={handleBack}>
              <ArrowLeft className="h-4 w-4" />
            </Button>
            <div>
              <h1 className="text-3xl font-bold tracking-tight">Project Activity</h1>
              <p className="mt-1 text-muted-foreground">Real-time updates from this project</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {pendingCount > 0 && (
              <Badge variant="destructive" className="gap-1">
                <AlertTriangle className="h-3 w-3" />
                {pendingCount} pending
              </Badge>
            )}
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setNotificationsEnabled(!notificationsEnabled)}
              aria-label={notificationsEnabled ? 'Disable notifications' : 'Enable notifications'}
            >
              {notificationsEnabled ? (
                <Bell className="h-4 w-4" />
              ) : (
                <BellOff className="h-4 w-4" />
              )}
            </Button>
            <Button variant="ghost" size="icon" onClick={reconnect} aria-label="Refresh connection">
              <RefreshCw
                className={connectionState === 'connecting' ? 'h-4 w-4 animate-spin' : 'h-4 w-4'}
              />
            </Button>
          </div>
        </div>

        {/* Demo Mode Banner */}
        {(!isConnected || sseEvents.length === 0) && (
          <div className="rounded-lg border border-yellow-200 bg-yellow-50 p-4 dark:border-yellow-800 dark:bg-yellow-950">
            <p className="text-sm text-yellow-800 dark:text-yellow-200">
              <strong>Demo Mode:</strong> Showing sample events. Events will appear here when agents
              are active.
            </p>
          </div>
        )}

        {/* Activity Feed Component */}
        <ActivityFeed
          events={events}
          connectionState={isConnected ? connectionState : 'disconnected'}
          onReconnect={reconnect}
          onApprove={handleApprove}
          onReject={handleReject}
          onEventClick={handleEventClick}
          maxHeight={600}
          showHeader={false}
          enableFiltering
          enableSearch
        />
      </div>
    </div>
  );
}
