import React, { useState } from 'react';
import { X, Award, Plus, Check, AlertCircle } from 'lucide-react';
import { apiFetch } from '../api/client';
import { getRandomSkillColor } from '../utils/colors';

export default function SkillsModal({ skills, user, onClose, onRefreshSkills, onRefreshUser }) {
  const [newSkillName, setNewSkillName] = useState('');
  const [newSkillDesc, setNewSkillDesc] = useState('');
  const [newSkillColor, setNewSkillColor] = useState(getRandomSkillColor());

  const [creating, setCreating] = useState(false);
  const [savingUserSkills, setSavingUserSkills] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  // Selected skill IDs for logged in user
  const [selectedSkillIds, setSelectedSkillIds] = useState(
    user?.skills ? user.skills.map(s => s.id) : []
  );

  const handleCreateSkill = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    if (!newSkillName.trim()) {
      setError('Bitte gib einen Namen für die Fähigkeit an.');
      return;
    }

    setCreating(true);
    try {
      await apiFetch('/skills/', {
        method: 'POST',
        body: JSON.stringify({
          name: newSkillName.trim(),
          description: newSkillDesc.trim(),
          color: newSkillColor
        })
      });
      setNewSkillName('');
      setNewSkillDesc('');
      setNewSkillColor(getRandomSkillColor());
      setSuccess('Fähigkeit erfolgreich angelegt!');
      onRefreshSkills();
    } catch (err) {
      setError(err.message || 'Erstellen der Fähigkeit fehlgeschlagen.');
    } finally {
      setCreating(false);
    }
  };

  const toggleUserSkill = (skillId) => {
    if (selectedSkillIds.includes(skillId)) {
      setSelectedSkillIds(selectedSkillIds.filter(id => id !== skillId));
    } else {
      setSelectedSkillIds([...selectedSkillIds, skillId]);
    }
  };

  const handleSaveMySkills = async () => {
    setError('');
    setSuccess('');
    setSavingUserSkills(true);
    try {
      await apiFetch('/users/me/', {
        method: 'PATCH',
        body: JSON.stringify({
          skill_ids: selectedSkillIds
        })
      });
      setSuccess('Deine Fähigkeiten wurden aktualisiert!');
      onRefreshUser();
    } catch (err) {
      setError(err.message || 'Speichern der Fähigkeiten fehlgeschlagen.');
    } finally {
      setSavingUserSkills(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm overflow-y-auto">
      <div className="glass-panel w-full max-w-xl rounded-2xl border border-slate-800 p-6 shadow-2xl relative my-8">
        <button
          onClick={onClose}
          className="absolute top-4 right-4 p-2 text-slate-400 hover:text-white rounded-lg transition"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="flex items-center gap-3 mb-6">
          <div className="w-10 h-10 rounded-xl bg-amber-500/10 text-amber-400 border border-amber-500/20 flex items-center justify-center">
            <Award className="w-5 h-5" />
          </div>
          <div>
            <h3 className="font-bold text-lg text-white">Fähigkeiten & Qualifikationen</h3>
            <p className="text-xs text-slate-400">Verwalte verfügbare Fähigkeiten und ordne sie deinem Profil zu</p>
          </div>
        </div>

        {error && (
          <div className="mb-4 p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 text-xs flex items-center gap-2">
            <AlertCircle className="w-4 h-4 shrink-0" />
            <span>{error}</span>
          </div>
        )}

        {success && (
          <div className="mb-4 p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs flex items-center gap-2">
            <Check className="w-4 h-4 shrink-0" />
            <span>{success}</span>
          </div>
        )}

        {/* Section 1: Select My Skills */}
        <div className="space-y-3 mb-6">
          <h4 className="font-bold text-xs text-slate-300 uppercase tracking-wider">
            Meine Qualifikationen ankreuzen
          </h4>

          {skills.length === 0 ? (
            <p className="text-xs text-slate-500 italic">Noch keine Fähigkeiten im System vorhanden.</p>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
              {skills.map((skill) => {
                const isSelected = selectedSkillIds.includes(skill.id);
                return (
                  <div
                    key={skill.id}
                    onClick={() => toggleUserSkill(skill.id)}
                    style={{ borderColor: isSelected ? skill.color : 'rgba(255,255,255,0.06)' }}
                    className={`p-3 rounded-xl border cursor-pointer transition flex items-center justify-between ${
                      isSelected ? 'bg-slate-900' : 'bg-slate-950/60 hover:bg-slate-900/40'
                    }`}
                  >
                    <div className="flex items-center gap-2">
                      <span className="w-3 h-3 rounded-full" style={{ backgroundColor: skill.color }}></span>
                      <span className="text-xs font-semibold text-white">{skill.name}</span>
                    </div>
                    {isSelected && <Check className="w-4 h-4" style={{ color: skill.color }} />}
                  </div>
                );
              })}
            </div>
          )}

          <div className="flex justify-end pt-1">
            <button
              onClick={handleSaveMySkills}
              disabled={savingUserSkills}
              className="px-4 py-2 rounded-xl text-xs font-bold bg-amber-500/20 hover:bg-amber-500/30 text-amber-300 border border-amber-500/30 transition"
            >
              {savingUserSkills ? 'Speichern...' : 'Meine Fähigkeiten speichern'}
            </button>
          </div>
        </div>

        {/* Section 2: Create New Skill */}
        <form onSubmit={handleCreateSkill} className="border-t border-slate-800 pt-5 space-y-3">
          <h4 className="font-bold text-xs text-blue-400 uppercase tracking-wider flex items-center gap-1.5">
            <Plus className="w-4 h-4" /> Neue Fähigkeit im System erstellen
          </h4>

          <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
            <input
              type="text"
              required
              placeholder="Name (z.B. Ersthelfer, Führerschein B)"
              value={newSkillName}
              onChange={(e) => setNewSkillName(e.target.value)}
              className="sm:col-span-2 px-3 py-2 rounded-xl bg-slate-900 border border-slate-800 text-white text-xs"
            />
            <div className="flex items-center gap-2">
              <input
                type="color"
                value={newSkillColor}
                onChange={(e) => setNewSkillColor(e.target.value)}
                className="w-9 h-9 rounded-xl border-0 cursor-pointer bg-slate-900 p-1"
              />
              <span className="text-[11px] text-slate-400">Farbe</span>
            </div>
          </div>

          <input
            type="text"
            placeholder="Beschreibung (optional)"
            value={newSkillDesc}
            onChange={(e) => setNewSkillDesc(e.target.value)}
            className="w-full px-3 py-2 rounded-xl bg-slate-900 border border-slate-800 text-white text-xs"
          />

          <div className="flex justify-end pt-1">
            <button
              type="submit"
              disabled={creating}
              className="px-4 py-2 rounded-xl text-xs font-bold bg-blue-600 hover:bg-blue-500 text-white transition"
            >
              {creating ? 'Erstellen...' : 'Fähigkeit anlegen'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
