import { useState, useEffect } from 'react';
import CloseIcon from './icons/CloseIcon';
import { useApi } from '../hooks/useApi';
import { useLoader } from '../context/loaders/useLoader';
import { useToast } from '../context/toasts/useToast';
import type { Card } from '../types/kanban';

interface LinkExistingCardModalProps {
  boardId: number;
  currentCardId: number;
  onClose: () => void;
  onLinked: () => void;
}

export function LinkExistingCardModal({
  boardId,
  currentCardId,
  onClose,
  onLinked,
}: LinkExistingCardModalProps) {
  const [search, setSearch] = useState('');
  const [cards, setCards] = useState<Card[]>([]);
  const [selectedCardId, setSelectedCardId] = useState<number | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const { getBoard, createCardLink } = useApi();
  const { withLoader } = useLoader();
  const { addNotification } = useToast();

  useEffect(() => {
    const fetchCards = async () => {
      try {
        const board = await getBoard(boardId);
        const allCards: Card[] = [];
        for (const list of board.lists) {
          allCards.push(...list.cards);
        }
        // Filter out the current card
        setCards(allCards.filter((c) => c.id !== currentCardId));
      } catch (err) {
        console.error(err);
        addNotification({
          type: 'error',
          title: 'Error',
          message: 'Failed to load board cards',
          duration: 5000,
        });
      }
    };
    fetchCards();
  }, [getBoard, boardId, currentCardId, addNotification]);

  const filteredCards = cards.filter(
    (c) =>
      c.name.toLowerCase().includes(search.toLowerCase()) ||
      String(c.id_short || c.id).includes(search)
  );

  const handleLink = async () => {
    if (!selectedCardId) return;
    setIsSubmitting(true);
    try {
      await withLoader(() => createCardLink(currentCardId, selectedCardId), 'Linking card...');
      addNotification({
        type: 'success',
        title: 'Card Linked',
        message: 'Card linked successfully.',
        duration: 3000,
      });
      onLinked();
      onClose();
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'Failed to link card';
      addNotification({
        type: 'error',
        title: 'Error',
        message: msg,
        duration: 5000,
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
      <div className="bg-gray-800 rounded-xl shadow-2xl w-full max-w-md mx-4 border border-gray-700">
        <div className="p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-bold text-white">Link Existing Card</h2>
            <button onClick={onClose} className="text-gray-400 hover:text-white transition-colors">
              <span className="w-5 h-5">
                <CloseIcon />
              </span>
            </button>
          </div>

          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full bg-gray-700 border border-gray-600 rounded-lg px-3 py-2 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 mb-3"
            placeholder="Search cards by name or ID..."
            autoFocus
          />

          <div className="max-h-60 overflow-y-auto space-y-1 scrollbar-custom">
            {filteredCards.length === 0 && (
              <p className="text-gray-500 text-sm text-center py-4">No cards found</p>
            )}
            {filteredCards.map((c) => (
              <button
                key={c.id}
                onClick={() => setSelectedCardId(c.id)}
                className={`w-full text-left px-3 py-2 rounded-lg transition-colors flex items-center gap-2 ${
                  selectedCardId === c.id
                    ? 'bg-blue-600 text-white'
                    : 'text-gray-300 hover:bg-gray-700'
                }`}
              >
                <span className="text-gray-500 text-xs">#{c.id_short || c.id}</span>
                <span className="truncate">{c.name}</span>
                <span className="ml-auto text-xs text-gray-500">{c.list_name}</span>
              </button>
            ))}
          </div>

          <div className="flex justify-end gap-3 pt-4 mt-2 border-t border-gray-700">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-gray-300 hover:text-white bg-gray-700 hover:bg-gray-600 rounded-lg transition-colors"
            >
              Cancel
            </button>
            <button
              onClick={handleLink}
              disabled={!selectedCardId || isSubmitting}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-800 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
            >
              {isSubmitting ? 'Linking...' : 'Link Card'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
