'use client';

import { useState, useEffect } from 'react';
import './project-timeline.css';

interface TimelineEvent {
  id: string;
  type: 'created' | 'bid_placed' | 'bid_accepted' | 'milestone_completed' | 'cancelled' | 'refund_requested' | 'refund_processed';
  title: string;
  description: string;
  timestamp: string;
  actor: string;
  actorRole: 'freelancer' | 'client' | 'system';
  data?: any;
}

interface ProjectTimelineProps {
  projectId: string;
  showCancellationEvents?: boolean;
}

export default function ProjectTimeline({ projectId, showCancellationEvents = false }: ProjectTimelineProps) {
  const [events, setEvents] = useState<TimelineEvent[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchTimelineEvents();
  }, [projectId]);

  const fetchTimelineEvents = async () => {
    try {
      setIsLoading(true);
      const response = await fetch(`/api/projects/${projectId}/timeline`);
      
      if (!response.ok) {
        throw new Error('Failed to fetch timeline events');
      }
      
      const data = await response.json();
      if (data.success) {
        setEvents(data.data);
      } else {
        throw new Error(data.error || 'Failed to fetch timeline');
      }
    } catch (error: any) {
      console.error('Error fetching timeline:', error);
      setError(error.message);
      
      // Mock timeline data for demo
      const mockEvents: TimelineEvent[] = [
        {
          id: '1',
          type: 'created',
          title: 'Project Created',
          description: 'Project was posted and is now accepting bids',
          timestamp: '2024-06-03T15:34:00Z',
          actor: 'Esther Howard',
          actorRole: 'client'
        },
        {
          id: '2',
          type: 'bid_placed',
          title: 'Bid Received',
          description: 'New proposal submitted for €2000',
          timestamp: '2024-06-04T10:15:00Z',
          actor: 'John Developer',
          actorRole: 'freelancer'
        },
        {
          id: '3',
          type: 'bid_accepted',
          title: 'Proposal Accepted',
          description: 'Client accepted the proposal and project started',
          timestamp: '2024-06-05T14:20:00Z',
          actor: 'Esther Howard',
          actorRole: 'client'
        },
        {
          id: '4',
          type: 'milestone_completed',
          title: 'Initial Setup Completed',
          description: 'Project setup and environment configuration finished',
          timestamp: '2024-06-08T16:45:00Z',
          actor: 'John Developer',
          actorRole: 'freelancer'
        },
        {
          id: '5',
          type: 'cancelled',
          title: 'Project Cancelled',
          description: 'Project was cancelled due to scope changes',
          timestamp: '2024-06-15T14:30:00Z',
          actor: 'Esther Howard',
          actorRole: 'client'
        },
        {
          id: '6',
          type: 'refund_requested',
          title: 'Refund Requested',
          description: 'Client requested a refund of €1500',
          timestamp: '2024-06-15T14:35:00Z',
          actor: 'Esther Howard',
          actorRole: 'client'
        },
        {
          id: '7',
          type: 'refund_processed',
          title: 'Refund Processed',
          description: 'Refund of €1500 has been processed successfully',
          timestamp: '2024-06-16T10:15:00Z',
          actor: 'System',
          actorRole: 'system'
        }
      ];
      
      setEvents(showCancellationEvents ? mockEvents : mockEvents.slice(0, 4));
    } finally {
      setIsLoading(false);
    }
  };

  const formatTimestamp = (timestamp: string) => {
    return new Date(timestamp).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const getEventIcon = (type: TimelineEvent['type']) => {
    switch (type) {
      case 'created':
        return '📝';
      case 'bid_placed':
        return '💰';
      case 'bid_accepted':
        return '✅';
      case 'milestone_completed':
        return '🎯';
      case 'cancelled':
        return '❌';
      case 'refund_requested':
        return '💸';
      case 'refund_processed':
        return '✅';
      default:
        return '📌';
    }
  };

  const getEventColor = (type: TimelineEvent['type']) => {
    switch (type) {
      case 'created':
        return '#3b82f6';
      case 'bid_placed':
        return '#f59e0b';
      case 'bid_accepted':
        return '#22c55e';
      case 'milestone_completed':
        return '#8b5cf6';
      case 'cancelled':
        return '#ef4444';
      case 'refund_requested':
        return '#f97316';
      case 'refund_processed':
        return '#22c55e';
      default:
        return '#6b7280';
    }
  };

  if (isLoading) {
    return (
      <div className="timeline-loading">
        <div className="spinner-border" role="status">
          <span className="visually-hidden">Loading timeline...</span>
        </div>
        <p>Loading project timeline...</p>
      </div>
    );
  }

  if (error && events.length === 0) {
    return (
      <div className="timeline-error">
        <h4>Unable to load timeline</h4>
        <p>{error}</p>
      </div>
    );
  }

  return (
    <div className="project-timeline">
      <h3>Project Timeline</h3>
      <div className="timeline-container">
        {events.map((event, index) => (
          <div key={event.id} className="timeline-item">
            <div 
              className="timeline-marker"
              style={{ backgroundColor: getEventColor(event.type) }}
            >
              {getEventIcon(event.type)}
            </div>
            <div className="timeline-content">
              <div className="timeline-header">
                <h4>{event.title}</h4>
                <span className="timeline-timestamp">
                  {formatTimestamp(event.timestamp)}
                </span>
              </div>
              <p className="timeline-description">
                {event.description}
              </p>
              <div className="timeline-actor">
                <span className={`actor-badge ${event.actorRole}`}>
                  {event.actor}
                </span>
              </div>
            </div>
            {index < events.length - 1 && <div className="timeline-line"></div>}
          </div>
        ))}
      </div>
      
      {showCancellationEvents && (
        <div className="cancellation-summary">
          <h4>Cancellation Summary</h4>
          <div className="summary-grid">
            <div className="summary-item">
              <span className="label">Cancelled on:</span>
              <span className="value">
                {formatTimestamp(events.find(e => e.type === 'cancelled')?.timestamp || '')}
              </span>
            </div>
            <div className="summary-item">
              <span className="label">Cancelled by:</span>
              <span className="value">
                {events.find(e => e.type === 'cancelled')?.actor || 'Unknown'}
              </span>
            </div>
            <div className="summary-item">
              <span className="label">Refund status:</span>
              <span className="value refund-processed">
                {events.some(e => e.type === 'refund_processed') ? 'Processed' : 
                 events.some(e => e.type === 'refund_requested') ? 'Requested' : 'Not applicable'}
              </span>
            </div>
            <div className="summary-item">
              <span className="label">Total events:</span>
              <span className="value">{events.length}</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}