import { useState, useRef } from 'react';
import { X, Upload, User } from 'lucide-react';
import { Button, Input, Spinner } from '@/shared/components/ui';
import { api } from '@/shared/lib/api';
import { ImageCropModal } from './image-crop-modal';
import type { Character } from '@/shared/types';

interface EditCharacterModalProps {
  campaignId: string;
  character: Character;
  onClose: () => void;
  onUpdated: (updated: Character) => void;
}

export function EditCharacterModal({ campaignId, character, onClose, onUpdated }: EditCharacterModalProps) {
  const [name, setName] = useState(character.name);
  const [type, setType] = useState<'PC' | 'NPC'>(character.type);
  const [level, setLevel] = useState(character.level);
  const [hpMax, setHpMax] = useState(character.hpMax);
  const [avatarUrl, setAvatarUrl] = useState(character.avatarUrl || '');
  const [ancestry, setAncestry] = useState(character.ancestryId || '');
  const [heritage, setHeritage] = useState(character.heritageId || '');
  const [characterClass, setCharacterClass] = useState(character.classId || '');
  const [background, setBackground] = useState(character.backgroundId || '');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');

  // Image crop state
  const [showImageCrop, setShowImageCrop] = useState(false);
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleImageSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      if (file.size > 10 * 1024 * 1024) {
        setError('Bilddatei ist zu groß. Maximum 10MB.');
        return;
      }

      if (!file.type.startsWith('image/')) {
        setError('Bitte eine gültige Bilddatei auswählen.');
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        setSelectedImage(e.target?.result as string);
        setShowImageCrop(true);
      };
      reader.readAsDataURL(file);
    }
    // Reset input so same file can be selected again
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleImageCropComplete = (croppedImage: string) => {
    setAvatarUrl(croppedImage);
    setShowImageCrop(false);
    setSelectedImage(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) {
      setError('Name ist erforderlich');
      return;
    }

    setIsSubmitting(true);
    setError('');

    try {
      const updated = await api.updateCharacter(campaignId, character.id, {
        name: name.trim(),
        type,
        level,
        hpMax,
        avatarUrl: avatarUrl || undefined,
        ancestryId: ancestry.trim() || undefined,
        heritageId: heritage.trim() || undefined,
        classId: characterClass.trim() || undefined,
        backgroundId: background.trim() || undefined,
      });
      onUpdated(updated);
      onClose();
    } catch (err) {
      setError('Fehler beim Speichern');
      console.error('Failed to update character:', err);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <>
      <div className="fixed inset-0 z-50 flex items-center justify-center">
        <div className="absolute inset-0 bg-black/50" onClick={onClose} />
        <div className="relative bg-bg-primary border border-border rounded-xl p-6 w-full max-w-md mx-4 shadow-xl max-h-[90vh] overflow-y-auto">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-lg font-semibold text-text-primary">Charakter bearbeiten</h2>
            <Button variant="ghost" size="icon" onClick={onClose}>
              <X className="h-5 w-5" />
            </Button>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Avatar Upload */}
            <div>
              <label className="block text-sm font-medium text-text-primary mb-2">
                Avatar
              </label>
              <div className="flex items-center gap-4">
                <div className="relative">
                  {avatarUrl ? (
                    <img
                      src={avatarUrl}
                      alt={name}
                      className="w-16 h-16 rounded-full object-cover border-2 border-border"
                    />
                  ) : (
                    <div className="w-16 h-16 rounded-full bg-bg-tertiary border-2 border-border flex items-center justify-center">
                      <User className="h-8 w-8 text-text-muted" />
                    </div>
                  )}
                </div>
                <div className="flex-1 space-y-2">
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    onChange={handleImageSelect}
                    className="hidden"
                    id="avatar-upload"
                  />
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => fileInputRef.current?.click()}
                    className="w-full"
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    Bild hochladen
                  </Button>
                  {avatarUrl && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => setAvatarUrl('')}
                      className="w-full text-text-secondary"
                    >
                      Entfernen
                    </Button>
                  )}
                </div>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">
                Name *
              </label>
              <Input
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Name des Charakters"
              />
            </div>

            {/* Ancestry & Heritage */}
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  Abstammung
                </label>
                <Input
                  value={ancestry}
                  onChange={(e) => setAncestry(e.target.value)}
                  placeholder="z.B. Human"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  Erbe
                </label>
                <Input
                  value={heritage}
                  onChange={(e) => setHeritage(e.target.value)}
                  placeholder="z.B. Skilled Human"
                />
              </div>
            </div>

            {/* Class & Background */}
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  Klasse
                </label>
                <Input
                  value={characterClass}
                  onChange={(e) => setCharacterClass(e.target.value)}
                  placeholder="z.B. Fighter"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  Hintergrund
                </label>
                <Input
                  value={background}
                  onChange={(e) => setBackground(e.target.value)}
                  placeholder="z.B. Warrior"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">
                Typ
              </label>
              <div className="flex gap-2">
                <Button
                  type="button"
                  variant={type === 'PC' ? 'default' : 'outline'}
                  onClick={() => setType('PC')}
                  className="flex-1"
                >
                  Spielercharakter
                </Button>
                <Button
                  type="button"
                  variant={type === 'NPC' ? 'default' : 'outline'}
                  onClick={() => setType('NPC')}
                  className="flex-1"
                >
                  NPC
                </Button>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  Level
                </label>
                <Input
                  type="number"
                  min={1}
                  max={20}
                  value={level}
                  onChange={(e) => setLevel(parseInt(e.target.value) || 1)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-text-primary mb-1.5">
                  Max HP
                </label>
                <Input
                  type="number"
                  min={1}
                  value={hpMax}
                  onChange={(e) => setHpMax(parseInt(e.target.value) || 1)}
                />
              </div>
            </div>

            {error && (
              <p className="text-sm text-red-500">{error}</p>
            )}

            <div className="flex justify-end gap-3 pt-2">
              <Button type="button" variant="outline" onClick={onClose}>
                Abbrechen
              </Button>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting ? <Spinner size="sm" /> : 'Speichern'}
              </Button>
            </div>
          </form>
        </div>
      </div>

      {/* Image Crop Modal */}
      {showImageCrop && selectedImage && (
        <ImageCropModal
          image={selectedImage}
          onComplete={handleImageCropComplete}
          onCancel={() => {
            setShowImageCrop(false);
            setSelectedImage(null);
          }}
          loading={isSubmitting}
        />
      )}
    </>
  );
}
