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

interface CreateProjectModalProps {
  isOpen: boolean;
  onClose: () => void;
  onCreate: (projectData: {
    title: string;
    description: string;
    category: Project['category'];
  }) => Promise<void>;
  linkedPlayerName?: string | null;
}

const CreateProjectModal: React.FC<CreateProjectModalProps> = ({ isOpen, onClose, onCreate, linkedPlayerName }) => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [category, setCategory] = useState<Project['category']>('Enterprise');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const categories = [
    { value: 'Enterprise', label: 'Unternehmen', description: 'Firmen, Läden, Dienstleistungen' },
    { value: 'Story Arc', label: 'Story Arc', description: 'Rollenspiel-Handlung, Quest' },
    { value: 'Faction', label: 'Fraktion', description: 'Gruppe, Gilde, Organisation' },
    { value: 'Black Market', label: 'Schwarzmarkt', description: 'Illegale Geschäfte (Vorsicht!)' },
  ];

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

    if (!title.trim() || !description.trim()) {
      setError('Titel und Beschreibung sind erforderlich');
      return;
    }

    try {
      setLoading(true);
      setError(null);
      await onCreate({ title: title.trim(), description: description.trim(), category });
      onClose();
      // Reset form
      setTitle('');
      setDescription('');
      setCategory('Enterprise');
    } catch (err) {
      console.error('Error creating project:', err);
      setError('Fehler beim Erstellen des Projekts');
    } 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-2xl 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" />
            Neues Unternehmen erstellen
          </h3>
          <button onClick={onClose} className="text-textMuted hover:text-white transition-colors text-xl leading-none">&times;</button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 flex-1 overflow-y-auto">
          <div className="space-y-6">
            {/* Title */}
            <div>
              <label className="block text-sm font-medium text-textMain mb-2">
                Name des Unternehmens *
              </label>
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="w-full bg-[#0b0b0d] border border-border rounded-lg p-3 text-sm text-gray-300 focus:border-accentInfo focus:outline-none"
                placeholder="z.B. DrKButz Architektur GmbH"
                required
                maxLength={100}
              />
            </div>

            {/* Category */}
            <div>
              <label className="block text-sm font-medium text-textMain mb-3">
                Kategorie *
              </label>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                {categories.map((cat) => (
                  <label
                    key={cat.value}
                    className={`p-3 border rounded-lg cursor-pointer transition-all ${
                      category === cat.value
                        ? 'border-accentInfo bg-accentInfo/10'
                        : 'border-border hover:border-accentInfo/50'
                    }`}
                  >
                    <input
                      type="radio"
                      name="category"
                      value={cat.value}
                      checked={category === cat.value}
                      onChange={(e) => setCategory(e.target.value as Project['category'])}
                      className="sr-only"
                    />
                    <div className="flex items-start gap-3">
                      <div className={`w-4 h-4 rounded-full border-2 mt-0.5 ${
                        category === cat.value
                          ? 'border-accentInfo bg-accentInfo'
                          : 'border-textMuted'
                      }`}>
                        {category === cat.value && (
                          <div className="w-full h-full rounded-full bg-white scale-50"></div>
                        )}
                      </div>
                      <div>
                        <div className="font-medium text-textMain">{cat.label}</div>
                        <div className="text-xs text-textMuted mt-1">{cat.description}</div>
                      </div>
                    </div>
                  </label>
                ))}
              </div>
            </div>

            {/* Description */}
            <div>
              <label className="block text-sm font-medium text-textMain mb-2">
                Beschreibung *
              </label>
              <textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                className="w-full h-32 bg-[#0b0b0d] border border-border rounded-lg p-3 text-sm text-gray-300 focus:border-accentInfo focus:outline-none resize-none"
                placeholder="Beschreiben Sie Ihr Unternehmen, seine Dienstleistungen und Ziele..."
                required
                maxLength={1000}
              />
              <div className="text-xs text-textMuted mt-1">
                {description.length}/1000 Zeichen
              </div>
            </div>

            {/* Linked Player Info */}
            {linkedPlayerName && (
              <div className="bg-green-500/10 border border-green-500/20 rounded-lg p-4">
                <div className="flex items-start gap-3">
                  <Icons.Users className="w-5 h-5 text-green-400 mt-0.5" />
                  <div>
                    <h4 className="text-sm font-medium text-green-400 mb-1">Projekt-Ersteller</h4>
                    <p className="text-sm text-green-300">
                      Dieses Unternehmen wird im Namen von <strong>{linkedPlayerName}</strong> erstellt.
                    </p>
                  </div>
                </div>
              </div>
            )}

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

            {/* Info */}
            <div className="bg-blue-500/10 border border-blue-500/20 rounded-lg p-4">
              <div className="flex items-start gap-3">
                <Icons.Crown className="w-5 h-5 text-blue-400 mt-0.5" />
                <div>
                  <h4 className="text-sm font-medium text-blue-400 mb-1">Wichtige Hinweise</h4>
                  <ul className="text-xs text-blue-300 space-y-1">
                    <li>• Sie sind automatisch der Eigentümer und können das Unternehmen jederzeit bearbeiten</li>
                    <li>• Das Unternehmen startet mit dem Status "aktiv"</li>
                    <li>• Sie können später Mitarbeiter hinzufügen und einen Shop einrichten</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>

          <div className="flex justify-end gap-3 mt-8 pt-6 border-t border-border">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-textMuted hover:text-white transition-colors"
              disabled={loading}
            >
              Abbrechen
            </button>
            <button
              type="submit"
              disabled={loading || !title.trim() || !description.trim()}
              className="px-6 py-2 text-sm font-medium bg-accentInfo hover:bg-accentInfo/90 text-white rounded transition-colors shadow-lg shadow-accentInfo/20 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {loading ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                  Erstelle...
                </>
              ) : (
                <>
                  <Icons.ShoppingBag className="w-4 h-4" />
                  Unternehmen erstellen
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default CreateProjectModal;
