import React, { useState, useEffect, useCallback } from 'react';
import { useParams } from 'react-router-dom';
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
import { api } from '../api';
import CardModal from '../components/CardModal';

export default function BoardView() {
  const { id } = useParams();
  const [board, setBoard] = useState(null);
  const [loading, setLoading] = useState(true);
  const [activeCard, setActiveCard] = useState(null);
  const [addingList, setAddingList] = useState(false);
  const [newListTitle, setNewListTitle] = useState('');
  const [showMembers, setShowMembers] = useState(false);
  const [addMemberEmail, setAddMemberEmail] = useState('');

  const loadBoard = useCallback(async () => {
    try {
      const data = await api.boards.full(id);
      setBoard(data);
    } catch {}
    setLoading(false);
  }, [id]);

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

  const handleDragEnd = async (result) => {
    if (!result.destination) return;
    const { source, destination, draggableId, type } = result;

    if (type === 'list') {
      const lists = [...board.lists];
      const [moved] = lists.splice(source.index, 1);
      lists.splice(destination.index, 0, moved);
      lists.forEach((l, i) => l.position = i * 65536);
      setBoard({ ...board, lists });
      await api.cards.reorderList(moved.id, destination.index * 65536);
      return;
    }

    const srcList = board.lists.find(l => l.id === parseInt(source.droppableId));
    const dstList = board.lists.find(l => l.id === parseInt(destination.droppableId));
    if (!srcList || !dstList) return;

    const srcCards = [...srcList.cards];
    const [movedCard] = srcCards.splice(source.index, 1);
    const moved = source.droppableId !== destination.droppableId;
    if (moved) movedCard.list_id = dstList.id;

    const dstCards = moved ? [...dstList.cards] : srcCards;
    dstCards.splice(destination.index, 0, movedCard);
    dstCards.forEach((c, i) => c.position = i * 65536);

    const newLists = board.lists.map(l => {
      if (l.id === dstList.id) return { ...l, cards: dstCards };
      if (l.id === srcList.id && moved) return { ...l, cards: srcCards };
      return l;
    });

    setBoard({ ...board, lists: newLists });

    try {
      const cardUpdates = dstCards.map((c, i) => ({
        id: c.id, list_id: c.list_id, position: i * 65536,
        moved: moved && c.id === movedCard.id,
        old_list_id: moved ? srcList.id : c.list_id,
      }));
      await api.cards.reorder(cardUpdates);
    } catch {
      loadBoard();
    }
  };

  const createList = async (e) => {
    e.preventDefault();
    if (!newListTitle.trim()) return;
    try {
      await api.cards.createList(id, newListTitle);
      setNewListTitle('');
      setAddingList(false);
      loadBoard();
    } catch (err) { alert(err.message); }
  };

  const addMember = async (e) => {
    e.preventDefault();
    if (!addMemberEmail.trim()) return;
    try {
      const allUsers = await api.users.list();
      const u = allUsers.find(u => u.email === addMemberEmail);
      if (!u) { alert('User not found. Admin needs to create them first.'); return; }
      await api.boards.addMember(id, { user_id: u.id });
      setAddMemberEmail('');
      loadBoard();
    } catch (err) { alert(err.message); }
  };

  const bgClasses = {
    'gradient-blue': 'gradient-blue',
    'gradient-purple': 'gradient-purple',
    'gradient-green': 'gradient-green',
    'gradient-orange': 'gradient-orange',
    'gradient-pink': 'gradient-pink',
    'gradient-teal': 'gradient-teal',
    'gradient-indigo': 'gradient-indigo',
    'gradient-red': 'gradient-red',
  };

  if (loading) return (
    <div className="flex items-center justify-center h-full"><div className="animate-spin h-8 w-8 border-4 border-brand-500 border-t-transparent rounded-full"></div></div>
  );
  if (!board) return <div className="p-6 text-gray-500">Board not found</div>;

  return (
    <div className="h-full flex flex-col">
      {/* Board Header */}
      <div className={`${bgClasses[board.background] || 'gradient-blue'} px-6 py-4 flex items-center justify-between shrink-0`}>
        <div className="flex items-center gap-4">
          <h1 className="text-2xl font-bold text-white">{board.title}</h1>
          {board.description && <span className="text-white/70 text-sm">{board.description}</span>}
        </div>
        <div className="flex items-center gap-3">
          <div className="flex -space-x-2">
            {board.members.slice(0, 5).map(m => (
              <div key={m.id} className="w-8 h-8 rounded-full border-2 border-white flex items-center justify-center text-white text-xs font-medium" style={{ backgroundColor: m.avatar_color }} title={m.name}>
                {m.name.charAt(0).toUpperCase()}
              </div>
            ))}
          </div>
          <button onClick={() => setShowMembers(!showMembers)} className="text-white/80 hover:text-white text-sm flex items-center gap-1">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
            {board.members.length}
          </button>
        </div>
      </div>

      {showMembers && (
        <div className="bg-white border-b border-gray-200 px-6 py-3 flex items-center gap-3 shrink-0">
          {board.members.map(m => (
            <div key={m.id} className="flex items-center gap-2 bg-gray-100 rounded-lg px-3 py-1.5 text-sm">
              <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-medium" style={{ backgroundColor: m.avatar_color }}>{m.name.charAt(0)}</div>
              <span className="font-medium">{m.name}</span>
              <span className="text-gray-400 text-xs">{m.board_role}</span>
            </div>
          ))}
          <form onSubmit={addMember} className="flex gap-1">
            <input type="email" value={addMemberEmail} onChange={e => setAddMemberEmail(e.target.value)} placeholder="Add by email..." className="px-2 py-1 text-sm border border-gray-300 rounded-lg w-48 focus:ring-1 focus:ring-brand-500 focus:border-transparent" />
            <button type="submit" className="text-brand-600 hover:bg-brand-50 px-2 py-1 rounded text-sm font-medium">+</button>
          </form>
        </div>
      )}

      {/* Kanban */}
      <DragDropContext onDragEnd={handleDragEnd}>
        <Droppable droppableId="board" type="list" direction="horizontal">
          {(provided) => (
            <div ref={provided.innerRef} {...provided.droppableProps} className="flex-1 flex gap-4 p-6 overflow-x-auto overflow-y-hidden">
              {board.lists.map((list, listIdx) => (
                <Draggable key={list.id} draggableId={`list-${list.id}`} index={listIdx}>
                  {(dragProvided) => (
                    <div ref={dragProvided.innerRef} {...dragProvided.draggableProps} className="w-72 shrink-0 flex flex-col bg-gray-100 rounded-xl max-h-full">
                      <div {...dragProvided.dragHandleProps} className="px-3 py-2.5 flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <h3 className="font-semibold text-gray-800 text-sm">{list.title}</h3>
                          <span className="bg-gray-300 text-gray-600 text-xs px-1.5 py-0.5 rounded-full font-medium">{list.cards.length}</span>
                        </div>
                      </div>
                      <Droppable droppableId={String(list.id)}>
                        {(dropProvided, snapshot) => (
                          <div ref={dropProvided.innerRef} {...dropProvided.droppableProps} className={`flex-1 overflow-y-auto px-2 pb-2 space-y-2 min-h-[4px] ${snapshot.isDraggingOver ? 'bg-brand-50 rounded-lg' : ''}`}>
                            {list.cards.map((card, cardIdx) => (
                              <Draggable key={card.id} draggableId={String(card.id)} index={cardIdx}>
                                {(cardDragProvided) => (
                                  <div ref={cardDragProvided.innerRef} {...cardDragProvided.draggableProps} {...cardDragProvided.dragHandleProps}>
                                    <CardComponent card={card} onClick={() => setActiveCard(card)} />
                                  </div>
                                )}
                              </Draggable>
                            ))}
                            {dropProvided.placeholder}
                          </div>
                        )}
                      </Droppable>
                      <div className="px-2 pb-2">
                        <AddCardForm listId={list.id} onAdded={loadBoard} />
                      </div>
                    </div>
                  )}
                </Draggable>
              ))}
              {provided.placeholder}
              {addingList ? (
                <div className="w-72 shrink-0 bg-white rounded-xl p-3 shadow-sm">
                  <form onSubmit={createList}>
                    <input type="text" value={newListTitle} onChange={e => setNewListTitle(e.target.value)} placeholder="List title" autoFocus className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded-lg mb-2 focus:ring-2 focus:ring-brand-500 focus:border-transparent" />
                    <div className="flex gap-1">
                      <button type="submit" className="bg-brand-600 text-white px-3 py-1 rounded text-sm font-medium hover:bg-brand-700">Add</button>
                      <button type="button" onClick={() => { setAddingList(false); setNewListTitle(''); }} className="px-3 py-1 text-gray-500 hover:bg-gray-100 rounded text-sm">Cancel</button>
                    </div>
                  </form>
                </div>
              ) : (
                <button onClick={() => setAddingList(true)} className="w-72 shrink-0 bg-white/80 hover:bg-white rounded-xl p-3 flex items-center gap-2 text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors">
                  <span className="text-lg">+</span> Add List
                </button>
              )}
            </div>
          )}
        </Droppable>
      </DragDropContext>

      {activeCard && (
        <CardModal cardId={activeCard.id} boardId={id} onClose={() => { setActiveCard(null); loadBoard(); }} />
      )}
    </div>
  );
}

