'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import Image from 'next/image';
import Link from 'next/link';
import { useToast } from '@/components/ui/ToastContext';

interface ProjectDetails {
  id: string;
  title: string;
  description: string;
  budget: number;
  currency: string;
  deadline: string;
  createdAt: string;
  status: string;
  category: string;
  bidCount: number;
  documentCount: number;
  workDuration: string;
  client: {
    id: string;
    name: string;
    avatar: string;
    rating: number;
    reviewsCount: number;
    projectsPosted: number;
    memberSince: string;
    location: string;
  };
  freelancerBid?: {
    id: string;
    amount: number;
    duration: string;
    proposal: string;
    status: string;
  };
  documents?: Array<{
    id: string;
    name: string;
    size: string;
    type: string;
    url: string;
  }>;
}

interface UpdateProposalForm {
  price: number;
  duration: string;
  description: string;
}

export default function FreelancerProjectDetailsPage() {
  const params = useParams();
  const router = useRouter();
  const { data: session } = useSession();
  const [project, setProject] = useState<ProjectDetails | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [showUpdateModal, setShowUpdateModal] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string>('');
  const [success, setSuccess] = useState<string>('');
  
  const [updateForm, setUpdateForm] = useState<UpdateProposalForm>({
    price: 0,
    duration: '',
    description: ''
  });

  const projectId = params.projectId as string;
  const locale = params.locale as string;
  const { showInfo } = useToast();

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

  const fetchProjectDetails = async () => {
    try {
      const [projectResponse, documentsResponse, bidResponse] = await Promise.all([
        fetch(`/api/projects/${projectId}/details`),
        fetch(`/api/projects/${projectId}/documents`),
        fetch(`/api/projects/${projectId}/my-bid`)
      ]);
      
      if (!projectResponse.ok) {
        throw new Error('Failed to fetch project details');
      }

      const projectData = await projectResponse.json();
      const documentsData = documentsResponse.ok ? await documentsResponse.json() : { success: false, data: [] };
      const bidData = bidResponse.ok ? await bidResponse.json() : { success: false };
      
      if (projectData.success) {
        const project = projectData.data;
        const documents = documentsData.success ? documentsData.data : [];
        const freelancerBid = bidData.success ? bidData.data : null;
        
        // Transform API data to match our interface
        const transformedProject: ProjectDetails = {
          id: project.id,
          title: project.title,
          description: project.description,
          budget: project.budget,
          currency: project.currency || 'EUR',
          deadline: project.deadline,
          createdAt: project.createdAt,
          status: project.status,
          category: 'Cabinetmaking / Carpentary', // Mock data - could be added to API
          bidCount: 4, // Mock data - could be added to API
          documentCount: documents.length,
          workDuration: '15 days', // Mock data - could be calculated from deadline
          client: {
            id: project.client?.id || project.clientId,
            name: project.client?.name || project.clientName,
            avatar: project.client?.avatar || project.clientAvatar,
            rating: project.client?.rating || 4.5,
            reviewsCount: project.client?.reviewsCount || 25,
            projectsPosted: 32, // Mock data
            memberSince: project.client?.joinedDate || '2024-05-21',
            location: 'Zurich, Switzerland' // Mock data
          },
          freelancerBid: freelancerBid ? {
            id: freelancerBid.id,
            amount: freelancerBid.amount,
            duration: freelancerBid.duration,
            proposal: freelancerBid.proposal,
            status: freelancerBid.status.toLowerCase()
          } : undefined,
          documents: documents.map((doc: any) => ({
            id: doc.id,
            name: doc.name,
            size: doc.size,
            type: doc.type,
            url: doc.url
          }))
        };
        
        setProject(transformedProject);
        setUpdateForm({
          price: transformedProject.freelancerBid?.amount || transformedProject.budget,
          duration: transformedProject.freelancerBid?.duration || '5 days',
          description: transformedProject.freelancerBid?.proposal || ''
        });
      } else {
        setError(projectData.error || 'Failed to load project details');
      }
    } catch (error) {
      console.error('Error fetching project details:', error);
      setError('Failed to load project details');
    } finally {
      setIsLoading(false);
    }
  };

  const handleUpdateProposal = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!updateForm.price || updateForm.price <= 0) {
      setError('Please enter a valid price');
      return;
    }
    
    if (!updateForm.duration.trim()) {
      setError('Please enter the duration');
      return;
    }
    
    if (!updateForm.description.trim() || updateForm.description.trim().length < 10) {
      setError('Please provide a description of at least 10 characters');
      return;
    }

    setIsSubmitting(true);
    setError('');

    try {
      const response = await fetch(`/api/projects/${projectId}/update-proposal`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          budget: updateForm.price,
          deadline: updateForm.duration,
          description: updateForm.description.trim(),
          reason: 'Proposal update request from project details page'
        })
      });

      const data = await response.json();

      if (data.success) {
        setSuccess('Proposal update request submitted successfully!');
        setShowUpdateModal(false);
        setTimeout(() => {
          setSuccess('');
        }, 3000);
      } else {
        setError(data.error || 'Failed to submit proposal update');
      }
    } catch (error) {
      console.error('Error updating proposal:', error);
      setError('Failed to submit proposal update. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  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) {
      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 'video':
      case 'mp4':
        return '/assets/image/vid.svg';
      default:
        return '/assets/image/document-text.svg';
    }
  };

  const handleDocumentDownload = (document: any) => {
    showInfo(`Downloading ${document.name}`, 'Download');
    // In a real implementation, this would handle secure document download
    // Example download logic could be added here
  };

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

  if (!project) {
    return (
      <section className="project-detail-wrapper py-40">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="error-container text-center">
                <h3>Project Not Found</h3>
                <p>The project you're looking for doesn't exist or you don't have access to it.</p>
                <Link href={`/${locale}/freelancer/my-projects`} className="btn btn-primary">
                  Back to My Projects
                </Link>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <>
      <section className="project-detail-wrapper py-40">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="back-button">
                <Link href={`/${locale}/freelancer/my-projects`} className="back-link">
                  <Image 
                    src="/assets/image/back-arrow.svg" 
                    alt="back to dashboard"
                    width={16}
                    height={16}
                  />
                  Back to Dashboard
                </Link>
              </div>
              <div className="page-title">
                <h2>Project Detail</h2>
              </div>
            </div>
          </div>

          <div className="row">
            {/* Client Profile Sidebar */}
            <div className="col-md-12 col-lg-3">
              <div className="profile-edit-block">
                <div className="profile-edit-top">
                  <div className="profile-img">
                    <Image 
                      src={project.client.avatar} 
                      className="profile-update-img" 
                      alt="client avatar"
                      width={80}
                      height={80}
                    />
                  </div>
                  <h5>{project.client.name}</h5>
                  <ul className="pd-contact">
                    <li className="pd-text">
                      <div className="icon">
                        <Image src="/assets/image/star-lg.svg" alt="star" width={16} height={16} />
                      </div>
                      {project.client.rating} ({project.client.reviewsCount}+ Reviews)
                    </li>
                    <li className="pd-text">
                      <div className="icon">
                        <Image src="/assets/image/briefcase.svg" alt="briefcase" width={16} height={16} />
                      </div>
                      {project.client.projectsPosted} Projects Posted
                    </li>
                    <li className="pd-text">
                      <div className="icon">
                        <Image src="/assets/image/timer-lg.svg" alt="timer" width={16} height={16} />
                      </div>
                      Member since {new Date(project.client.memberSince).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}
                    </li>
                  </ul>
                </div>
                <div className="chat-btn">
                  <Image src="/assets/image/location.svg" alt="location" width={16} height={16} />
                  {project.client.location}
                </div>
              </div>
            </div>

            {/* Project Details */}
            <div className="col-md-12 col-lg-9">
              <div className="review-content">
                {/* Success/Error Messages */}
                {success && (
                  <div className="alert alert-success mb-3">
                    {success}
                  </div>
                )}
                {error && (
                  <div className="alert alert-danger mb-3">
                    {error}
                  </div>
                )}

                {/* Project Tags */}
                <div className="pd-tag">
                  <ul className="pd-tag0list">
                    <li className="bg-light-sec">
                      <Image src="/assets/image/cabinetmaking.svg" alt="category" width={20} height={20} />
                      <span>{project.category}</span>
                    </li>
                    <li>
                      <Image src="/assets/image/noto_fire.svg" alt="bids" width={20} height={20} />
                      <span>{project.bidCount} Bids</span>
                    </li>
                    <li>
                      <Image src="/assets/image/timer.svg" alt="duration" width={20} height={20} />
                      <span>Work duration- {project.workDuration}</span>
                    </li>
                    <li>
                      <Image src="/assets/image/document-text.svg" alt="documents" width={20} height={20} />
                      <span>{project.documentCount} 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"/>
                      </svg>
                      Share
                    </a>
                  </div>
                </div>

                {/* Project Header */}
                <div className="pd-head">
                  <div className="pd-head-titile">
                    <h2>{project.title}</h2>
                    <div className="pd-time">
                      <Image src="/assets/image/calendar.svg" alt="calendar" width={16} height={16} />
                      {formatDate(project.createdAt)}
                    </div>
                    <div className="d-flex">
                      <button 
                        onClick={() => setShowUpdateModal(true)}
                        className="custom-btn primary-outline"
                      >
                        <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M8.5 12H16.5" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                          <path d="M12.5 16V8" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                          <path d="M9.5 22H15.5C20.5 22 22.5 20 22.5 15V9C22.5 4 20.5 2 15.5 2H9.5C4.5 2 2.5 4 2.5 9V15C2.5 20 4.5 22 9.5 22Z" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                        Bid
                      </button>
                    </div>
                  </div>
                  <div className="pd-price">
                    {project.currency} {project.budget.toLocaleString()}
                  </div>
                </div>

                {/* Project Description */}
                <div className="pd-discription">
                  <h3>About this project</h3>
                  <div dangerouslySetInnerHTML={{ __html: project.description }} />
                  
                  {/* Documents Section */}
                  {project.documents && project.documents.length > 0 && (
                    <>
                      <h3>Documents ({project.documents.length})</h3>
                      <div className="document-wrapper">
                        <div className="doc-grid">
                          {project.documents.map((doc) => (
                            <div key={doc.id} className={`doc-card ${doc.type}`}>
                              <div className="doc-left">
                                <div className="icon-box">
                                  <Image 
                                    src={getDocumentIcon(doc.type)} 
                                    alt={doc.type}
                                    width={24}
                                    height={24}
                                  />
                                </div>
                                <div className="doc-text">
                                  <div className="filename">{doc.name}</div>
                                  <div className="size">{doc.size}</div>
                                </div>
                              </div>
                              <div className="download-arrow" onClick={() => handleDocumentDownload(doc)}>
                                <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>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Update Proposal Modal */}
      {showUpdateModal && (
        <div className="modal fade show custom-modal" style={{ display: 'block', backgroundColor: 'rgba(0,0,0,0.5)' }}>
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content">
              <div className="tab-title">
                <h5>Update Proposal</h5>
                <button 
                  type="button" 
                  className="btn-close" 
                  onClick={() => setShowUpdateModal(false)}
                  aria-label="Close"
                />
              </div>
              <form onSubmit={handleUpdateProposal}>
                <div className="form-group">
                  <div className="mb-20">
                    <label htmlFor="price" className="form-label">Price <span className='text-danger'>*</span></label>
                    <div className="input-icon">
                      <input 
                        type="number" 
                        className="form-control" 
                        name="price" 
                        id="price" 
                        placeholder="Enter Price"
                        value={updateForm.price}
                        onChange={(e) => setUpdateForm(prev => ({ ...prev, price: parseFloat(e.target.value) || 0 }))}
                        disabled={isSubmitting}
                        required
                      />
                    </div>
                  </div>
                  <div className="mb-20">
                    <label htmlFor="days" className="form-label">Days needed to complete the work</label>
                    <div className="input-icon">
                      <input 
                        type="text" 
                        className="form-control" 
                        name="days" 
                        id="days" 
                        placeholder="Enter Days"
                        value={updateForm.duration}
                        onChange={(e) => setUpdateForm(prev => ({ ...prev, duration: e.target.value }))}
                        disabled={isSubmitting}
                        required
                      />
                    </div>
                  </div>
                </div>

                <div className="form-group">
                  <div className="mb-20">
                    <label htmlFor="description" className="form-label">Description</label>
                    <div className="input-icon">
                      <textarea 
                        className="form-control" 
                        id="description"
                        name="description"
                        placeholder="Describe your updated proposal..."
                        value={updateForm.description}
                        onChange={(e) => setUpdateForm(prev => ({ ...prev, description: e.target.value }))}
                        disabled={isSubmitting}
                        rows={4}
                        required
                      />
                    </div>
                  </div>
                </div>
                
                <div className="pop-dis">
                  <p>
                    Please read in full and understand the client's requirements. A well written and fully understood proposal is key to winning the work.
                  </p>
                </div>
                
                <button 
                  type="submit" 
                  className="w-100 custom-btn secondary-btn"
                  disabled={isSubmitting}
                >
                  {isSubmitting ? 'Saving...' : 'Save'}
                </button>
              </form>
            </div>
          </div>
        </div>
      )}

      <style jsx>{`
        .loading-container, .error-container {
          padding: 60px 20px;
        }

        .alert {
          padding: 12px 16px;
          border-radius: 8px;
          margin-bottom: 20px;
        }

        .alert-danger {
          background-color: #f8d7da;
          border: 1px solid #f5c6cb;
          color: #721c24;
        }

        .alert-success {
          background-color: #d1edff;
          border: 1px solid #bee5eb;
          color: #0c5460;
        }

        .back-link {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          color: var(--color-primary);
          text-decoration: none;
          font-weight: 500;
          margin-bottom: 20px;
        }

        .back-link:hover {
          color: var(--color-primary-dark);
        }

        .modal.show {
          animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }

        .doc-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 16px;
          margin-top: 20px;
        }

        .doc-card {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 16px;
          border: 1px solid var(--border-plight);
          border-radius: 10px;
          background: white;
          transition: 0.2s ease;
        }

        .doc-card:hover {
          box-shadow: 0 4px 10px rgba(0,0,0,0.05);
        }

        .doc-left {
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .icon-box {
          width: 40px;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 4px;
          background: #ffe5db;
        }

        .filename {
          font-weight: 600;
          color: var(--text-color);
          margin-bottom: 4px;
        }

        .size {
          font-size: 12px;
          font-weight: 400;
          color: #787676;
        }

        .download-arrow {
          cursor: pointer;
          color: #f58220;
          font-size: 18px;
        }

        .doc-card.pdf .icon-box { background: #FEE2E2; }
        .doc-card.img .icon-box { background: #FCE3CF; }
        .doc-card.vid .icon-box { background: #E5E2FE; }
        .doc-card.svg .icon-box { background: #E2EEFE; }

        @media (max-width: 768px) {
          .doc-grid {
            grid-template-columns: 1fr;
          }
          
          .d-flex {
            flex-direction: column;
            gap: 15px !important;
          }
        }
      `}</style>
    </>
  );
}