import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { api } from '../api';

export default function Dashboard() {
  const [boards, setBoards] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showNew, setShowNew] = useState(false);
  const [newTitle, setNewTitle] = useState('');
  const [newDesc, setNewDesc] = useState('');
  const { user } = useAuth();
  const navigate = useNavigate();

  const loadBoards = async () => {
    try {
      const data = await api.boards.list();
      setBoards(data);
    } catch {}
    setLoading(false);
  };

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

  const createBoard = async (e) => {
    e.preventDefault();
    if (!newTitle.trim()) return;
    try {
      const board = await api.boards.create({ title: newTitle, description: newDesc });
      setNewTitle('');
      setNewDesc('');
      setShowNew(false);
      navigate(`/board/${board.id}`);
    } catch (err) {
      alert(err.message);
    }
  };

  const bgColors = {
    'gradient-blue': 'from-blue-600 to-blue-400',
    'gradient-purple': 'from-purple-600 to-purple-400',
    'gradient-green': 'from-green-600 to-green-400',
    'gradient-orange': 'from-orange-600 to-orange-400',
    'gradient-pink': 'from-pink-600 to-pink-400',
    'gradient-teal': 'from-teal-600 to-teal-400',
    'gradient-indigo': 'from-indigo-600 to-indigo-400',
    'gradient-red': 'from-red-600 to-red-400',
  };

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Your Boards</h1>
          <p className="text-sm text-gray-500 mt-1">Welcome back, {user?.name}</p>
        </div>
        <button onClick={() => setShowNew(!showNew)} className="bg-brand-600 text-white px-4 py-2 rounded-lg font-medium hover:bg-brand-700 transition-colors flex items-center gap-2">
          <span className="text-lg leading-none">+</span> New Board
        </button>
      </div>

      {showNew && (
        <form onSubmit={createBoard} className="bg-white rounded-xl border border-gray-200 p-5 mb-6 shadow-sm">
          <h3 className="font-semibold text-gray-900 mb-3">Create New Board</h3>
          <input type="text" value={newTitle} onChange={e => setNewTitle(e.target.value)} placeholder="Board title" autoFocus className="w-full px-3 py-2 border border-gray-300 rounded-lg mb-3 focus:ring-2 focus:ring-brand-500 focus:border-transparent" />
          <input type="text" value={newDesc} onChange={e => setNewDesc(e.target.value)} placeholder="Description (optional)" className="w-full px-3 py-2 border border-gray-300 rounded-lg mb-3 focus:ring-2 focus:ring-brand-500 focus:border-transparent" />
          <div className="flex gap-2">
            <button type="submit" className="bg-brand-600 text-white px-4 py-2 rounded-lg font-medium hover:bg-brand-700">Create</button>
            <button type="button" onClick={() => setShowNew(false)} className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">Cancel</button>
          </div>
        </form>
      )}

      {loading ? (
        <div className="flex items-center justify-center py-20">
          <div className="animate-spin h-8 w-8 border-4 border-brand-500 border-t-transparent rounded-full"></div>
        </div>
      ) : boards.length === 0 ? (
        <div className="text-center py-20">
          <div className="text-6xl mb-4">📋</div>
          <h3 className="text-xl font-semibold text-gray-900 mb-2">No boards yet</h3>
          <p className="text-gray-500 mb-4">Create your first board to get started</p>
          <button onClick={() => setShowNew(true)} className="bg-brand-600 text-white px-6 py-2.5 rounded-lg font-medium hover:bg-brand-700">Create Board</button>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {boards.map(board => (
            <div
              key={board.id}
              onClick={() => navigate(`/board/${board.id}`)}
              className={`bg-gradient-to-br ${bgColors[board.background] || bgColors['gradient-blue']} rounded-xl p-5 text-white cursor-pointer hover:scale-[1.02] transition-transform shadow-md hover:shadow-lg min-h-[140px] flex flex-col justify-between`}
            >
              <div>
                <h3 className="font-bold text-lg">{board.title}</h3>
                {board.description && <p className="text-white/80 text-sm mt-1 line-clamp-2">{board.description}</p>}
              </div>
              <div className="flex items-center justify-between mt-4">
                <span className="text-xs bg-white/20 px-2 py-0.5 rounded-full">{board.my_role}</span>
                {board.due_soon_count > 0 && (
                  <span className="text-xs bg-yellow-400/90 text-yellow-900 px-2 py-0.5 rounded-full font-medium">
                    ⏰ {board.due_soon_count}
                  </span>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