function CardComponent({ card, onClick }) {
  const priorityStyles = { none: '', low: 'border-l-green-400', medium: 'border-l-yellow-400', high: 'border-l-orange-400', urgent: 'border-l-red-500' };
  const priorityBg = { none: '', low: 'bg-green-50', medium: 'bg-yellow-50', high: 'bg-orange-50', urgent: 'bg-red-50' };

  const dueBadge = card.due_date ? (() => {
    const due = new Date(card.due_date);
    const now = new Date();
    const days = Math.ceil((due - now) / 86400000);
    if (days < 0) return <span className="text-xs text-red-600 bg-red-50 px-1.5 py-0.5 rounded">Overdue</span>;
    if (days <= 3) return <span className="text-xs text-orange-600 bg-orange-50 px-1.5 py-0.5 rounded">Due {due.toLocaleDateString()}</span>;
    return <span className="text-xs text-gray-500 bg-gray-100 px-1.5 py-0.5 rounded">{due.toLocaleDateString()}</span>;
  })() : null;

  return (
    <div onClick={onClick} className={`bg-white rounded-lg p-3 shadow-sm border border-gray-200 cursor-pointer hover:border-brand-300 hover:shadow-md transition-all border-l-4 ${priorityStyles[card.priority] || ''} card-enter`}>
      {card.labels?.length > 0 && (
        <div className="flex gap-1 mb-2 flex-wrap">
          {card.labels.map(l => (
            <span key={l.id} className="text-xs px-2 py-0.5 rounded-full text-white font-medium" style={{ backgroundColor: l.color }}>{l.name}</span>
          ))}
        </div>
      )}
      <p className="text-sm font-medium text-gray-800 mb-1">{card.title}</p>
      {card.description && <p className="text-xs text-gray-500 line-clamp-2 mb-2">{card.description}</p>}
      <div className="flex items-center justify-between mt-1">
        <div className="flex items-center gap-1.5">
          {dueBadge}
          {card.total_items > 0 && (
            <span className={`text-xs px-1.5 py-0.5 rounded ${card.done_items === card.total_items ? 'bg-green-100 text-green-700' : 'bg-blue-100 text-blue-700'}`}>
              {card.done_items}/{card.total_items} ✓
            </span>
          )}
        </div>
        {card.assignee_color && (
          <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-medium" style={{ backgroundColor: card.assignee_color }} title={card.assignee_name}>
            {card.assignee_name?.charAt(0)?.toUpperCase()}
          </div>
        )}
      </div>
    </div>
  );
}

