import React, { useState } from 'react';
import UploadModal from './components/UploadModal';

function App() {
  const [resumeData, setResumeData] = useState({
    personal: {
      name: '',
      title: '',
      email: '',
      phone: '',
      location: ''
    },
    summary: '',
    skills: [],
    experience: [],
    education: []
  });
  
  const [selectedTemplate, setSelectedTemplate] = useState('modern');
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  
  const handleCVParse = (parsedData) => {
    setResumeData({
      personal: {
        ...parsedData.personal
      },
      summary: parsedData.summary || '',
      skills: parsedData.skills || [],
      experience: parsedData.experience || [],
      education: parsedData.education || []
    });

const handleCVParse = (parsedData) => {
  console.log('📄 Raw extracted data:', parsedData);
  
  // Create new state object with extracted data
  const newResumeData = {
    personal: {
      name: parsedData.personal?.name || '',
      title: parsedData.personal?.title || '',
      email: parsedData.personal?.email || '',
      phone: parsedData.personal?.phone || '',
      location: parsedData.personal?.location || ''
    },
    summary: parsedData.summary || '',
    skills: Array.isArray(parsedData.skills) ? parsedData.skills : [],
    experience: Array.isArray(parsedData.experience) ? parsedData.experience : [],
    education: Array.isArray(parsedData.education) ? parsedData.education : []
  };
  
  setResumeData(newResumeData);
  
  // Show detailed extraction results
  alert(`✓ CV Data Extracted!\n\n` +
    `📝 Name: ${newResumeData.personal.name || '(not found)'}\n` +
    `📧 Email: ${newResumeData.personal.email || '(not found)'}\n` +
    `📱 Phone: ${newResumeData.personal.phone || '(not found)'}\n` +
    `📍 Location: ${newResumeData.personal.location || '(not found)'}\n` +
    `🛠️ Skills: ${newResumeData.skills.length} found\n` +
    `💼 Experience: ${newResumeData.experience.length} entries\n` +
    `🎓 Education: ${newResumeData.education.length} entries\n\n` +
    `All fields have been populated with data from your file!`);
};
    
    // Show success message with parsed data summary
    alert(`✓ CV parsed successfully!\n\n📊 Found:\n• ${parsedData.skills?.length || 0} skills\n• ${parsedData.experience?.length || 0} work experiences\n• ${parsedData.education?.length || 0} education entries\n\nYou can now edit the information in the editor.`);
  };
  
  const saveResume = () => {
    localStorage.setItem('savedResume', JSON.stringify(resumeData));
    alert('Resume saved to browser storage!');
  };
  
  const loadResume = () => {
    const saved = localStorage.getItem('savedResume');
    if (saved) {
      setResumeData(JSON.parse(saved));
      alert('Resume loaded successfully!');
    } else {
      alert('No saved resume found');
    }
  };
  
  const exportAsJSON = () => {
    const dataStr = JSON.stringify(resumeData, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
    const exportFileDefaultName = 'resume-data.json';
    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
  };
  
  const addExperience = () => {
    setResumeData({
      ...resumeData,
      experience: [...resumeData.experience, {
        id: Date.now(),
        company: '',
        position: '',
        start_date: '',
        end_date: '',
        description: ''
      }]
    });
  };
  
  const updateExperience = (index, field, value) => {
    const updated = [...resumeData.experience];
    updated[index][field] = value;
    setResumeData({...resumeData, experience: updated});
  };
  
  const removeExperience = (index) => {
    const updated = resumeData.experience.filter((_, i) => i !== index);
    setResumeData({...resumeData, experience: updated});
  };
  
  const addEducation = () => {
    setResumeData({
      ...resumeData,
      education: [...resumeData.education, {
        id: Date.now(),
        degree: '',
        school: '',
        year: ''
      }]
    });
  };
  
  const updateEducation = (index, field, value) => {
    const updated = [...resumeData.education];
    updated[index][field] = value;
    setResumeData({...resumeData, education: updated});
  };
  
  const removeEducation = (index) => {
    const updated = resumeData.education.filter((_, i) => i !== index);
    setResumeData({...resumeData, education: updated});
  };
  
  return (
    <div className="flex h-screen bg-gray-50">
      <UploadModal 
        isOpen={isUploadModalOpen}
        onClose={() => setIsUploadModalOpen(false)}
        onCVParse={handleCVParse}
      />
      
      <div className="fixed top-0 left-0 right-0 bg-white border-b border-gray-200 px-6 py-3 flex justify-between items-center z-50 shadow-sm">
        <div className="flex items-center gap-4">
          <h1 className="text-xl font-bold text-gray-800">📄 ResumeBuilder</h1>
          <div className="flex gap-2">
            {['modern', 'classic', 'minimal'].map(t => (
              <button
                key={t}
                onClick={() => setSelectedTemplate(t)}
                className={`px-4 py-2 rounded-lg transition capitalize ${selectedTemplate === t ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}
              >
                {t}
              </button>
            ))}
          </div>
        </div>
        <div className="flex gap-3">
          <button 
            onClick={() => setIsUploadModalOpen(true)} 
            className="px-5 py-2 bg-indigo-500 text-white rounded-lg hover:bg-indigo-600 transition flex items-center gap-2"
          >
            📤 Upload & Parse CV
          </button>
          <button onClick={loadResume} className="px-5 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition">
            📂 Load Saved
          </button>
          <button onClick={saveResume} className="px-5 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition">
            💾 Save
          </button>
          <button onClick={exportAsJSON} className="px-5 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition">
            📥 Export JSON
          </button>
        </div>
      </div>
      
      {/* Editor Panel */}
      <div className="w-1/2 bg-white border-r border-gray-200 overflow-y-auto p-6 mt-16">
        <div className="max-w-2xl mx-auto">
          {/* Personal Info */}
          <div className="mb-8">
            <h2 className="text-2xl font-bold mb-4 text-gray-800">Personal Information</h2>
            <div className="space-y-3">
              <input 
                type="text" 
                placeholder="Full Name"
                value={resumeData.personal.name}
                onChange={(e) => setResumeData({...resumeData, personal: {...resumeData.personal, name: e.target.value}})}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              />
              <input 
                type="text" 
                placeholder="Professional Title"
                value={resumeData.personal.title}
                onChange={(e) => setResumeData({...resumeData, personal: {...resumeData.personal, title: e.target.value}})}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg"
              />
              <div className="grid grid-cols-2 gap-3">
                <input type="email" placeholder="Email" value={resumeData.personal.email} onChange={(e) => setResumeData({...resumeData, personal: {...resumeData.personal, email: e.target.value}})} className="px-4 py-2 border border-gray-300 rounded-lg" />
                <input type="tel" placeholder="Phone" value={resumeData.personal.phone} onChange={(e) => setResumeData({...resumeData, personal: {...resumeData.personal, phone: e.target.value}})} className="px-4 py-2 border border-gray-300 rounded-lg" />
              </div>
              <input 
                type="text" 
                placeholder="Location (City, State)"
                value={resumeData.personal.location}
                onChange={(e) => setResumeData({...resumeData, personal: {...resumeData.personal, location: e.target.value}})}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg"
              />
            </div>
          </div>
          
          {/* Summary */}
          <div className="mb-8">
            <h2 className="text-2xl font-bold mb-4 text-gray-800">Professional Summary</h2>
            <textarea 
              value={resumeData.summary}
              onChange={(e) => setResumeData({...resumeData, summary: e.target.value})}
              rows={4}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg"
              placeholder="Write a compelling professional summary..."
            />
          </div>
          
          {/* Skills */}
          <div className="mb-8">
            <h2 className="text-2xl font-bold mb-4 text-gray-800">Skills</h2>
            <input 
              type="text"
              value={resumeData.skills.join(', ')}
              onChange={(e) => setResumeData({...resumeData, skills: e.target.value.split(',').map(s => s.trim())})}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg"
              placeholder="React, Node.js, Python, SQL (comma separated)"
            />
            {resumeData.skills.length > 0 && (
              <div className="mt-2 flex flex-wrap gap-2">
                {resumeData.skills.map((skill, idx) => (
                  <span key={idx} className="bg-blue-100 text-blue-700 px-2 py-1 rounded text-sm">
                    {skill}
                  </span>
                ))}
              </div>
            )}
          </div>
          
          {/* Experience */}
          <div className="mb-8">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-2xl font-bold text-gray-800">Work Experience</h2>
              <button onClick={addExperience} className="text-blue-500 hover:text-blue-600 text-sm font-semibold">
                + Add Experience
              </button>
            </div>
            {resumeData.experience.map((exp, idx) => (
              <div key={exp.id} className="mb-4 p-4 border border-gray-200 rounded-lg bg-gray-50">
                <input 
                  placeholder="Company Name" 
                  value={exp.company} 
                  onChange={(e) => updateExperience(idx, 'company', e.target.value)}
                  className="w-full mb-2 px-3 py-2 border border-gray-300 rounded"
                />
                <input 
                  placeholder="Position Title" 
                  value={exp.position} 
                  onChange={(e) => updateExperience(idx, 'position', e.target.value)}
                  className="w-full mb-2 px-3 py-2 border border-gray-300 rounded"
                />
                <div className="grid grid-cols-2 gap-2 mb-2">
                  <input placeholder="Start Date" value={exp.start_date} onChange={(e) => updateExperience(idx, 'start_date', e.target.value)} className="px-3 py-2 border border-gray-300 rounded" />
                  <input placeholder="End Date" value={exp.end_date} onChange={(e) => updateExperience(idx, 'end_date', e.target.value)} className="px-3 py-2 border border-gray-300 rounded" />
                </div>
                <textarea 
                  placeholder="Job Description" 
                  value={exp.description} 
                  onChange={(e) => updateExperience(idx, 'description', e.target.value)}
                  rows={3} 
                  className="w-full mb-2 px-3 py-2 border border-gray-300 rounded"
                />
                <button onClick={() => removeExperience(idx)} className="text-red-500 text-sm hover:text-red-600">
                  Remove
                </button>
              </div>
            ))}
          </div>
          
          {/* Education */}
          <div className="mb-8">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-2xl font-bold text-gray-800">Education</h2>
              <button onClick={addEducation} className="text-blue-500 hover:text-blue-600 text-sm font-semibold">
                + Add Education
              </button>
            </div>
            {resumeData.education.map((edu, idx) => (
              <div key={edu.id} className="mb-4 p-4 border border-gray-200 rounded-lg bg-gray-50">
                <input 
                  placeholder="Degree" 
                  value={edu.degree} 
                  onChange={(e) => updateEducation(idx, 'degree', e.target.value)}
                  className="w-full mb-2 px-3 py-2 border border-gray-300 rounded"
                />
                <input 
                  placeholder="School/University" 
                  value={edu.school} 
                  onChange={(e) => updateEducation(idx, 'school', e.target.value)}
                  className="w-full mb-2 px-3 py-2 border border-gray-300 rounded"
                />
                <input 
                  placeholder="Year of Graduation" 
                  value={edu.year} 
                  onChange={(e) => updateEducation(idx, 'year', e.target.value)}
                  className="w-full mb-2 px-3 py-2 border border-gray-300 rounded"
                />
                <button onClick={() => removeEducation(idx)} className="text-red-500 text-sm hover:text-red-600">
                  Remove
                </button>
              </div>
            ))}
          </div>
        </div>
      </div>
      
      {/* Preview Panel */}
      <div className="w-1/2 bg-gray-100 overflow-y-auto p-6 mt-16">
        <div className="max-w-4xl mx-auto">
          <div className="bg-white shadow-xl rounded-lg overflow-hidden">
            <div className="p-8">
              <div className="border-b-4 border-blue-500 pb-4 mb-6">
                <h1 className="text-4xl font-bold text-gray-800">{resumeData.personal.name || 'Your Name'}</h1>
                <p className="text-xl text-blue-600 mt-2">{resumeData.personal.title || 'Professional Title'}</p>
                <div className="flex gap-4 mt-3 text-sm text-gray-600 flex-wrap">
                  {resumeData.personal.email && <span>📧 {resumeData.personal.email}</span>}
                  {resumeData.personal.phone && <span>📱 {resumeData.personal.phone}</span>}
                  {resumeData.personal.location && <span>📍 {resumeData.personal.location}</span>}
                </div>
              </div>
              
              {resumeData.summary && (
                <div className="mb-6">
                  <h2 className="text-xl font-semibold text-gray-800 mb-2">Professional Summary</h2>
                  <p className="text-gray-700 leading-relaxed">{resumeData.summary}</p>
                </div>
              )}
              
              {resumeData.skills.length > 0 && (
                <div className="mb-6">
                  <h2 className="text-xl font-semibold text-gray-800 mb-2">Core Skills</h2>
                  <div className="flex flex-wrap gap-2">
                    {resumeData.skills.map((skill, idx) => (
                      <span key={idx} className="bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm">
                        {skill}
                      </span>
                    ))}
                  </div>
                </div>
              )}
              
              {resumeData.experience.length > 0 && (
                <div className="mb-6">
                  <h2 className="text-xl font-semibold text-gray-800 mb-3">Work Experience</h2>
                  {resumeData.experience.map((job, idx) => (
                    <div key={idx} className="mb-4">
                      <div className="flex justify-between items-start flex-wrap">
                        <div>
                          <h3 className="font-semibold text-gray-800">{job.position}</h3>
                          <p className="text-blue-600">{job.company}</p>
                        </div>
                        {(job.start_date || job.end_date) && (
                          <span className="text-sm text-gray-500">{job.start_date} - {job.end_date}</span>
                        )}
                      </div>
                      <p className="text-gray-700 mt-2">{job.description}</p>
                    </div>
                  ))}
                </div>
              )}
              
              {resumeData.education.length > 0 && (
                <div>
                  <h2 className="text-xl font-semibold text-gray-800 mb-3">Education</h2>
                  {resumeData.education.map((edu, idx) => (
                    <div key={idx} className="mb-3">
                      <div className="flex justify-between flex-wrap">
                        <div>
                          <h3 className="font-semibold text-gray-800">{edu.degree}</h3>
                          <p className="text-gray-600">{edu.school}</p>
                        </div>
                        <span className="text-sm text-gray-500">{edu.year}</span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
              
              {!resumeData.personal.name && !resumeData.summary && resumeData.skills.length === 0 && (
                <div className="text-center py-12 text-gray-400">
                  <svg className="mx-auto h-16 w-16 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                  <p>📤 Click "Upload & Parse CV" to get started</p>
                  <p className="text-sm mt-2">Upload a PDF, DOCX, or TXT file with your existing CV</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;