'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useToast } from '@/components/ui/ToastContext';
import ProjectMilestones from '@/components/project/ProjectMilestones';
import './ongoing-project-details.css';

interface OngoingProjectDetails {
  id: string;
  title: string;
  description: string;
  status: 'active' | 'ongoing';
  budget: number;
  currency: string;
  deadline: string;
  createdAt: string;
  startedAt: string;
  freelancerId: string;
  clientId: string;
  freelancerName: string;
  clientName: string;
  clientAvatar: string;
  clientRating: number;
  clientReviewsCount: number;
  clientProjectsCount: number;
  clientMemberSince: string;
  clientLocation: string;
  category: string;
  userRole: 'freelancer' | 'client';
  progress: number;
  documents: Array<{
    id: string;
    name: string;
    type: string;
    url: string;
    uploadedAt: string;
    uploadedBy: string;
  }>;
  currentMilestone?: string;
}

interface ProposalUpdate {
  budget?: number;
  deadline?: string;
  description?: string;
  reason: string;
}

export default function OngoingProjectDetailsPage({ params }: { params: Promise<{ projectId: string }> }) {
  const { data: session, status } = useSession();
  const { showSuccess, showError } = useToast();
  
  const [project, setProject] = useState<OngoingProjectDetails | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [projectId, setProjectId] = useState<string>('');
  const [showUpdateModal, setShowUpdateModal] = useState(false);
  const [isSubmittingUpdate, setIsSubmittingUpdate] = useState(false);
  const [updateData, setUpdateData] = useState<ProposalUpdate>({
    reason: ''
  });
  const [showDeliverableModal, setShowDeliverableModal] = useState(false);
  const [isSubmittingDeliverable, setIsSubmittingDeliverable] = useState(false);
  const [deliverableData, setDeliverableData] = useState({
    deliverables: [{ name: '', description: '', fileUrl: '' }],
    completionNote: ''
  });

  useEffect(() => {
    const initializeParams = async () => {
      const resolvedParams = await params;
      setProjectId(resolvedParams.projectId);
    };
    
    initializeParams();
  }, [params]);

  useEffect(() => {
    if (status === 'authenticated' && projectId) {
      fetchProjectDetails();
    }
  }, [status, projectId]);

  const fetchProjectDetails = async () => {
    try {
      setIsLoading(true);
      const response = await fetch(`/api/projects/ongoing/${projectId}`);
      
      if (!response.ok) {
        throw new Error('Failed to fetch ongoing project details');
      }
      
      const data = await response.json();
      if (data.success) {
        setProject(data.data);
      } else {
        throw new Error(data.error || 'Failed to fetch project details');
      }
    } catch (error: any) {
      console.error('Error fetching ongoing project details:', error);
      showError(error.message || 'Failed to load project details');
    } finally {
      setIsLoading(false);
    }
  };

  const handleUpdateProposal = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!project) return;
    
    if (!updateData.reason.trim()) {
      showError('Please provide a reason for the update');
      return;
    }

    try {
      setIsSubmittingUpdate(true);
      const response = await fetch(`/api/projects/${projectId}/update-proposal`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updateData),
      });

      if (!response.ok) {
        throw new Error('Failed to submit proposal update');
      }

      const data = await response.json();
      if (data.success) {
        showSuccess('Proposal update submitted successfully!');
        setShowUpdateModal(false);
        setUpdateData({ reason: '' });
        await fetchProjectDetails();
      } else {
        throw new Error(data.error || 'Failed to submit proposal update');
      }
    } catch (error: any) {
      console.error('Error submitting proposal update:', error);
      showError(error.message || 'Failed to submit proposal update');
    } finally {
      setIsSubmittingUpdate(false);
    }
  };

  const handleSubmitDeliverables = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!project) return;
    
    // Validate deliverables
    const validDeliverables = deliverableData.deliverables.filter(
      d => d.name.trim() && d.description.trim() && d.fileUrl.trim()
    );
    
    if (validDeliverables.length === 0) {
      showError('Please add at least one complete deliverable with name, description, and file URL');
      return;
    }

    try {
      setIsSubmittingDeliverable(true);
      const response = await fetch(`/api/projects/${projectId}/complete`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          deliverables: validDeliverables,
          completionNote: deliverableData.completionNote.trim() || undefined
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to submit deliverables');
      }

      const data = await response.json();
      if (data.success) {
        showSuccess('Project completed successfully! You will be redirected to leave a review.');
        setShowDeliverableModal(false);
        
        // Redirect to freelancer review page
        setTimeout(() => {
          window.location.href = `/freelancer/review/${projectId}`;
        }, 2000);
      } else {
        throw new Error(data.error || 'Failed to submit deliverables');
      }
    } catch (error: any) {
      console.error('Error submitting deliverables:', error);
      showError(error.message || 'Failed to submit deliverables');
    } finally {
      setIsSubmittingDeliverable(false);
    }
  };

  const addDeliverable = () => {
    setDeliverableData(prev => ({
      ...prev,
      deliverables: [...prev.deliverables, { name: '', description: '', fileUrl: '' }]
    }));
  };

  const removeDeliverable = (index: number) => {
    setDeliverableData(prev => ({
      ...prev,
      deliverables: prev.deliverables.filter((_, i) => i !== index)
    }));
  };

  const updateDeliverable = (index: number, field: string, value: string) => {
    setDeliverableData(prev => ({
      ...prev,
      deliverables: prev.deliverables.map((d, i) => 
        i === index ? { ...d, [field]: value } : d
      )
    }));
  };

  const formatBudget = (amount: number, currency: string) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: currency
    }).format(amount);
  };

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

  const getTimeRemaining = (deadline: string) => {
    const now = new Date();
    const deadlineDate = new Date(deadline);
    const timeDiff = deadlineDate.getTime() - now.getTime();
    const daysRemaining = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
    
    if (daysRemaining < 0) {
      return 'Overdue';
    } else if (daysRemaining === 0) {
      return 'Due today';
    } else if (daysRemaining === 1) {
      return '1 day remaining';
    } else {
      return `${daysRemaining} days remaining`;
    }
  };

  if (status === 'loading' || isLoading) {
    return (
      <div className="project-detail-wrapper py-40">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="loading-container">
                <div className="spinner-border" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
                <p>Loading ongoing project details...</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (status === 'unauthenticated') {
    return (
      <div className="project-detail-wrapper py-40">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="error-container">
                <h2>Access Denied</h2>
                <p>Please log in to view this project.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!project) {
    return (
      <div className="project-detail-wrapper py-40">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="error-container">
                <h2>Project Not Found</h2>
                <p>The ongoing project you're looking for doesn't exist or you don't have access to it.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <section className="project-detail-wrapper py-40">
      <div className="container">
        <div className="row">
          <div className="col-12">
            <div className="back-button">
              <a href="/en/freelancer" className="back-link">
                <img src="/assets/image/back-arrow.svg" alt="back to dashboard" />
                Back to Dashboard
              </a>
            </div>
            <div className="page-title">
              <h2>Ongoing Project Details</h2>
            </div>
          </div>
        </div>
        <div className="row">
          <div className="col-md-12 col-lg-3">
            <div className="profile-edit-block">
              <div className="profile-edit-top">
                <div className="profile-img">
                  <img src={project.clientAvatar} className="profile-update-img" alt={project.clientName} />
                </div>
                <h5>{project.clientName}</h5>
                <ul className="pd-contact">
                  <li className="pd-text">
                    <div className="icon">
                      <img src="/assets/image/star-lg.svg" alt="star-lg" />
                    </div>
                    {project.clientRating} ({project.clientReviewsCount}+ Reviews)
                  </li>
                  <li className="pd-text">
                    <div className="icon">
                      <img src="/assets/image/briefcase.svg" alt="briefcase" />
                    </div>
                    {project.clientProjectsCount} Projects Posted
                  </li>
                  <li className="pd-text">
                    <div className="icon">
                      <img src="/assets/image/timer-lg.svg" alt="timer-lg" />
                    </div>
                    Member since {project.clientMemberSince}
                  </li>
                </ul>
              </div>
              <div className="chat-btn">
                <img src="/assets/image/location.svg" alt="" />
                {project.clientLocation}
              </div>
            </div>
          </div>
          <div className="col-md-12 col-lg-9">
            <div className="review-content">
              <div className="pd-tag">
                <ul className="pd-tag0list">
                  <li className="bg-light-sec">
                    <img src="/assets/image/cabinetmaking.svg" alt="category" />
                    <span>{project.category}</span>
                  </li>
                  <li>
                    <img src="/assets/image/calendar.svg" alt="calendar" />
                    <span>{formatDate(project.createdAt)}</span>
                  </li>
                  <li className="status-ongoing">
                    <img src="/assets/image/clock.svg" alt="status" />
                    <span>Ongoing</span>
                  </li>
                </ul>
                <div className="pd-bid">
                  <a href="#" className="share-profile">
                    <svg width="21" height="21" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M15.5 13.8993C14.8667 13.8993 14.3 14.1494 13.8667 14.541L7.925 11.0827C7.96667 10.891 8 10.6993 8 10.4993C8 10.2993 7.96667 10.1077 7.925 9.91602L13.8 6.49102C14.25 6.90768 14.8417 7.16602 15.5 7.16602C16.8833 7.16602 18 6.04935 18 4.66602C18 3.28268 16.8833 2.16602 15.5 2.16602C14.1167 2.16602 13 3.28268 13 4.66602C13 4.86602 13.0333 5.05768 13.075 5.24935L7.2 8.67435C6.75 8.25768 6.15833 7.99935 5.5 7.99935C4.11667 7.99935 3 9.11602 3 10.4993C3 11.8827 4.11667 12.9993 5.5 12.9993C6.15833 12.9993 6.75 12.741 7.2 12.3243L13.1333 15.791C13.0917 15.966 13.0667 16.1493 13.0667 16.3327C13.0667 17.6743 14.1583 18.766 15.5 18.766C16.8417 18.766 17.9333 17.6743 17.9333 16.3327C17.9333 14.991 16.8417 13.8993 15.5 13.8993Z" fill="#EF7310"></path>
                    </svg>
                    Share
                  </a>
                </div>
              </div>
              
              <div className="pd-head">
                <div className="pd-head-titile">
                  <h2>{project.title}</h2>
                  <div className="project-timeline">
                    <div className="timeline-item">
                      <span>Started on</span>
                      <div className="pd-time">
                        <img src="/assets/image/play-circle.svg" alt="play-circle" />
                        {formatDate(project.startedAt)}
                      </div>
                    </div>
                    <div className="timeline-item">
                      <span>Deadline</span>
                      <div className="pd-time deadline">
                        <img src="/assets/image/clock.svg" alt="clock" />
                        {formatDate(project.deadline)}
                        <span className="time-remaining">({getTimeRemaining(project.deadline)})</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="pd-price">
                  {formatBudget(project.budget, project.currency)}
                </div>
              </div>

              {/* Project Progress */}
              <div className="project-progress-section">
                <h3>Project Progress</h3>
                <div className="progress-container">
                  <div className="progress-info">
                    <span className="progress-label">Overall Progress</span>
                    <span className="progress-value">{project.progress}%</span>
                  </div>
                  <div className="progress-bar">
                    <div 
                      className="progress-fill"
                      style={{ width: `${project.progress}%` }}
                    ></div>
                  </div>
                  {project.currentMilestone && (
                    <div className="current-milestone">
                      <span>Current Milestone: </span>
                      <strong>{project.currentMilestone}</strong>
                    </div>
                  )}
                </div>
              </div>

              <div className="pd-discription">
                <h3>About this project</h3>
                <p>{project.description}</p>

                {/* Project Documents */}
                {project.documents && project.documents.length > 0 && (
                  <div className="project-documents">
                    <h3>Project Documents</h3>
                    <div className="documents-list">
                      {project.documents.map((document) => (
                        <div key={document.id} className="document-item">
                          <div className="document-info">
                            <div className="document-icon">
                              <img src="/assets/image/document.svg" alt="document" />
                            </div>
                            <div className="document-details">
                              <h4>{document.name}</h4>
                              <small>
                                Uploaded by {document.uploadedBy} on {formatDate(document.uploadedAt)}
                              </small>
                            </div>
                          </div>
                          <div className="document-actions">
                            <a href={document.url} className="download-btn" target="_blank" rel="noopener noreferrer">
                              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                                <path d="M7 10L12 15L17 10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                                <path d="M12 15V3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                              </svg>
                              Download
                            </a>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Project Milestones */}
                {projectId && (
                  <ProjectMilestones 
                    projectId={projectId} 
                    userRole={project.userRole} 
                    projectStatus="active" 
                  />
                )}

                {/* Project Actions Section - Only for freelancers */}
                {project.userRole === 'freelancer' && (
                  <div className="project-actions-section">
                    {/* Complete Project Section */}
                    <div className="complete-project-section">
                      <div className="section-header">
                        <h3>Ready to Complete the Project?</h3>
                        <p>Submit your deliverables and mark the project as complete.</p>
                      </div>
                      <button 
                        className="custom-btn secondary-btn"
                        onClick={() => setShowDeliverableModal(true)}
                      >
                        Submit Deliverables
                      </button>
                    </div>
                    
                    {/* Update Proposal Section */}
                    <div className="update-proposal-section">
                      <div className="section-header">
                        <h3>Need to Update Project Terms?</h3>
                        <p>Request changes to budget, timeline, or scope with client approval.</p>
                      </div>
                      <button 
                        className="custom-btn primary-btn"
                        onClick={() => setShowUpdateModal(true)}
                      >
                        Request Project Update
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Update Proposal Modal */}
      {showUpdateModal && (
        <div className="modal-overlay" onClick={() => setShowUpdateModal(false)}>
          <div className="modal-content update-proposal-modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h3>Update Project Proposal</h3>
              <button 
                className="close-btn"
                onClick={() => setShowUpdateModal(false)}
              >
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
            </div>
            
            <form onSubmit={handleUpdateProposal}>
              <div className="modal-body">
                <div className="form-wrap mb-3">
                  <label htmlFor="updateBudget" className="form-label">New Budget (Optional)</label>
                  <input 
                    type="number"
                    id="updateBudget"
                    placeholder="Enter new budget amount"
                    value={updateData.budget || ''}
                    onChange={(e) => setUpdateData(prev => ({
                      ...prev,
                      budget: e.target.value ? parseFloat(e.target.value) : undefined
                    }))}
                    disabled={isSubmittingUpdate}
                  />
                </div>

                <div className="form-wrap mb-3">
                  <label htmlFor="updateDeadline" className="form-label">New Deadline (Optional)</label>
                  <input 
                    type="date"
                    id="updateDeadline"
                    value={updateData.deadline || ''}
                    onChange={(e) => setUpdateData(prev => ({
                      ...prev,
                      deadline: e.target.value
                    }))}
                    disabled={isSubmittingUpdate}
                  />
                </div>

                <div className="form-wrap mb-3">
                  <label htmlFor="updateDescription" className="form-label">Updated Description (Optional)</label>
                  <textarea 
                    id="updateDescription"
                    rows={4}
                    placeholder="Describe any changes to project scope or requirements"
                    value={updateData.description || ''}
                    onChange={(e) => setUpdateData(prev => ({
                      ...prev,
                      description: e.target.value
                    }))}
                    disabled={isSubmittingUpdate}
                  />
                </div>

                <div className="form-wrap mb-3">
                  <label htmlFor="updateReason" className="form-label">Reason for Update *</label>
                  <textarea 
                    id="updateReason"
                    rows={3}
                    placeholder="Explain why you need to update the project terms"
                    value={updateData.reason}
                    onChange={(e) => setUpdateData(prev => ({
                      ...prev,
                      reason: e.target.value
                    }))}
                    disabled={isSubmittingUpdate}
                    required
                  />
                </div>
              </div>

              <div className="modal-footer">
                <button 
                  type="button"
                  className="custom-btn secondary-btn"
                  onClick={() => setShowUpdateModal(false)}
                  disabled={isSubmittingUpdate}
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  className="custom-btn primary-btn"
                  disabled={isSubmittingUpdate || !updateData.reason.trim()}
                >
                  {isSubmittingUpdate ? 'Submitting...' : 'Submit Update Request'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Submit Deliverables Modal */}
      {showDeliverableModal && (
        <div className="modal-overlay" onClick={() => setShowDeliverableModal(false)}>
          <div className="modal-content deliverable-modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h3>Submit Project Deliverables</h3>
              <button 
                className="close-btn"
                onClick={() => setShowDeliverableModal(false)}
              >
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
            </div>
            
            <form onSubmit={handleSubmitDeliverables}>
              <div className="modal-body">
                <p className="modal-description">
                  Submit your project deliverables to mark this project as complete. Both you and the client will be able to leave reviews after completion.
                </p>

                {/* Deliverables */}
                <div className="deliverables-section">
                  <div className="section-header">
                    <h4>Project Deliverables</h4>
                    <button 
                      type="button" 
                      className="add-deliverable-btn"
                      onClick={addDeliverable}
                      disabled={isSubmittingDeliverable}
                    >
                      + Add Deliverable
                    </button>
                  </div>
                  
                  {deliverableData.deliverables.map((deliverable, index) => (
                    <div key={index} className="deliverable-item">
                      <div className="deliverable-header">
                        <h5>Deliverable #{index + 1}</h5>
                        {deliverableData.deliverables.length > 1 && (
                          <button 
                            type="button"
                            className="remove-btn"
                            onClick={() => removeDeliverable(index)}
                            disabled={isSubmittingDeliverable}
                          >
                            Remove
                          </button>
                        )}
                      </div>
                      
                      <div className="form-wrap mb-3">
                        <label className="form-label">Name *</label>
                        <input 
                          type="text"
                          placeholder="e.g., Final Website Design"
                          value={deliverable.name}
                          onChange={(e) => updateDeliverable(index, 'name', e.target.value)}
                          disabled={isSubmittingDeliverable}
                          required
                        />
                      </div>
                      
                      <div className="form-wrap mb-3">
                        <label className="form-label">Description *</label>
                        <textarea 
                          rows={3}
                          placeholder="Describe what you're delivering..."
                          value={deliverable.description}
                          onChange={(e) => updateDeliverable(index, 'description', e.target.value)}
                          disabled={isSubmittingDeliverable}
                          required
                        />
                      </div>
                      
                      <div className="form-wrap mb-3">
                        <label className="form-label">File URL *</label>
                        <input 
                          type="url"
                          placeholder="https://... (link to your deliverable file)"
                          value={deliverable.fileUrl}
                          onChange={(e) => updateDeliverable(index, 'fileUrl', e.target.value)}
                          disabled={isSubmittingDeliverable}
                          required
                        />
                      </div>
                    </div>
                  ))}
                </div>

                {/* Completion Note */}
                <div className="form-wrap mb-3">
                  <label className="form-label">Completion Note (Optional)</label>
                  <textarea 
                    rows={3}
                    placeholder="Add any final notes about the project completion..."
                    value={deliverableData.completionNote}
                    onChange={(e) => setDeliverableData(prev => ({
                      ...prev,
                      completionNote: e.target.value
                    }))}
                    disabled={isSubmittingDeliverable}
                  />
                </div>
              </div>

              <div className="modal-footer">
                <button 
                  type="button"
                  className="custom-btn secondary-btn"
                  onClick={() => setShowDeliverableModal(false)}
                  disabled={isSubmittingDeliverable}
                >
                  Cancel
                </button>
                <button 
                  type="submit"
                  className="custom-btn primary-btn"
                  disabled={isSubmittingDeliverable}
                >
                  {isSubmittingDeliverable ? 'Submitting...' : 'Complete Project'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </section>
  );
}