'use client';

import { useState, useEffect, use } from 'react';
import { useSession } from 'next-auth/react';
import { useToast } from '@/components/ui/ToastContext';
import AddExperienceModal from '@/components/AddExperienceModal';
import FreelancerLayout from '@/components/layout/FreelancerLayout';

interface ExperienceDocument {
  id: string;
  filename: string;
  fileUrl: string;
  fileSize: string;
  fileType: string;
}

interface Experience {
  id: string;
  title: string;
  company: string;
  location: string;
  startDate: string;
  endDate?: string;
  isCurrent: boolean;
  description: string;
  documents: ExperienceDocument[];
  createdAt: string;
  updatedAt: string;
}

interface ProfileData {
  id: string;
  firstName: string;
  lastName: string;
  profileImage: string;
  profileCompletion: number;
  rating: number;
  reviewCount: number;
}

interface AddExperiencePageProps {
  params: Promise<{
    locale: string;
  }>;
}

export default function AddExperiencePage({ params }: AddExperiencePageProps) {
  const { locale } = use(params);
  const { data: session, status } = useSession();
  const { showError, showSuccess } = useToast();
  
  const [profile, setProfile] = useState<ProfileData | null>(null);
  const [experiences, setExperiences] = useState<Experience[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingExperience, setEditingExperience] = useState<Experience | null>(null);

  // Fetch profile data
  useEffect(() => {
    if (status === 'authenticated') {
      fetchProfile();
      fetchExperiences();
    }
  }, [status]);

  const fetchProfile = async () => {
    try {
      const response = await fetch('/api/freelancer/profile', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

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

      const data = await response.json();
      if (data.success) {
        setProfile(data.data);
      } else {
        throw new Error(data.error || 'Failed to fetch profile');
      }
    } catch (error: any) {
      console.error('Error fetching profile:', error);
      showError(error.message || 'Failed to load profile');
    }
  };

  const fetchExperiences = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/freelancer/experiences', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

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

      const data = await response.json();
      if (data.success) {
        setExperiences(data.data || []);
      } else {
        throw new Error(data.error || 'Failed to fetch experiences');
      }
    } catch (error: any) {
      console.error('Error fetching experiences:', error);
      showError(error.message || 'Failed to load experiences');
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddExperience = () => {
    setEditingExperience(null);
    setIsModalOpen(true);
  };

  const handleEditExperience = (experience: Experience) => {
    setEditingExperience(experience);
    setIsModalOpen(true);
  };

  const handleDeleteExperience = async (id: string) => {
    if (!confirm('Are you sure you want to delete this experience?')) {
      return;
    }

    try {
      const response = await fetch(`/api/freelancer/experiences/${id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
        },
      });

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

      const data = await response.json();
      if (data.success) {
        showSuccess('Experience deleted successfully');
        fetchExperiences();
      } else {
        throw new Error(data.error || 'Failed to delete experience');
      }
    } catch (error: any) {
      console.error('Error deleting experience:', error);
      showError(error.message || 'Failed to delete experience');
    }
  };

  const handleExperienceUpdated = () => {
    fetchExperiences();
    setIsModalOpen(false);
    setEditingExperience(null);
  };

  const handleDownloadDocument = (doc: ExperienceDocument) => {
    // Create a temporary link to download the file
    const link = document.createElement('a');
    link.href = doc.fileUrl;
    link.download = doc.filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  if (status === 'loading' || isLoading) {
    return (
      <div className="profile-wrapper">
        <div className="container-fluid">
          <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 experience data...</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (status === 'unauthenticated') {
    return (
      <div className="profile-wrapper">
        <div className="container-fluid">
          <div className="row">
            <div className="col-12">
              <div className="error-container">
                <h2>Access Denied</h2>
                <p>Please log in to view your experience page.</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
      } : undefined}
      unreadMessagesCount={0}
    >
      <div className="content-box">
        {/* Welcome Header */}
        <div className="welcome-head">
          <div className="welcome-left">
            <div className="progress-container">
              <div className="progress-circle">
                <svg width="56" height="56">
                  <circle cx="28" cy="28" r="24" className="bg" />
                  <circle 
                    cx="28" 
                    cy="28" 
                    r="24" 
                    className="progress"
                    style={{
                      strokeDasharray: `${2 * Math.PI * 24}`,
                      strokeDashoffset: `${2 * Math.PI * 24 - (profile?.profileCompletion || 0) / 100 * 2 * Math.PI * 24}`
                    }}
                  />
                </svg>
                <div className="percentage">{profile?.profileCompletion || 0}%</div>
              </div>
            </div>
            <div className="welcome-content">
              <h6>Hi {profile?.firstName || 'User'}! Please complete your profile.</h6>
              <p>Let's spend a few minutes optimizing your profile to maximize opportunities.</p>
            </div>
          </div>
          <div className="welcome-img">
            <img src="/assets/image/profile-bg.png" alt="profile-bg" />
          </div>
        </div>

        {/* Experience Content */}
              <div className="content-box-inner">
                <div className="tab-title">
                  <h5>Add Experience</h5>
                </div>
                
                <div className="form-wrap">
                  <div className="d-flex mb-4">
                    <button 
                      className="custom-btn secondary-btn"
                      onClick={handleAddExperience}
                    >
                      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M8 12H16" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                        <path d="M12 16V8" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                        <path d="M9 22H15C20 22 22 20 22 15V9C22 4 20 2 15 2H9C4 2 2 4 2 9V15C2 20 4 22 9 22Z" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                      Add Experience
                    </button>
                  </div>

                  {/* Experience Cards */}
                  <div className="work-exp-outer">
                    {experiences.length === 0 ? (
                      <div className="empty-state">
                        <p>No experience entries yet. Click "Add Experience" to get started.</p>
                      </div>
                    ) : (
                      experiences.map((experience) => (
                        <div key={experience.id} className="work-exp-card">
                          <div className="work-exp-title">
                            <div className="work-exp-left">
                              <h4>{experience.title}</h4>
                              <div className="work-company">{experience.company}</div>
                              <div className="work-location">{experience.location}</div>
                              <div className="work-dates">
                                {new Date(experience.startDate).toLocaleDateString()} - {' '}
                                {experience.isCurrent ? 'Present' : new Date(experience.endDate!).toLocaleDateString()}
                              </div>
                            </div>
                            <div className="work-exp-action">
                              <button onClick={() => handleEditExperience(experience)}>
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                  <path d="M15.8711 1.92676C16.7555 1.9018 17.7106 2.31238 18.7383 3.2832C19.7658 4.2539 20.2298 5.18401 20.2549 6.06836C20.2799 6.95285 19.8693 7.90881 18.8984 8.93652L10.6885 17.626L10.6865 17.6279C10.3413 17.9978 9.66107 18.3643 9.16113 18.4463H9.1582L5.96484 18.9922C5.7638 19.0049 5.68089 19.0195 5.54199 19.0195C5.04466 19.0195 4.60307 18.8487 4.29688 18.5576L4.29492 18.5557L4.15723 18.4082C3.85618 18.042 3.70335 17.5277 3.76855 16.9463L4.13867 13.707C4.16608 13.4682 4.25683 13.1648 4.39551 12.8662C4.53449 12.567 4.70502 12.3066 4.86914 12.1387L4.875 12.1328L13.085 3.44336C14.0558 2.41572 14.9867 1.95173 15.8711 1.92676ZM15.9316 2.40918C14.9418 2.4093 14.145 3.02885 13.4482 3.7666L5.24023 12.4648C5.08559 12.6272 4.95016 12.8613 4.85352 13.0684C4.75603 13.2773 4.66639 13.5262 4.63672 13.7412L4.63477 13.7529L4.26562 16.9893C4.21284 17.4247 4.3101 17.8722 4.63867 18.1826C4.96941 18.495 5.41696 18.5578 5.83691 18.4941L5.8457 18.4922L9.06641 17.9424C9.28781 17.9042 9.53518 17.7982 9.7373 17.6895C9.93972 17.5806 10.1624 17.4341 10.3145 17.2744L10.3154 17.2725L18.5254 8.58301L18.5264 8.58203C19.1613 7.90613 19.6927 7.1597 19.7451 6.29199C19.7991 5.39684 19.3389 4.53186 18.3838 3.63477C17.54 2.82394 16.7331 2.40918 15.9316 2.40918Z" fill="#292D32" stroke="#EF7310"/>
                                  <path d="M11.8691 4.80469C11.9867 4.79043 12.1003 4.85875 12.1436 4.97266L12.1572 5.02539C12.562 7.58322 14.5836 9.56862 17.1328 9.92871L17.3818 9.95801C17.5103 9.97054 17.6112 10.0881 17.6025 10.2236C17.5813 10.3525 17.4653 10.451 17.3408 10.4512H17.3037C14.419 10.1572 12.1011 7.96522 11.6553 5.09863C11.6355 4.96349 11.7254 4.83208 11.8691 4.80469Z" fill="#292D32" stroke="#EF7310"/>
                                  <path d="M3 21.75H21C21.1339 21.75 21.25 21.8661 21.25 22C21.25 22.1339 21.1339 22.25 21 22.25H3C2.86614 22.25 2.75 22.1339 2.75 22C2.75 21.8661 2.86614 21.75 3 21.75Z" fill="#292D32" stroke="#EF7310"/>
                                </svg>
                              </button>
                              <button onClick={() => handleDeleteExperience(experience.id)}>
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                  <path d="M5.00977 5.52832C10.2843 4.99294 15.6384 5.20028 21.0205 5.72852H21.0215C21.1525 5.74152 21.2558 5.86294 21.2422 6.00195L21.2412 6.01172C21.232 6.13158 21.1283 6.2303 21 6.23047H20.9395C15.9721 5.73396 10.9988 5.52595 6.05859 5.94141L5.06934 6.0332L3.03125 6.23242C2.88131 6.2462 2.76036 6.14246 2.74707 6.00293C2.7332 5.85645 2.83364 5.74185 2.96777 5.72852H2.96875L5.00879 5.52832H5.00977Z" fill="#EF7310" stroke="#EF7310"/>
                                  <path d="M10.6904 1.75H13.3105C14.3764 1.75 14.8508 2.05874 15.0957 2.36621C15.3683 2.70864 15.4493 3.152 15.5273 3.63086V3.63379L15.748 4.93359V4.93457C15.7719 5.0755 15.6723 5.19845 15.5566 5.21582L15.5469 5.2168C15.4058 5.24089 15.283 5.1412 15.2656 5.02539L15.2637 5.0166L15.0439 3.7168H15.043C15.0098 3.51085 14.978 3.30599 14.9297 3.13477C14.8793 2.95649 14.797 2.7561 14.627 2.59277C14.4542 2.42696 14.2433 2.34965 14.0342 2.30957C13.8313 2.27071 13.591 2.25977 13.3203 2.25977H10.7012C10.4334 2.25977 10.1956 2.26858 9.99609 2.30371C9.79093 2.33989 9.57785 2.4119 9.40234 2.57617C9.22937 2.73819 9.1473 2.93914 9.09668 3.11621C9.04798 3.28657 9.0139 3.4931 8.97852 3.70312L8.74805 5.00293L8.74707 5.00977C8.72726 5.13194 8.62141 5.21961 8.50098 5.21973H8.46875L8.45703 5.21777L8.40918 5.2041C8.30207 5.1609 8.23446 5.04324 8.25293 4.93652L8.25391 4.93262L8.47363 3.62305V3.62207C8.557 3.12189 8.63979 2.68382 8.91016 2.34961C9.15284 2.04978 9.62428 1.75006 10.6904 1.75Z" fill="#EF7310" stroke="#EF7310"/>
                                  <path d="M18.8662 8.88867C19.0115 8.90051 19.111 9.02163 19.1016 9.1543V9.15723L18.4512 19.2246C18.3941 20.0338 18.3301 20.7559 17.9414 21.2988C17.5857 21.7956 16.8659 22.25 15.21 22.25H8.79004C7.13443 22.2499 6.41529 21.7956 6.05957 21.2988C5.67138 20.7566 5.60584 20.0356 5.54883 19.2275H5.5498L4.89941 9.15723V9.15332L4.90039 9.10547C4.91606 8.99755 5.00983 8.89964 5.13281 8.88867C5.28164 8.88579 5.39158 8.99314 5.40137 9.12598L6.05176 19.1914V19.1953C6.07853 19.5652 6.1033 19.9197 6.16211 20.2227C6.22193 20.5308 6.3259 20.8405 6.54785 21.0996C6.99616 21.6226 7.75515 21.75 8.79004 21.75H15.21C16.249 21.75 17.0113 21.623 17.46 21.0996C17.6826 20.8398 17.7862 20.5295 17.8447 20.2207C17.9022 19.9172 17.9249 19.5625 17.9492 19.1924V19.1914L18.5986 9.12109C18.6106 8.99437 18.726 8.8869 18.8662 8.88867Z" fill="#EF7310" stroke="#EF7310"/>
                                  <path d="M13.6581 17.25H10.3281C9.91813 17.25 9.57812 16.91 9.57812 16.5C9.57812 16.09 9.91813 15.75 10.3281 15.75H13.6581C14.0681 15.75 14.4081 16.09 14.4081 16.5C14.4081 16.91 14.0681 17.25 13.6581 17.25Z" fill="#EF7310"/>
                                  <path d="M14.5 13.25H9.5C9.09 13.25 8.75 12.91 8.75 12.5C8.75 12.09 9.09 11.75 9.5 11.75H14.5C14.91 11.75 15.25 12.09 15.25 12.5C15.25 12.91 14.91 13.25 14.5 13.25Z" fill="#EF7310"/>
                                </svg>
                              </button>
                            </div>
                          </div>
                          
                          {experience.description && (
                            <div className="work-dis">
                              <p>{experience.description}</p>
                            </div>
                          )}
                          
                          {experience.documents && experience.documents.length > 0 && (
                            <div className="doc-grid">
                              {experience.documents.map((doc) => (
                                <div key={doc.id} className="doc-card">
                                  <div className="doc-left">
                                    <div className="icon-box">
                                      <img src="/assets/image/png.svg" alt={doc.fileType} />
                                    </div>
                                    <div className="doc-text">
                                      <div className="filename">{doc.filename}</div>
                                      <div className="size">{doc.fileSize}</div>
                                    </div>
                                  </div>
                                  <div className="download-arrow">
                                    <button onClick={() => handleDownloadDocument(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>
                                    </button>
                                  </div>
                                </div>
                              ))}
                            </div>
                          )}
                        </div>
                      ))
                    )}
                  </div>
                </div>
        </div>
      </div>

      {/* Add Experience Modal */}
      <AddExperienceModal
        isOpen={isModalOpen}
        onClose={() => {
          setIsModalOpen(false);
          setEditingExperience(null);
        }}
        experience={editingExperience}
        onExperienceUpdated={handleExperienceUpdated}
      />
    </FreelancerLayout>
  );
}