import { useState, useRef } from 'react';
import { X, Upload, Image } from 'lucide-react';
import { cn } from '@/shared/lib/utils';

interface UploadMapModalProps {
  onClose: () => void;
  onUpload: (data: {
    name: string;
    gridSizeX: number;
    gridSizeY: number;
    gridOffsetX: number;
    gridOffsetY: number;
    image: File;
  }) => void;
  isLoading?: boolean;
}

export function UploadMapModal({ onClose, onUpload, isLoading }: UploadMapModalProps) {
  const [name, setName] = useState('');
  const [gridSizeX, setGridSizeX] = useState(20);
  const [gridSizeY, setGridSizeY] = useState(20);
  const [gridOffsetX, setGridOffsetX] = useState(0);
  const [gridOffsetY, setGridOffsetY] = useState(0);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedFile(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreview(reader.result as string);
      };
      reader.readAsDataURL(file);

      // Auto-fill name from filename if empty
      if (!name) {
        setName(file.name.replace(/\.[^/.]+$/, ''));
      }
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedFile || !name.trim()) return;

    onUpload({
      name: name.trim(),
      gridSizeX,
      gridSizeY,
      gridOffsetX,
      gridOffsetY,
      image: selectedFile,
    });
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70">
      <div className="bg-bg-secondary border border-border-default rounded-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-border-default">
          <h2 className="text-lg font-semibold text-text-primary">Karte hochladen</h2>
          <button
            onClick={onClose}
            className="p-1 rounded-lg hover:bg-white/10 text-text-secondary transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-4 space-y-4">
          {/* File Upload */}
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-2">
              Kartenbild
            </label>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/png,image/jpeg,image/webp"
              onChange={handleFileSelect}
              className="hidden"
            />
            {preview ? (
              <div className="relative">
                <img
                  src={preview}
                  alt="Preview"
                  className="w-full h-48 object-contain bg-black/30 rounded-lg"
                />
                <button
                  type="button"
                  onClick={() => {
                    setSelectedFile(null);
                    setPreview(null);
                  }}
                  className="absolute top-2 right-2 p-1 rounded-full bg-black/50 hover:bg-black/70 text-white"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>
            ) : (
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="w-full h-48 border-2 border-dashed border-border-default rounded-lg flex flex-col items-center justify-center gap-2 hover:border-primary hover:bg-primary/5 transition-colors"
              >
                <Image className="w-8 h-8 text-text-secondary" />
                <span className="text-sm text-text-secondary">Klicken zum Auswählen</span>
                <span className="text-xs text-text-secondary">PNG, JPG, WebP (max. 10MB)</span>
              </button>
            )}
          </div>

          {/* Name */}
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-2">
              Name
            </label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="z.B. Taverne im Wald"
              className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary placeholder:text-text-secondary focus:outline-none focus:border-primary"
              required
            />
          </div>

          {/* Grid Size */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">
                Grid Spalten (X)
              </label>
              <input
                type="number"
                value={gridSizeX}
                onChange={(e) => setGridSizeX(parseInt(e.target.value) || 1)}
                min={1}
                max={100}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">
                Grid Reihen (Y)
              </label>
              <input
                type="number"
                value={gridSizeY}
                onChange={(e) => setGridSizeY(parseInt(e.target.value) || 1)}
                min={1}
                max={100}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
          </div>

          {/* Grid Offset */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">
                Offset X (px)
              </label>
              <input
                type="number"
                value={gridOffsetX}
                onChange={(e) => setGridOffsetX(parseInt(e.target.value) || 0)}
                min={0}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">
                Offset Y (px)
              </label>
              <input
                type="number"
                value={gridOffsetY}
                onChange={(e) => setGridOffsetY(parseInt(e.target.value) || 0)}
                min={0}
                className="w-full px-3 py-2 bg-bg-tertiary border border-border-default rounded-lg text-text-primary focus:outline-none focus:border-primary"
              />
            </div>
          </div>

          <p className="text-xs text-text-secondary">
            Offset ist nützlich für Karten mit vorgezeichnetem Grid, um das digitale Grid auszurichten.
          </p>

          {/* Actions */}
          <div className="flex gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-2 bg-bg-tertiary text-text-primary rounded-lg hover:bg-white/10 transition-colors"
            >
              Abbrechen
            </button>
            <button
              type="submit"
              disabled={!selectedFile || !name.trim() || isLoading}
              className={cn(
                'flex-1 px-4 py-2 rounded-lg font-medium transition-colors flex items-center justify-center gap-2',
                selectedFile && name.trim() && !isLoading
                  ? 'bg-primary text-white hover:bg-primary/80'
                  : 'bg-primary/50 text-white/50 cursor-not-allowed'
              )}
            >
              {isLoading ? (
                <>
                  <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  Hochladen...
                </>
              ) : (
                <>
                  <Upload className="w-4 h-4" />
                  Hochladen
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
