'use client';

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

interface Milestone {
  id: string;
  title: string;
  description: string;
  status: 'pending' | 'in_progress' | 'completed' | 'cancelled';
  dueDate: string;
  completedAt?: string;
  progress: number;
  deliverables: Array<{
    id: string;
    name: string;
    completed: boolean;
  }>;
}

interface ProjectMilestonesProps {
  projectId: string;
  userRole: 'freelancer' | 'client';
  projectStatus: 'active' | 'ongoing' | 'completed' | 'cancelled' | 'proposed';
}

export default function ProjectMilestones({ projectId, userRole, projectStatus }: ProjectMilestonesProps) {
  const [milestones, setMilestones] = useState<Milestone[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const fetchMilestones = async () => {
    try {
      setIsLoading(true);
      const response = await fetch(`/api/projects/${projectId}/milestones`);
      
      if (!response.ok) {
        throw new Error('Failed to fetch milestones');
      }
      
      const data = await response.json();
      if (data.success) {
        setMilestones(data.data);
      } else {
        throw new Error(data.error || 'Failed to fetch milestones');
      }
    } catch (error: any) {
      console.error('Error fetching milestones:', error);
      setError(error.message);
      
      // Mock milestones data for demo
      const mockMilestones: Milestone[] = [
        {
          id: '1',
          title: 'Project Setup & Planning',
          description: 'Initial project setup, requirement analysis, and project planning',
          status: 'completed',
          dueDate: '2024-06-05T00:00:00Z',
          completedAt: '2024-06-04T16:30:00Z',
          progress: 100,
          deliverables: [
            { id: '1', name: 'Project requirements document', completed: true },
            { id: '2', name: 'Technical architecture plan', completed: true },
            { id: '3', name: 'Timeline and milestones', completed: true }
          ]
        },
        {
          id: '2',
          title: 'Design & Wireframing',
          description: 'UI/UX design, wireframes, and prototype creation',
          status: 'completed',
          dueDate: '2024-06-08T00:00:00Z',
          completedAt: '2024-06-07T14:20:00Z',
          progress: 100,
          deliverables: [
            { id: '4', name: 'Wireframes', completed: true },
            { id: '5', name: 'UI/UX designs', completed: true },
            { id: '6', name: 'Interactive prototype', completed: true }
          ]
        },
        {
          id: '3',
          title: 'Development Phase 1',
          description: 'Core functionality development and backend implementation',
          status: 'completed',
          dueDate: '2024-06-11T00:00:00Z',
          completedAt: '2024-06-10T18:45:00Z',
          progress: 100,
          deliverables: [
            { id: '7', name: 'Backend API development', completed: true },
            { id: '8', name: 'Database setup', completed: true },
            { id: '9', name: 'User authentication', completed: true }
          ]
        },
        {
          id: '4',
          title: 'Development Phase 2',
          description: 'Frontend development and integration',
          status: 'completed',
          dueDate: '2024-06-12T00:00:00Z',
          completedAt: '2024-06-12T12:00:00Z',
          progress: 100,
          deliverables: [
            { id: '10', name: 'Frontend components', completed: true },
            { id: '11', name: 'API integration', completed: true },
            { id: '12', name: 'Responsive design', completed: true }
          ]
        }
      ];
      
      setMilestones(mockMilestones);
    } finally {
      setIsLoading(false);
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  const getMilestoneIcon = (status: Milestone['status']) => {
    switch (status) {
      case 'completed':
        return '✅';
      case 'in_progress':
        return '🔄';
      case 'pending':
        return '⏳';
      case 'cancelled':
        return '❌';
      default:
        return '📋';
    }
  };

  const getMilestoneColor = (status: Milestone['status']) => {
    switch (status) {
      case 'completed':
        return '#22c55e';
      case 'in_progress':
        return '#f59e0b';
      case 'pending':
        return '#6b7280';
      case 'cancelled':
        return '#ef4444';
      default:
        return '#6b7280';
    }
  };

  const calculateOverallProgress = () => {
    if (milestones.length === 0) return 0;
    const totalProgress = milestones.reduce((sum, milestone) => sum + milestone.progress, 0);
    return Math.round(totalProgress / milestones.length);
  };

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

  return (
    <div className="project-milestones">
      <div className="milestones-header">
        <h3>Project Milestones</h3>
        <div className="overall-progress">
          <div className="progress-info">
            <span className="progress-label">Overall Progress</span>
            <span className="progress-value">{calculateOverallProgress()}%</span>
          </div>
          <div className="progress-bar">
            <div 
              className="progress-fill"
              style={{ width: `${calculateOverallProgress()}%` }}
            ></div>
          </div>
        </div>
      </div>

      {error && milestones.length === 0 ? (
        <div className="milestones-error">
          <h4>Unable to load milestones</h4>
          <p>{error}</p>
        </div>
      ) : (
        <div className="milestones-container">
          {milestones.map((milestone, index) => (
            <div key={milestone.id} className={`milestone-item ${milestone.status}`}>
              <div className="milestone-timeline">
                <div 
                  className="milestone-marker"
                  style={{ backgroundColor: getMilestoneColor(milestone.status) }}
                >
                  {getMilestoneIcon(milestone.status)}
                </div>
                {index < milestones.length - 1 && (
                  <div className="milestone-line"></div>
                )}
              </div>
              
              <div className="milestone-content">
                <div className="milestone-header">
                  <h4>{milestone.title}</h4>
                  <div className="milestone-meta">
                    <span className={`status-badge ${milestone.status}`}>
                      {milestone.status.replace('_', ' ').toUpperCase()}
                    </span>
                    <span className="due-date">
                      Due: {formatDate(milestone.dueDate)}
                    </span>
                  </div>
                </div>
                
                <p className="milestone-description">{milestone.description}</p>
                
                {milestone.completedAt && (
                  <div className="completion-info">
                    <span className="completed-date">
                      ✅ Completed on {formatDate(milestone.completedAt)}
                    </span>
                  </div>
                )}
                
                <div className="milestone-progress">
                  <div className="progress-header">
                    <span>Progress</span>
                    <span>{milestone.progress}%</span>
                  </div>
                  <div className="progress-bar">
                    <div 
                      className="progress-fill"
                      style={{ 
                        width: `${milestone.progress}%`,
                        backgroundColor: getMilestoneColor(milestone.status)
                      }}
                    ></div>
                  </div>
                </div>
                
                {milestone.deliverables && milestone.deliverables.length > 0 && (
                  <div className="milestone-deliverables">
                    <h5>Deliverables:</h5>
                    <ul>
                      {milestone.deliverables.map(deliverable => (
                        <li key={deliverable.id} className={deliverable.completed ? 'completed' : ''}>
                          <span className="deliverable-status">
                            {deliverable.completed ? '✅' : '⏳'}
                          </span>
                          {deliverable.name}
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
      
      {projectStatus === 'completed' && (
        <div className="project-completion-summary">
          <div className="completion-header">
            <h4>🎉 Project Completed!</h4>
            <p>All milestones have been successfully completed.</p>
          </div>
          <div className="completion-stats">
            <div className="stat-item">
              <span className="stat-value">{milestones.length}</span>
              <span className="stat-label">Total Milestones</span>
            </div>
            <div className="stat-item">
              <span className="stat-value">{milestones.filter(m => m.status === 'completed').length}</span>
              <span className="stat-label">Completed</span>
            </div>
            <div className="stat-item">
              <span className="stat-value">100%</span>
              <span className="stat-label">Success Rate</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}