'use client';

import { useState, useEffect, use } from 'react';
import { useSession } from 'next-auth/react';
import { useToast } from '@/components/ui/ToastContext';
import { useFreelancerProfile } from '@/hooks/useFreelancerProfile';
import ProjectTimeline from '@/components/project/ProjectTimeline';
import FreelancerLayout from '@/components/layout/FreelancerLayout';
import './cancelled-project-details.css';

interface CancelledProjectDetails {
  id: string;
  title: string;
  description: string;
  status: 'cancelled';
  budget: number;
  currency: string;
  deadline: string;
  createdAt: string;
  cancelledAt: string;
  cancelledBy: 'freelancer' | 'client' | 'admin';
  cancellationReason: string;
  refundAmount?: number;
  refundStatus: 'pending' | 'processed' | 'rejected' | 'not_applicable';
  freelancerId: string;
  clientId: string;
  freelancerName: string;
  clientName: string;
  clientAvatar: string;
  clientRating: number;
  clientReviewsCount: number;
  clientProjectsCount: number;
  clientMemberSince: string;
  clientLocation: string;
  category: string;
  bidsCount: number;
  workDuration: string;
  documentsCount: number;
  projectDocuments: Array<{
    id: string;
    name: string;
    type: string;
    size: string;
    url: string;
  }>;
}

interface CancelledProjectDetailsPageProps {
  params: Promise<{
    locale: string;
    projectId: string;
  }>;
}

