import React, { useState, useEffect } from 'react';
import { Icons } from './IconSet';

interface ShopItem {
  id: string;
  name: string;
  description: string;
  price: number;
  currency: string;
  stock: number;
  type: 'item' | 'service';
  materialsRequired?: string;
}

interface ShopManagementModalProps {
  isOpen: boolean;
  onClose: () => void;
  projectId: string;
  onUpdate: () => void;
}

const ShopManagementModal: React.FC<ShopManagementModalProps> = ({
  isOpen,
  onClose,
  projectId,
  onUpdate
}) => {
  const [items, setItems] = useState<ShopItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [showAddForm, setShowAddForm] = useState(false);
  const [editingItem, setEditingItem] = useState<ShopItem | null>(null);
  const [error, setError] = useState<string | null>(null);

  // Form state for add/edit
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    price: '',
    currency: 'Gold',
    stock: '',
    type: 'item' as 'item' | 'service',
    materialsRequired: ''
  });

  useEffect(() => {
    if (isOpen && projectId) {
      loadShopItems();
    }
  }, [isOpen, projectId]);

  const loadShopItems = async () => {
    try {
      setLoading(true);
      const response = await fetch(`https://vollidioten.ceraticsoft.de/api/projects/${projectId}/shop`);
      if (response.ok) {
        const data = await response.json();
        setItems(data);
      } else {
        setError('Fehler beim Laden der Shop-Artikel');
      }
    } catch (err) {
      console.error('Error loading shop items:', err);
      setError('Netzwerkfehler');
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      description: '',
      price: '',
      currency: 'Gold',
      stock: '',
      type: 'item',
      materialsRequired: ''
    });
    setEditingItem(null);
    setShowAddForm(false);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.name.trim() || !formData.description.trim() || !formData.price) {
      setError('Name, Beschreibung und Preis sind erforderlich');
      return;
    }

    try {
      setLoading(true);
      setError(null);

      const itemData = {
        name: formData.name.trim(),
        description: formData.description.trim(),
        price: parseFloat(formData.price),
        currency: formData.currency,
        stock: parseInt(formData.stock) || 0,
        type: formData.type,
        materialsRequired: formData.materialsRequired.trim() || undefined
      };

      let response;
      if (editingItem) {
        // Update existing item
        response = await fetch(`https://vollidioten.ceraticsoft.de/api/projects/${projectId}/shop/${editingItem.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify(itemData)
        });
      } else {
        // Add new item
        response = await fetch(`https://vollidioten.ceraticsoft.de/api/projects/${projectId}/shop`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify(itemData)
        });
      }

      if (response.ok) {
        await loadShopItems();
        resetForm();
        onUpdate();
      } else {
        const errorData = await response.json();
        setError(errorData.error || 'Fehler beim Speichern');
      }
    } catch (err) {
      console.error('Error saving shop item:', err);
      setError('Netzwerkfehler');
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (item: ShopItem) => {
    setFormData({
      name: item.name,
      description: item.description,
      price: item.price.toString(),
      currency: item.currency,
      stock: item.stock.toString(),
      type: item.type,
      materialsRequired: item.materialsRequired || ''
    });
    setEditingItem(item);
    setShowAddForm(true);
  };

  const handleDelete = async (itemId: string) => {
    if (!confirm('Artikel wirklich löschen?')) return;

    try {
      setLoading(true);
      const response = await fetch(`https://vollidioten.ceraticsoft.de/api/projects/${projectId}/shop/${itemId}`, {
        method: 'DELETE',
        credentials: 'include'
      });

      if (response.ok) {
        await loadShopItems();
        onUpdate();
      } else {
        setError('Fehler beim Löschen');
      }
    } catch (err) {
      console.error('Error deleting shop item:', err);
      setError('Netzwerkfehler');
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-in fade-in duration-200">
      <div className="bg-surface border border-border rounded-xl w-full max-w-4xl shadow-2xl flex flex-col max-h-[90vh]">
        <div className="p-4 border-b border-border flex justify-between items-center bg-surfaceHighlight/20">
          <h3 className="font-bold text-textMain flex items-center gap-2">
            <Icons.ShoppingBag className="w-5 h-5" />
            Shop verwalten
          </h3>
          <button onClick={onClose} className="text-textMuted hover:text-white transition-colors text-xl leading-none">&times;</button>
        </div>

        <div className="p-6 flex-1 overflow-y-auto">
          {/* Add/Edit Form */}
          {showAddForm && (
            <div className="bg-surfaceHighlight/30 border border-border rounded-lg p-4 mb-6">
              <h4 className="font-semibold text-textMain mb-4">
                {editingItem ? 'Artikel bearbeiten' : 'Neuen Artikel hinzufügen'}
              </h4>

              <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-textMain mb-1">Name *</label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({...formData, name: e.target.value})}
                    className="w-full bg-[#0b0b0d] border border-border rounded p-2 text-sm"
                    required
                  />
                </div>

                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-textMain mb-1">Beschreibung *</label>
                  <textarea
                    value={formData.description}
                    onChange={(e) => setFormData({...formData, description: e.target.value})}
                    className="w-full h-20 bg-[#0b0b0d] border border-border rounded p-2 text-sm"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-textMain mb-1">Preis *</label>
                  <input
                    type="number"
                    step="0.01"
                    value={formData.price}
                    onChange={(e) => setFormData({...formData, price: e.target.value})}
                    className="w-full bg-[#0b0b0d] border border-border rounded p-2 text-sm"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-textMain mb-1">Währung</label>
                  <select
                    value={formData.currency}
                    onChange={(e) => setFormData({...formData, currency: e.target.value})}
                    className="w-full bg-[#0b0b0d] border border-border rounded p-2 text-sm"
                  >
                    <option value="Gold">Gold</option>
                    <option value="Diamonds">Diamanten</option>
                    <option value="Credits">Credits</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-textMain mb-1">Bestand</label>
                  <input
                    type="number"
                    value={formData.stock}
                    onChange={(e) => setFormData({...formData, stock: e.target.value})}
                    className="w-full bg-[#0b0b0d] border border-border rounded p-2 text-sm"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-textMain mb-1">Typ</label>
                  <select
                    value={formData.type}
                    onChange={(e) => setFormData({...formData, type: e.target.value as 'item' | 'service'})}
                    className="w-full bg-[#0b0b0d] border border-border rounded p-2 text-sm"
                  >
                    <option value="item">Produkt</option>
                    <option value="service">Dienstleistung</option>
                  </select>
                </div>

                {formData.type === 'service' && (
                  <div className="md:col-span-2">
                    <label className="block text-sm font-medium text-textMain mb-1">Materialanforderungen</label>
                    <input
                      type="text"
                      value={formData.materialsRequired}
                      onChange={(e) => setFormData({...formData, materialsRequired: e.target.value})}
                      className="w-full bg-[#0b0b0d] border border-border rounded p-2 text-sm"
                      placeholder="z.B. Kunde stellt Steinziegel"
                    />
                  </div>
                )}

                <div className="md:col-span-2 flex gap-2 pt-2">
                  <button
                    type="submit"
                    disabled={loading}
                    className="bg-accentInfo hover:bg-accentInfo/90 text-white px-4 py-2 rounded text-sm font-medium disabled:opacity-50"
                  >
                    {loading ? 'Speichere...' : (editingItem ? 'Aktualisieren' : 'Hinzufügen')}
                  </button>
                  <button
                    type="button"
                    onClick={resetForm}
                    className="bg-surfaceHighlight hover:bg-white/10 px-4 py-2 rounded text-sm"
                  >
                    Abbrechen
                  </button>
                </div>
              </form>
            </div>
          )}

          {/* Error Display */}
          {error && (
            <div className="bg-red-500/10 border border-red-500/20 rounded-lg p-4 mb-6">
              <p className="text-red-400">{error}</p>
            </div>
          )}

          {/* Header with Add Button */}
          <div className="flex justify-between items-center mb-6">
            <h4 className="text-lg font-semibold text-textMain">Artikel ({items.length})</h4>
            <button
              onClick={() => setShowAddForm(true)}
              className="bg-accentInfo hover:bg-accentInfo/90 text-white px-4 py-2 rounded text-sm font-medium flex items-center gap-2"
            >
              <Icons.ShoppingBag className="w-4 h-4" />
              Artikel hinzufügen
            </button>
          </div>

          {/* Items List */}
          {loading ? (
            <div className="flex justify-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-accentInfo"></div>
            </div>
          ) : items.length === 0 ? (
            <div className="text-center py-8 text-textMuted">
              <p>Noch keine Artikel im Shop.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {items.map((item) => (
                <div key={item.id} className="bg-surfaceHighlight/30 border border-border rounded-lg p-4">
                  <div className="flex justify-between items-start mb-2">
                    <h5 className="font-medium text-textMain">{item.name}</h5>
                    <span className={`text-xs px-2 py-1 rounded ${
                      item.type === 'service' ? 'bg-amber-500/20 text-amber-400' : 'bg-blue-500/20 text-blue-400'
                    }`}>
                      {item.type === 'service' ? 'Dienst' : 'Produkt'}
                    </span>
                  </div>

                  <p className="text-sm text-textMuted mb-3 line-clamp-2">{item.description}</p>

                  <div className="flex items-center justify-between mb-3">
                    <div className="text-sm font-medium text-accentInfo">
                      {item.price} {item.currency}
                    </div>
                    <div className="text-xs text-textMuted">
                      Bestand: {item.stock}
                    </div>
                  </div>

                  {item.materialsRequired && (
                    <div className="text-xs text-amber-400 bg-amber-500/10 p-2 rounded mb-3">
                      Material: {item.materialsRequired}
                    </div>
                  )}

                  <div className="flex gap-2">
                    <button
                      onClick={() => handleEdit(item)}
                      className="flex-1 bg-accentInfo hover:bg-accentInfo/90 text-white px-3 py-1 rounded text-xs font-medium"
                    >
                      Bearbeiten
                    </button>
                    <button
                      onClick={() => handleDelete(item.id)}
                      className="flex-1 bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded text-xs font-medium"
                    >
                      Löschen
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="p-4 border-t border-border flex justify-end">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-textMuted hover:text-white transition-colors"
          >
            Schließen
          </button>
        </div>
      </div>
    </div>
  );
};

export default ShopManagementModal;
