// frontend/src/components/Editor/SectionEditor.jsx
import React, { useState } from 'react';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { enhanceWithAI } from '../../api';

const SectionEditor = ({ type, data, onChange }) => {
  const [isEnhancing, setIsEnhancing] = useState(false);
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: type });
  
  const style = { transform: CSS.Transform.toString(transform), transition };
  
  const sectionTitles = {
    summary: 'Professional Summary',
    skills: 'Skills',
    experience: 'Work Experience',
    education: 'Education'
  };
  
  const handleAIEnhance = async () => {
    setIsEnhancing(true);
    const enhanced = await enhanceWithAI(type, data);
    onChange(enhanced);
    setIsEnhancing(false);
  };
  
  if (type === 'summary') {
    return (
      <div ref={setNodeRef} style={style} className="mb-8 p-4 border rounded-lg">
        <div {...attributes} {...listeners} className="cursor-move bg-gray-50 p-2 rounded mb-3 flex justify-between items-center">
          <h3 className="font-semibold">{sectionTitles[type]}</h3>
          <button onClick={handleAIEnhance} disabled={isEnhancing} className="text-sm bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600">
            {isEnhancing ? 'Enhancing...' : '✨ AI Enhance'}
          </button>
        </div>
        <textarea 
          value={data || ''}
          onChange={(e) => onChange(e.target.value)}
          rows={5}
          className="w-full px-4 py-2 border rounded-lg"
          placeholder="Write a compelling professional summary..."
        />
      </div>
    );
  }
  
  if (type === 'skills') {
    return (
      <div ref={setNodeRef} style={style} className="mb-8 p-4 border rounded-lg">
        <div {...attributes} {...listeners} className="cursor-move bg-gray-50 p-2 rounded mb-3 font-semibold">
          {sectionTitles[type]}
        </div>
        <input 
          type="text"
          value={Array.isArray(data) ? data.join(', ') : ''}
          onChange={(e) => onChange(e.target.value.split(',').map(s => s.trim()))}
          className="w-full px-4 py-2 border rounded-lg"
          placeholder="React, Node.js, Python, SQL (comma separated)"
        />
      </div>
    );
  }
  
  if (type === 'experience' || type === 'education') {
    const items = Array.isArray(data) ? data : [];
    const addItem = () => {
      const newItem = type === 'experience' 
        ? { id: Date.now(), company: '', position: '', start_date: '', end_date: '', description: '' }
        : { id: Date.now(), degree: '', school: '', year: '' };
      onChange([...items, newItem]);
    };
    
    return (
      <div ref={setNodeRef} style={style} className="mb-8 p-4 border rounded-lg">
        <div {...attributes} {...listeners} className="cursor-move bg-gray-50 p-2 rounded mb-3 font-semibold">
          {sectionTitles[type]}
        </div>
        {items.map((item, idx) => (
          <div key={item.id} className="mb-4 p-3 border rounded">
            {type === 'experience' ? (
              <>
                <input placeholder="Company" value={item.company} onChange={(e) => {
                  const updated = [...items];
                  updated[idx].company = e.target.value;
                  onChange(updated);
                }} className="w-full mb-2 px-3 py-1 border rounded" />
                <input placeholder="Position" value={item.position} onChange={(e) => {
                  const updated = [...items];
                  updated[idx].position = e.target.value;
                  onChange(updated);
                }} className="w-full mb-2 px-3 py-1 border rounded" />
                <div className="grid grid-cols-2 gap-2 mb-2">
                  <input placeholder="Start Date" value={item.start_date} onChange={(e) => {
                    const updated = [...items];
                    updated[idx].start_date = e.target.value;
                    onChange(updated);
                  }} className="px-3 py-1 border rounded" />
                  <input placeholder="End Date" value={item.end_date} onChange={(e) => {
                    const updated = [...items];
                    updated[idx].end_date = e.target.value;
                    onChange(updated);
                  }} className="px-3 py-1 border rounded" />
                </div>
                <textarea placeholder="Description" value={item.description} onChange={(e) => {
                  const updated = [...items];
                  updated[idx].description = e.target.value;
                  onChange(updated);
                }} rows={3} className="w-full px-3 py-1 border rounded" />
              </>
            ) : (
              <>
                <input placeholder="Degree" value={item.degree} onChange={(e) => {
                  const updated = [...items];
                  updated[idx].degree = e.target.value;
                  onChange(updated);
                }} className="w-full mb-2 px-3 py-1 border rounded" />
                <input placeholder="School" value={item.school} onChange={(e) => {
                  const updated = [...items];
                  updated[idx].school = e.target.value;
                  onChange(updated);
                }} className="w-full mb-2 px-3 py-1 border rounded" />
                <input placeholder="Year" value={item.year} onChange={(e) => {
                  const updated = [...items];
                  updated[idx].year = e.target.value;
                  onChange(updated);
                }} className="w-full px-3 py-1 border rounded" />
              </>
            )}
            <button onClick={() => onChange(items.filter((_, i) => i !== idx))} className="text-red-500 text-sm mt-2">Remove</button>
          </div>
        ))}
        <button onClick={addItem} className="w-full border-2 border-dashed border-gray-300 rounded-lg py-2 text-gray-500 hover:border-blue-500 hover:text-blue-500">
          + Add {type === 'experience' ? 'Experience' : 'Education'}
        </button>
      </div>
    );
  }
  
  return null;
};

export default SectionEditor;