export default function CancelledProjectDetailsPage({ params }: CancelledProjectDetailsPageProps) {
  const { locale, projectId: paramProjectId } = use(params);
  const { data: session, status } = useSession();
  const { showError } = useToast();
  const { profile } = useFreelancerProfile();
  
  const [project, setProject] = useState<CancelledProjectDetails | null>(null);
  const [isLoading, setIsLoading] = useState(true);

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

  const fetchProjectDetails = async () => {
    try {
      setIsLoading(true);
      const response = await fetch(`/api/projects/cancelled/${paramProjectId}`);
      
      if (!response.ok) {
        throw new Error('Failed to fetch cancelled 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 cancelled project details:', error);
      showError(error.message || 'Failed to load project details');
    } finally {
      setIsLoading(false);
    }
  };

  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',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const getDocumentIcon = (type: string) => {
    switch (type.toLowerCase()) {
      case 'pdf':
        return '/assets/image/pdf.svg';
      case 'svg':
        return '/assets/image/svg.svg';
      case 'png':
      case 'jpg':
      case 'jpeg':
        return '/assets/image/png.svg';
      case 'mp4':
      case 'avi':
        return '/assets/image/vid.svg';
      default:
        return '/assets/image/pdf.svg';
    }
  };

  const getRefundStatusColor = (status: string) => {
    switch (status) {
      case 'processed': return '#22c55e';
      case 'pending': return '#f59e0b';
      case 'rejected': return '#ef4444';
      default: return '#6b7280';
    }
  };

  const getCancellationReasonDisplay = (reason: string) => {
    const reasons: { [key: string]: string } = {
      'client_request': 'Cancelled by client request',
      'freelancer_unavailable': 'Freelancer became unavailable',
      'scope_change': 'Project scope changed significantly',
      'payment_issues': 'Payment processing issues',
      'quality_concerns': 'Quality concerns raised',
      'deadline_missed': 'Deadline could not be met',
      'mutual_agreement': 'Mutual agreement to cancel',
      'platform_violation': 'Platform policy violation',
      'other': 'Other reasons'
    };
    return reasons[reason] || reason;
  };

  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 cancelled 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 cancelled project you're looking for doesn't exist or you don't have access to it.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <FreelancerLayout 
      locale={locale}
      userProfile={profile ? {
        name: `${profile.firstName} ${profile.lastName}`,
        profileImage: profile.profileImage || "/assets/image/profile03.png",
        rating: profile.rating || 4.5,
        reviewCount: profile.reviewCount || 0
      } : {
        name: session?.user?.name || 'User',
        profileImage: session?.user?.image || "/assets/image/profile03.png",
        rating: 4.5,
        reviewCount: 0
      }}
      unreadMessagesCount={0}
    >
      <div className="project-detail-wrapper">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="page-title">
                <h2>Cancelled 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/noto_fire.svg" alt="bids" />
                    <span>{project.bidsCount} Bids</span>
                  </li>
                  <li>
                    <img src="/assets/image/timer.svg" alt="timer" />
                    <span>Work duration- {project.workDuration}</span>
                  </li>
                  <li>
                    <img src="/assets/image/document-text.svg" alt="documents" />
                    <span>{project.documentsCount} Documents</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="pd-time">
                    <img src="/assets/image/calendar.svg" alt="calendar" />
                    {formatDate(project.createdAt)}
                  </div>
                  <div className="d-flex deal-price-outer gap-3">
                    <span className="custom-btn red-outline">
                      Cancelled
                    </span>
                  </div>
                </div>
                <div className="pd-price">
                  {formatBudget(project.budget, project.currency)}
                </div>
              </div>

              {/* Cancellation Information */}
              <div className="cancellation-info">
                <h3>Cancellation Details</h3>
                <div className="cancellation-details">
                  <div className="cancellation-item">
                    <span className="label">Cancelled on:</span>
                    <span className="value">{formatDate(project.cancelledAt)}</span>
                  </div>
                  <div className="cancellation-item">
                    <span className="label">Cancelled by:</span>
                    <span className="value">{project.cancelledBy.charAt(0).toUpperCase() + project.cancelledBy.slice(1)}</span>
                  </div>
                  <div className="cancellation-item">
                    <span className="label">Reason:</span>
                    <span className="value">{getCancellationReasonDisplay(project.cancellationReason)}</span>
                  </div>
                  {project.refundAmount && (
                    <>
                      <div className="cancellation-item">
                        <span className="label">Refund Amount:</span>
                        <span className="value">{formatBudget(project.refundAmount, project.currency)}</span>
                      </div>
                      <div className="cancellation-item">
                        <span className="label">Refund Status:</span>
                        <span 
                          className="value"
                          style={{ 
                            color: getRefundStatusColor(project.refundStatus),
                            fontWeight: '600'
                          }}
                        >
                          {project.refundStatus.charAt(0).toUpperCase() + project.refundStatus.slice(1).replace('_', ' ')}
                        </span>
                      </div>
                    </>
                  )}
                </div>
              </div>

              <div className="pd-discription">
                <h3>About this project</h3>
                <p>{project.description}</p>
                
                <h3>Documents ({project.documentsCount})</h3>
                <div className="document-wrapper">
                  <div className="doc-grid">
                    {project.projectDocuments.map((doc) => (
                      <div key={doc.id} className={`doc-card ${doc.type.toLowerCase()}`}>
                        <div className="doc-left">
                          <div className="icon-box">
                            <img src={getDocumentIcon(doc.type)} alt={doc.type} />
                          </div>
                          <div className="doc-text">
                            <div className="filename">{doc.name}</div>
                            <div className="size">{doc.size}</div>
                          </div>
                        </div>
                        <div className="download-arrow">
                          <svg width="19" height="18" viewBox="0 0 19 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M10.0294 16.9298C9.89508 17.0642 9.71123 17.149 9.4991 17.149C9.08898 17.149 8.74957 16.8096 8.74957 16.3995V-1.39949C8.74957 -1.80962 9.08898 -2.14903 9.4991 -2.14903C9.90922 -2.14903 10.2486 -1.80962 10.2486 -1.39949L10.2486 16.3995C10.2486 16.6116 10.1638 16.7955 10.0294 16.9298Z" fill="#EF7310"/>
                            <path d="M17.2912 9.66705L10.0292 16.929C9.73933 17.2189 9.2585 17.2189 8.96859 16.929L1.7066 9.66705C1.41669 9.37714 1.41669 8.8963 1.7066 8.60639C1.99651 8.31647 2.47735 8.31647 2.76726 8.60639L9.49892 15.338L16.2306 8.60639C16.5205 8.31648 17.0013 8.31648 17.2912 8.60639C17.5811 8.8963 17.5811 9.37714 17.2912 9.66705Z" fill="#EF7310"/>
                          </svg>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              {/* Project Timeline */}
              {paramProjectId && <ProjectTimeline projectId={paramProjectId} showCancellationEvents={true} />}
            </div>
            </div>
          </div>
        </div>
      </div>
    </FreelancerLayout>
  );
}