'use client';
import React, { useState, useEffect } from 'react';
import { Users, Plus, Save, X, Loader2, Pencil, Trash2, GripVertical } from 'lucide-react';
import ImageUpload from '@/components/admin/ImageUpload';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, rectSortingStrategy, useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

interface SortableLeaderProps {
  leader: any;
  onEdit: (l: any) => void;
  onDelete: (id: string) => void;
}

// Sortable Item Component
const SortableLeader: React.FC<SortableLeaderProps> = ({ leader, onEdit, onDelete }) => {
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: leader._id });
  
  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  };

  return (
    <div ref={setNodeRef} style={style} className="relative group flex items-center gap-4 p-4 border rounded-lg bg-slate-50 hover:bg-slate-100 transition shadow-sm">
      <div {...attributes} {...listeners} className="cursor-grab active:cursor-grabbing text-slate-400 hover:text-slate-600">
        <GripVertical size={20} />
      </div>
      <img src={leader.image || 'https://via.placeholder.com/100'} alt="" className="w-16 h-16 rounded-full object-cover border border-slate-200" />
      <div className="flex-1">
        <h4 className="font-bold text-slate-900">{leader.name}</h4>
        <span className={`text-[10px] text-white px-2 py-0.5 rounded ${leader.roleColor}`}>{leader.role}</span>
      </div>
      <div className="flex gap-2">
         <button 
            onClick={() => onEdit(leader)}
            className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-full transition"
            title="Edit"
          >
            <Pencil size={16} />
          </button>
          <button 
            onClick={() => onDelete(leader._id)}
            className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-full transition"
            title="Delete"
          >
            <Trash2 size={16} />
          </button>
      </div>
    </div>
  );
};

