/* eslint-disable @next/next/no-img-element -- External card image URLs; next/image migration is out of scope. */
import { useState, useEffect } from 'react';
import { VOCAB } from '../lib/collection-vocabulary.js';
import { Modal, SearchBar, Button } from './ui';

export default function CollectionSelectionModal({
  isOpen,
  onClose,
  cards,
  onAddToCollections,
}) {
  const [collections, setCollections] = useState([]);
  const [selectedCollections, setSelectedCollections] = useState([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  const [prevIsOpen, setPrevIsOpen] = useState(isOpen);
  if (isOpen && !prevIsOpen) {
    setPrevIsOpen(true);
    setSelectedCollections([]);
    setSearchQuery('');
  } else if (!isOpen && prevIsOpen) {
    setPrevIsOpen(false);
  }

  useEffect(() => {
    if (!isOpen) return;
    const fetchCollections = async () => {
      setLoading(true);
      try {
        const response = await fetch('/api/collections?excludeSystem=true');
        if (response.ok) {
          const data = await response.json();
          setCollections(Array.isArray(data) ? data : data.collections || []);
        } else {
          console.error('Failed to fetch collections:', response.status, response.statusText);
          setCollections([]);
        }
      } catch (error) {
        console.error('Error fetching collections:', error);
        setCollections([]);
      } finally {
        setLoading(false);
      }
    };
    fetchCollections();
  }, [isOpen]);

  const handleCollectionToggle = (collectionId) => {
    setSelectedCollections((prev) =>
      prev.includes(collectionId)
        ? prev.filter((id) => id !== collectionId)
        : [...prev, collectionId]
    );
  };

  const getFilteredCollections = () => {
    if (!searchQuery.trim()) return collections;
    return collections.filter(
      (collection) =>
        collection.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        collection.description?.toLowerCase().includes(searchQuery.toLowerCase())
    );
  };

  const handleSelectAll = () => {
    const filteredCollections = getFilteredCollections();
    const allSelected = filteredCollections.every((collection) =>
      selectedCollections.includes(collection.id)
    );
    if (allSelected) {
      setSelectedCollections((prev) =>
        prev.filter((id) => !filteredCollections.some((c) => c.id === id))
      );
    } else {
      const newSelections = filteredCollections
        .filter((collection) => !selectedCollections.includes(collection.id))
        .map((collection) => collection.id);
      setSelectedCollections((prev) => [...prev, ...newSelections]);
    }
  };

  const handleSubmit = async () => {
    if (selectedCollections.length === 0) return;
    setSubmitting(true);
    try {
      const results = [];
      for (const collectionId of selectedCollections) {
        for (const card of cards) {
          const response = await fetch(`/api/collections/${collectionId}/cards`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ cardId: card.id, quantity: 1 }),
          });
          results.push({
            collectionId,
            cardId: card.id,
            success: response.ok,
          });
        }
      }
      onAddToCollections(results, selectedCollections, cards);
      onClose();
    } catch (error) {
      console.error('Error adding cards to collections:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const filteredCollections = getFilteredCollections();
  const allFilteredSelected =
    filteredCollections.length > 0 &&
    filteredCollections.every((collection) =>
      selectedCollections.includes(collection.id)
    );

  return (
    <Modal open={isOpen} onClose={onClose} title={VOCAB.ADD_TO_LISTS} size="lg">
      <div className="flex items-center space-x-3 mb-4">
        <div className="flex -space-x-2">
          {cards.slice(0, 3).map((card) => (
            <div
              key={card.id}
              className="w-12 h-16 rounded border-2 overflow-hidden"
              style={{
                backgroundColor: 'var(--bg-tertiary)',
                borderColor: 'var(--bg-primary)',
              }}
            >
              {card.image_url ? (
                <img
                  src={card.image_url}
                  alt={card.name}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div
                  className="w-full h-full flex items-center justify-center text-xs"
                  style={{ color: 'var(--text-tertiary)' }}
                >
                  No Image
                </div>
              )}
            </div>
          ))}
          {cards.length > 3 && (
            <div
              className="w-12 h-16 rounded border-2 flex items-center justify-center"
              style={{
                backgroundColor: 'var(--bg-tertiary)',
                borderColor: 'var(--bg-primary)',
              }}
            >
              <span className="text-sm font-bold" style={{ color: 'var(--text-secondary)' }}>
                +{cards.length - 3}
              </span>
            </div>
          )}
        </div>
        <div>
          <p className="text-lg font-semibold" style={{ color: 'var(--text-primary)' }}>
            {cards.length} card{cards.length !== 1 ? 's' : ''} selected
          </p>
          <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
            Choose lists to add {cards.length === 1 ? 'this card' : 'these cards'} to
          </p>
        </div>
      </div>

      <div className="mb-4">
        <SearchBar
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          onClear={() => setSearchQuery('')}
          placeholder="Search lists…"
        />
      </div>

      <div className="overflow-y-auto" style={{ maxHeight: '24rem' }}>
        {loading ? (
          <div className="p-8 text-center">
            <div
              className="motion-essential animate-spin rounded-full h-8 w-8 border-b-2 mx-auto mb-2"
              style={{ borderColor: 'var(--accent-ember)' }}
            />
            <p style={{ color: 'var(--text-secondary)' }}>Loading lists...</p>
          </div>
        ) : filteredCollections.length === 0 ? (
          <div className="p-8 text-center">
            <svg
              className="w-12 h-12 mx-auto mb-4"
              style={{ color: 'var(--text-tertiary)' }}
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
              aria-hidden="true"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"
              />
            </svg>
            <p className="mb-2" style={{ color: 'var(--text-secondary)' }}>
              {searchQuery ? 'No lists match your search' : 'No lists found'}
            </p>
            <p className="text-sm" style={{ color: 'var(--text-tertiary)' }}>
              {searchQuery ? 'Try a different search term' : 'Create your first list to get started'}
            </p>
          </div>
        ) : (
          <>
            {filteredCollections.length > 1 && (
              <div
                className="flex items-center justify-between p-3 border-b mb-2"
                style={{ borderColor: 'var(--border)' }}
              >
                <label className="flex items-center space-x-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={allFilteredSelected}
                    onChange={handleSelectAll}
                    className="w-4 h-4 rounded"
                    style={{ accentColor: 'var(--accent-ember)' }}
                  />
                  <span className="font-medium" style={{ color: 'var(--text-primary)' }}>
                    Select All ({filteredCollections.length})
                  </span>
                </label>
              </div>
            )}

            <div className="space-y-2">
              {filteredCollections.map((collection) => {
                const isSelected = selectedCollections.includes(collection.id);
                return (
                  <div
                    key={collection.id}
                    className="p-4 rounded-lg border-2 cursor-pointer"
                    style={{
                      borderColor: isSelected
                        ? 'var(--accent-ember)'
                        : 'var(--border)',
                      backgroundColor: isSelected
                        ? 'rgba(var(--ember-rim-subtle), 0.08)'
                        : 'transparent',
                      transition: 'all var(--motion-duration-default) var(--motion-ease-out)',
                    }}
                    onClick={() => handleCollectionToggle(collection.id)}
                  >
                    <div className="flex items-center space-x-3">
                      <input
                        type="checkbox"
                        checked={isSelected}
                        onChange={() => handleCollectionToggle(collection.id)}
                        className="w-4 h-4 rounded"
                        style={{ accentColor: 'var(--accent-ember)' }}
                      />
                      <div
                        className="w-12 h-12 rounded-lg overflow-hidden flex-shrink-0"
                        style={{ backgroundColor: 'var(--bg-tertiary)' }}
                      >
                        {collection.image ? (
                          <img
                            src={collection.image}
                            alt={collection.name}
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <div
                            className="w-full h-full flex items-center justify-center"
                            style={{ color: 'var(--text-tertiary)' }}
                          >
                            <svg
                              className="w-6 h-6"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                              aria-hidden="true"
                            >
                              <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"
                              />
                            </svg>
                          </div>
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <h3
                          className="font-semibold truncate"
                          style={{ color: 'var(--text-primary)' }}
                        >
                          {collection.name}
                        </h3>
                        {collection.description && (
                          <p
                            className="text-sm truncate"
                            style={{ color: 'var(--text-secondary)' }}
                          >
                            {collection.description}
                          </p>
                        )}
                        <div className="flex items-center space-x-4 mt-1">
                          <span className="text-xs" style={{ color: 'var(--text-tertiary)' }}>
                            {collection.card_count || 0} cards
                          </span>
                          {collection.is_public && (
                            <span
                              className="text-xs px-2 py-1 rounded-full"
                              style={{
                                backgroundColor: 'rgba(34, 197, 94, 0.15)',
                                color: 'rgb(21, 128, 61)',
                              }}
                            >
                              Public
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </>
        )}
      </div>

      <div
        className="flex items-center justify-between mt-6 pt-4 border-t"
        style={{ borderColor: 'var(--border)' }}
      >
        <div className="text-sm" style={{ color: 'var(--text-secondary)' }}>
          {selectedCollections.length > 0 && (
            <span>
              {selectedCollections.length} list
              {selectedCollections.length !== 1 ? 's' : ''} selected
            </span>
          )}
        </div>
        <div className="flex space-x-3">
          <Button variant="secondary" onClick={onClose}>
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={handleSubmit}
            disabled={selectedCollections.length === 0 || submitting}
            loading={submitting}
          >
            {submitting
              ? 'Adding...'
              : `Add to ${selectedCollections.length} List${
                  selectedCollections.length !== 1 ? 's' : ''
                }`}
          </Button>
        </div>
      </div>
    </Modal>
  );
}
