import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { tcgApi } from '../../services/tcgApi';
import type { CreateDeckData } from '../../types';

interface DeckManagerProps {
  isOpen: boolean;
  onClose: () => void;
  deckId?: string; // For editing existing deck
}

const DeckManager: React.FC<DeckManagerProps> = ({
  isOpen,
  onClose,
  deckId
}) => {
  const queryClient = useQueryClient();
  
  const [formData, setFormData] = useState<CreateDeckData>({
    name: '',
    description: '',
    game: 'MTG',
    format: '',
    tags: [],
    color: '#8b5cf6',
    isPublic: false,
  });

  const [selectedTags, setSelectedTags] = useState<string[]>([]);


  const colors = [
    '#8b5cf6', '#3b82f6', '#10b981', '#f59e0b', '#ef4444', 
    '#ec4899', '#6366f1', '#06b6d4', '#84cc16', '#f97316'
  ];

  // Queries
  const { data: existingDeck } = useQuery({
    queryKey: ['deck', deckId],
    queryFn: () => tcgApi.decks.getDeck(deckId!),
    enabled: !!deckId,
  });

  const { data: tags = [] } = useQuery({
    queryKey: ['tags'],
    queryFn: () => tcgApi.tags.getTags(),
  });

  // Mutations
  const createMutation = useMutation({
    mutationFn: tcgApi.decks.createDeck,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['decks'] });
      onClose();
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<CreateDeckData> }) =>
      tcgApi.decks.updateDeck(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['decks'] });
      queryClient.invalidateQueries({ queryKey: ['deck', deckId] });
      onClose();
    },
  });

  // Initialize form with existing deck data
  useEffect(() => {
    if (existingDeck) {
      setFormData({
        name: existingDeck.name,
        description: existingDeck.description || '',
        game: existingDeck.game,
        format: existingDeck.format || '',
        tags: existingDeck.tags,
        color: existingDeck.color || '#8b5cf6',
        isPublic: existingDeck.isPublic,
      });
      setSelectedTags(existingDeck.tags);
    }
  }, [existingDeck]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const submitData = {
      ...formData,
      tags: selectedTags,
    };

    if (deckId && existingDeck) {
      updateMutation.mutate({ id: deckId, data: submitData });
    } else {
      createMutation.mutate(submitData);
    }
  };

  const getGameBadgeColor = (game: string) => {
    switch (game) {
      case 'MTG': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
      case 'POKEMON': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';  
      case 'LORCANA': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
      case 'YUGIOH': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
      default: return 'bg-surface-100 text-surface-800 dark:bg-surface-700 dark:text-surface-300';
    }
  };

  const getFormatOptions = (game: string) => {
    switch (game) {
      case 'MTG':
        return [
          { value: 'standard', label: 'Standard' },
          { value: 'modern', label: 'Modern' },
          { value: 'commander', label: 'Commander' },
          { value: 'pioneer', label: 'Pioneer' },
          { value: 'legacy', label: 'Legacy' },
          { value: 'vintage', label: 'Vintage' },
          { value: 'draft', label: 'Draft' },
          { value: 'sealed', label: 'Sealed' },
        ];
      case 'POKEMON':
        return [
          { value: 'standard', label: 'Standard' },
          { value: 'expanded', label: 'Expanded' },
          { value: 'unlimited', label: 'Unlimited' },
        ];
      case 'LORCANA':
        return [
          { value: 'standard', label: 'Standard' },
          { value: 'constructed', label: 'Constructed' },
        ];
      case 'YUGIOH':
        return [
          { value: 'advanced', label: 'Advanced' },
          { value: 'traditional', label: 'Traditional' },
        ];
      default:
        return [];
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 bg-black/50" onClick={onClose}>
      <div className="fixed bottom-0 left-0 right-0 bg-white dark:bg-surface-900 rounded-t-3xl max-h-[90vh] overflow-hidden animate-slide-up">
        <div className="p-6">
          <div className="w-12 h-1.5 bg-surface-300 dark:bg-surface-600 rounded-full mx-auto mb-6"></div>
          
          {/* Header */}
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-bold text-surface-900 dark:text-white">
              {deckId ? 'Edit Deck' : 'New Deck'}
            </h2>
            <button
              onClick={onClose}
              className="p-2 rounded-xl text-surface-400 hover:text-surface-600 dark:hover:text-surface-300 transition-colors"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          <div className="max-h-[calc(90vh-8rem)] overflow-y-auto">
            <form onSubmit={handleSubmit} className="space-y-6" onClick={(e) => e.stopPropagation()}>
              
              {/* Deck Preview */}
              <div className="p-4 bg-surface-50 dark:bg-surface-800 rounded-2xl">
                <div className="flex items-center space-x-4">
                  <div
                    className="w-12 h-12 rounded-xl flex items-center justify-center text-white text-xl font-semibold shadow-md"
                    style={{ backgroundColor: formData.color }}
                  >
                    🎴
                  </div>
                  <div className="flex-1">
                    <h3 className="font-semibold text-surface-900 dark:text-white">
                      {formData.name || 'Deck Name'}
                    </h3>
                    {formData.description && (
                      <p className="text-sm text-surface-600 dark:text-surface-400">
                        {formData.description}
                      </p>
                    )}
                    <div className="flex items-center space-x-2 mt-2">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${getGameBadgeColor(formData.game)}`}>
                        {formData.game}
                      </span>
                      {formData.format && (
                        <span className="px-2 py-1 bg-surface-100 dark:bg-surface-700 text-surface-700 dark:text-surface-300 rounded-full text-xs font-medium">
                          {formData.format}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              </div>

              {/* Name */}
              <div>
                <label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
                  Deck Name *
                </label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                  placeholder="Enter deck name..."
                  className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
                  required
                />
              </div>

              {/* Description */}
              <div>
                <label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
                  Description
                </label>
                <textarea
                  value={formData.description}
                  onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                  rows={3}
                  placeholder="Describe your deck..."
                  className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white placeholder-surface-500 dark:placeholder-surface-400 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors resize-none"
                />
              </div>

              {/* Game and Format */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
                    Game *
                  </label>
                  <select
                    value={formData.game}
                    onChange={(e) => setFormData(prev => ({ ...prev, game: e.target.value as any, format: '' }))}
                    className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
                  >
                    <option value="MTG">Magic: The Gathering</option>
                    <option value="POKEMON">Pokémon</option>
                    <option value="LORCANA">Disney Lorcana</option>
                    <option value="YUGIOH">Yu-Gi-Oh!</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
                    Format
                  </label>
                  <select
                    value={formData.format}
                    onChange={(e) => setFormData(prev => ({ ...prev, format: e.target.value }))}
                    className="w-full px-4 py-3 bg-surface-50 dark:bg-surface-700 border border-surface-300 dark:border-surface-600 rounded-xl text-surface-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors"
                  >
                    <option value="">Select Format</option>
                    {getFormatOptions(formData.game).map((format) => (
                      <option key={format.value} value={format.value}>
                        {format.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Color */}
              <div>
                <label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
                  Color
                </label>
                <div className="grid grid-cols-5 gap-2">
                  {colors.map((color) => (
                    <button
                      key={color}
                      type="button"
                      onClick={() => setFormData(prev => ({ ...prev, color }))}
                      className={`w-full h-12 rounded-lg transition-all ${
                        formData.color === color ? 'ring-2 ring-surface-400 ring-offset-2 dark:ring-offset-surface-900' : ''
                      }`}
                      style={{ backgroundColor: color }}
                    />
                  ))}
                </div>
              </div>

              {/* Tags */}
              <div>
                <label className="block text-sm font-medium text-surface-700 dark:text-surface-300 mb-2">
                  Tags
                </label>
                <div className="flex flex-wrap gap-2">
                  {tags.map((tag) => (
                    <button
                      key={tag.id}
                      type="button"
                      onClick={() => {
                        setSelectedTags(prev =>
                          prev.includes(tag.id)
                            ? prev.filter(id => id !== tag.id)
                            : [...prev, tag.id]
                        );
                      }}
                      className={`px-3 py-2 rounded-full text-sm font-medium transition-colors ${
                        selectedTags.includes(tag.id)
                          ? 'text-white'
                          : 'bg-surface-100 dark:bg-surface-700 text-surface-700 dark:text-surface-300'
                      }`}
                      style={{
                        backgroundColor: selectedTags.includes(tag.id) ? tag.color : undefined,
                      }}
                    >
                      {tag.name}
                    </button>
                  ))}
                </div>
              </div>

              {/* Privacy Toggle */}
              <div>
                <label className="flex items-center justify-between">
                  <div>
                    <span className="text-sm font-medium text-surface-700 dark:text-surface-300">
                      Public Deck
                    </span>
                    <p className="text-xs text-surface-600 dark:text-surface-400 mt-1">
                      Allow others to view your deck
                    </p>
                  </div>
                  <button
                    type="button"
                    onClick={() => setFormData(prev => ({ ...prev, isPublic: !prev.isPublic }))}
                    className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 ${
                      formData.isPublic ? 'bg-primary-600' : 'bg-surface-200 dark:bg-surface-700'
                    }`}
                  >
                    <span
                      className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                        formData.isPublic ? 'translate-x-5' : 'translate-x-0'
                      }`}
                    />
                  </button>
                </label>
              </div>

              {/* Deck Cards Section */}
              {deckId && existingDeck && (
                <div>
                  <div className="mb-4">
                    <h3 className="text-lg font-semibold text-surface-900 dark:text-white">
                      Deck Cards ({existingDeck.mainboard?.length || 0})
                    </h3>
                  </div>

                  {/* Deck Cards List */}
                  <div className="space-y-2 max-h-48 overflow-y-auto">
                    {existingDeck.mainboard?.map((deckCard, index) => (
                      <div key={index} className="flex items-center justify-between p-3 bg-surface-50 dark:bg-surface-700 rounded-lg">
                        <div className="flex items-center space-x-3">
                          <span className="text-sm font-medium text-surface-900 dark:text-white">
                            {deckCard.quantity}x
                          </span>
                          <span className="text-sm text-surface-700 dark:text-surface-300">
                            {deckCard.card?.name || 'Unknown Card'}
                          </span>
                        </div>
                        <button
                          type="button"
                          onClick={() => {/* Remove card from deck */}}
                          className="p-1 text-red-400 hover:text-red-600 rounded transition-colors"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                          </svg>
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Submit Button */}
              <button
                type="submit"
                disabled={!formData.name.trim() || createMutation.isPending || updateMutation.isPending}
                className="w-full bg-gradient-to-r from-primary-500 to-accent-500 hover:from-primary-600 hover:to-accent-600 disabled:from-surface-400 disabled:to-surface-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl disabled:shadow-none transform hover:-translate-y-0.5 disabled:transform-none"
              >
                {(createMutation.isPending || updateMutation.isPending) ? (
                  <div className="flex items-center justify-center">
                    <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    {deckId ? 'Updating...' : 'Creating...'}
                  </div>
                ) : (
                  deckId ? 'Update Deck' : 'Create Deck'
                )}
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default DeckManager; 