export default function AdminLeadership() {
  const [isCreating, setIsCreating] = useState(false);
  const [leaders, setLeaders] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [formData, setFormData] = useState({
    name: '',
    role: '',
    image: '',
    roleColor: 'bg-primary'
  });

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  useEffect(() => {
    fetchLeaders();
  }, []);

  const fetchLeaders = async () => {
    try {
      const res = await fetch('/api/leadership');
      const data = await res.json();
      if (Array.isArray(data)) setLeaders(data);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleDragEnd = async (event: DragEndEvent) => {
    const { active, over } = event;

    if (over && active.id !== over.id) {
      setLeaders((items) => {
        const oldIndex = items.findIndex((item) => item._id === active.id);
        const newIndex = items.findIndex((item) => item._id === over.id);
        const newOrder = arrayMove(items, oldIndex, newIndex);
        
        // Save order
        saveOrder(newOrder);
        return newOrder;
      });
    }
  };

  const saveOrder = async (newItems: any[]) => {
    try {
      const updates = newItems.map((item, index) => ({ _id: item._id, order: index }));
      await fetch('/api/leadership/reorder', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ updates })
      });
    } catch (e) {
      console.error("Failed to save order");
    }
  };

  const resetForm = () => {
    setIsCreating(false);
    setEditingId(null);
    setFormData({ name: '', role: '', image: '', roleColor: 'bg-primary' });
  };

  const handleEdit = (leader: any) => {
    setFormData({
      name: leader.name,
      role: leader.role,
      image: leader.image || '',
      roleColor: leader.roleColor || 'bg-primary'
    });
    setEditingId(leader._id);
    setIsCreating(true);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this leader?')) return;
    try {
      const res = await fetch(`/api/leadership/${id}`, { method: 'DELETE' });
      if (res.ok) fetchLeaders();
    } catch (error) {
      console.error('Failed to delete', error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const url = editingId ? `/api/leadership/${editingId}` : '/api/leadership';
      const method = editingId ? 'PUT' : 'POST';

      const res = await fetch(url, {
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });
      
      if (res.ok) {
        resetForm();
        fetchLeaders();
      }
    } catch (error) {
      console.error(error);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div>
      <div className="flex flex-col md:flex-row md:justify-between md:items-center gap-4 mb-8">
        <div>
          <h2 className="text-2xl font-bold text-slate-800">Leadership Team</h2>
          <p className="text-slate-500 text-sm">Manage executive committee. Drag items to reorder.</p>
        </div>
        {!isCreating && (
          <div className="flex-1 md:max-w-xs">
            <input
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search leaders..."
              className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary outline-none text-sm"
            />
          </div>
        )}
        {!isCreating && (
          <button 
            onClick={() => setIsCreating(true)}
            className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg font-medium transition flex items-center gap-2"
          >
            <Plus size={18} /> Add Leader
          </button>
        )}
      </div>

      {isCreating ? (
        <div className="bg-white rounded-xl border border-slate-200 p-6 shadow-sm mb-6">
          <div className="flex justify-between items-center mb-6">
            <h3 className="text-lg font-bold">{editingId ? 'Edit Leader' : 'Add New Leader'}</h3>
            <button onClick={resetForm} className="text-slate-400 hover:text-slate-600"><X size={20} /></button>
          </div>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Full Name</label>
              <input 
                required
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                value={formData.name}
                onChange={e => setFormData({...formData, name: e.target.value})}
                placeholder="e.g. John Doe"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Role / Title</label>
              <input 
                required
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                value={formData.role}
                onChange={e => setFormData({...formData, role: e.target.value})}
                placeholder="e.g. DIRECTOR"
              />
            </div>
            
            <ImageUpload 
              label="Profile Photo (Single)"
              value={formData.image}
              onChange={(val) => setFormData({...formData, image: val as string})}
            />

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Badge Color (Tailwind Class)</label>
              <select 
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                value={formData.roleColor}
                onChange={e => setFormData({...formData, roleColor: e.target.value})}
              >
                <option value="bg-primary">Green (Primary)</option>
                <option value="bg-blue-600">Blue</option>
                <option value="bg-slate-600">Slate</option>
                <option value="bg-red-600">Red</option>
                <option value="bg-purple-600">Purple</option>
              </select>
            </div>
            <div className="pt-2">
              <button 
                type="submit" 
                disabled={submitting}
                className="bg-primary hover:bg-primary-dark text-white px-6 py-2 rounded-lg font-medium transition flex items-center gap-2 disabled:opacity-50"
              >
                {submitting ? <Loader2 className="animate-spin" size={18} /> : <Save size={18} />} {editingId ? 'Update Leader' : 'Save Leader'}
              </button>
            </div>
          </form>
        </div>
      ) : null}

      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden shadow-sm">
        {loading ? (
          <div className="p-8 text-center"><Loader2 className="animate-spin mx-auto text-primary" /></div>
        ) : leaders.length === 0 ? (
          <div className="p-8 text-center py-16">
             <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4 text-slate-400">
               <Users size={32} />
             </div>
             <h3 className="text-lg font-medium text-slate-900">No leaders found</h3>
             <p className="text-slate-500 mb-6">Add leadership profiles to populate the About/Leadership section.</p>
          </div>
        ) : (
          (() => {
            const filtered = leaders.filter((leader) => {
              const term = searchTerm.toLowerCase().trim();
              if (!term) return true;
              const name = (leader.name || '').toLowerCase();
              const role = (leader.role || '').toLowerCase();
              return name.includes(term) || role.includes(term);
            });
            const canDrag = searchTerm.trim() === '';

            return (
              <>
                {canDrag ? (
                  <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
                    <SortableContext items={leaders.map(l => l._id)} strategy={rectSortingStrategy}>
                      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6">
                        {filtered.map((leader) => (
                          <SortableLeader 
                            key={leader._id} 
                            leader={leader} 
                            onEdit={handleEdit} 
                            onDelete={handleDelete} 
                          />
                        ))}
                      </div>
                    </SortableContext>
                  </DndContext>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6">
                    {filtered.map((leader) => (
                      <SortableLeader 
                        key={leader._id} 
                        leader={leader} 
                        onEdit={handleEdit} 
                        onDelete={handleDelete} 
                      />
                    ))}
                  </div>
                )}

                <div className="p-4 flex flex-col md:flex-row md:items-center md:justify-between gap-3 border-t border-slate-100">
                  <p className="text-xs text-slate-500">Showing {filtered.length} leaders</p>
                </div>
              </>
            );
          })()
        )}
      </div>
    </div>
  );
}