function AddCardForm({ listId, onAdded }) {
  const [show, setShow] = useState(false);
  const [title, setTitle] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!title.trim()) return;
    try {
      await api.cards.create(listId, { title });
      setTitle('');
      setShow(false);
      onAdded();
    } catch (err) { alert(err.message); }
  };

  if (!show) return <button onClick={() => setShow(true)} className="w-full text-left px-2 py-1.5 text-gray-500 hover:bg-gray-200 rounded-lg text-sm transition-colors">+ Add card</button>;

  return (
    <form onSubmit={handleSubmit} className="bg-white rounded-lg p-2 shadow-sm border border-gray-200">
      <input type="text" value={title} onChange={e => setTitle(e.target.value)} placeholder="Card title..." autoFocus className="w-full px-2 py-1 text-sm border border-gray-300 rounded mb-1 focus:ring-1 focus:ring-brand-500 focus:border-transparent" onBlur={() => { if (!title) setShow(false); }} />
      <div className="flex gap-1">
        <button type="submit" className="bg-brand-600 text-white px-2 py-0.5 rounded text-xs font-medium hover:bg-brand-700">Add</button>
        <button type="button" onClick={() => { setShow(false); setTitle(''); }} className="px-2 py-0.5 text-gray-400 hover:text-gray-600 text-xs">✕</button>
      </div>
    </form>
  );
}
