import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { MapMarker } from '../types';
import { authService } from '../services/AuthService';
import { DiscordUser } from '../types';

const EditMarker: React.FC = () => {
    const { markerId } = useParams<{ markerId: string }>();
    const navigate = useNavigate();
    const [user, setUser] = useState<DiscordUser | null>(null);
    const [marker, setMarker] = useState<MapMarker | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);

    // Form state
    const [formData, setFormData] = useState({
        name: '',
        type: 'city' as const,
        x_coord: 0,
        z_coord: 0,
        description: '',
        linked_entity_type: '',
        linked_entity_id: '',
        icon_type: 'city' as const,
        color: '#2563eb',
        is_public: true
    });

    // Subscribe to auth changes
    useEffect(() => {
        const unsub = authService.subscribe((currentUser) => {
            setUser(currentUser);
            if (!currentUser?.isAdmin) {
                navigate('/world-map');
            }
        });
        return unsub;
    }, [navigate]);

    // Load marker data
    useEffect(() => {
        const loadMarker = async () => {
            try {
                setLoading(true);
                setError(null);

                const response = await fetch(`/api/map/markers/${markerId}`);
                if (!response.ok) throw new Error('Fehler beim Laden des Markers');
                
                const markerData = await response.json();
                setMarker(markerData);
                
                // Initialize form with marker data
                setFormData({
                    name: markerData.name || '',
                    type: markerData.type || 'city',
                    x_coord: markerData.x_coord || 0,
                    z_coord: markerData.z_coord || 0,
                    description: markerData.description || '',
                    linked_entity_type: markerData.linked_entity_type || '',
                    linked_entity_id: markerData.linked_entity_id || '',
                    icon_type: markerData.icon_type || 'city',
                    color: markerData.color || '#2563eb',
                    is_public: markerData.is_public || true
                });
            } catch (err) {
                console.error('Error loading marker:', err);
                setError(err instanceof Error ? err.message : 'Unbekannter Fehler');
            } finally {
                setLoading(false);
            }
        };

        if (markerId) {
            loadMarker();
        }
    }, [markerId]);

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
        const { name, value, type } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : value
        }));
    };

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

        try {
            const response = await fetch(`/api/map/markers/${markerId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData)
            });

            if (!response.ok) {
                throw new Error('Fehler beim Aktualisieren des Markers');
            }

            setSuccess('Marker erfolgreich aktualisiert');
            // Redirect back to map after 2 seconds
            setTimeout(() => {
                navigate('/world-map');
            }, 2000);
        } catch (err) {
            console.error('Error updating marker:', err);
            setError(err instanceof Error ? err.message : 'Unbekannter Fehler');
        }
    };

    const handleDelete = async () => {
        if (!window.confirm('Sind Sie sicher, dass Sie diesen Marker löschen möchten?')) {
            return;
        }

        try {
            const response = await fetch(`/api/map/markers/${markerId}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                throw new Error('Fehler beim Löschen des Markers');
            }

            setSuccess('Marker erfolgreich gelöscht');
            // Redirect back to map after 2 seconds
            setTimeout(() => {
                navigate('/world-map');
            }, 2000);
        } catch (err) {
            console.error('Error deleting marker:', err);
            setError(err instanceof Error ? err.message : 'Unbekannter Fehler');
        }
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center h-screen">
                <div className="text-textMuted">Lade Marker...</div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="flex items-center justify-center h-screen">
                <div className="text-red-500">Fehler: {error}</div>
            </div>
        );
    }

    if (!marker) {
        return (
            <div className="flex items-center justify-center h-screen">
                <div className="text-textMuted">Marker nicht gefunden</div>
            </div>
        );
    }

    return (
        <div className="max-w-2xl mx-auto p-6">
            <div className="flex items-center justify-between mb-6">
                <h1 className="text-2xl font-bold text-textPrimary">Marker bearbeiten</h1>
                <button
                    onClick={() => navigate('/world-map')}
                    className="px-4 py-2 text-textMuted hover:text-textPrimary transition-colors"
                >
                    ← Zurück zur Karte
                </button>
            </div>

            {success && (
                <div className="mb-6 p-4 bg-green-500/10 border border-green-500/50 text-green-400 rounded-lg">
                    {success}
                </div>
            )}

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

            <form onSubmit={handleSubmit} className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label className="block text-sm font-medium text-textMuted mb-2">
                            Name
                        </label>
                        <input
                            type="text"
                            name="name"
                            value={formData.name}
                            onChange={handleInputChange}
                            className="w-full px-3 py-2 bg-bgSecondary border border-border rounded-lg text-textPrimary focus:outline-none focus:border-accentInfo"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-textMuted mb-2">
                            Typ
                        </label>
                        <select
                            name="type"
                            value={formData.type}
                            onChange={handleInputChange}
                            className="w-full px-3 py-2 bg-bgSecondary border border-border rounded-lg text-textPrimary focus:outline-none focus:border-accentInfo"
                        >
                            <option value="city">Stadt</option>
                            <option value="poi">Sehenswürdigkeit</option>
                            <option value="player_home">Spieler-Haus</option>
                            <option value="waypoint">Wegpunkt</option>
                        </select>
                    </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label className="block text-sm font-medium text-textMuted mb-2">
                            X-Koordinate
                        </label>
                        <input
                            type="number"
                            name="x_coord"
                            value={formData.x_coord}
                            onChange={handleInputChange}
                            className="w-full px-3 py-2 bg-bgSecondary border border-border rounded-lg text-textPrimary focus:outline-none focus:border-accentInfo"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-textMuted mb-2">
                            Z-Koordinate
                        </label>
                        <input
                            type="number"
                            name="z_coord"
                            value={formData.z_coord}
                            onChange={handleInputChange}
                            className="w-full px-3 py-2 bg-bgSecondary border border-border rounded-lg text-textPrimary focus:outline-none focus:border-accentInfo"
                            required
                        />
                    </div>
                </div>

                <div>
                    <label className="block text-sm font-medium text-textMuted mb-2">
                        Beschreibung
                    </label>
                    <textarea
                        name="description"
                        value={formData.description}
                        onChange={handleInputChange}
                        rows={4}
                        className="w-full px-3 py-2 bg-bgSecondary border border-border rounded-lg text-textPrimary focus:outline-none focus:border-accentInfo"
                    />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label className="block text-sm font-medium text-textMuted mb-2">
                            Verknüpftes Entity (optional)
                        </label>
                        <select
                            name="linked_entity_type"
                            value={formData.linked_entity_type}
                            onChange={handleInputChange}
                            className="w-full px-3 py-2 bg-bgSecondary border border-border rounded-lg text-textPrimary focus:outline-none focus:border-accentInfo"
                        >
                            <option value="">Keine Verknüpfung</option>
                            <option value="organization">Organisation</option>
                            <option value="city">Stadt</option>
                            <option value="player">Spieler</option>
                        </select>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-textMuted mb-2">
                            Entity ID
                        </label>
                        <input
                            type="text"
                            name="linked_entity_id"
                            value={formData.linked_entity_id}
                            onChange={handleInputChange}
                            className="w-full px-3 py-2 bg-bgSecondary border border-border rounded-lg text-textPrimary focus:outline-none focus:border-accentInfo"
                            placeholder="z.B. city_12345"
                        />
                    </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label className="block text-sm font-medium text-textMuted mb-2">
                            Icon-Typ
                        </label>
                        <select
                            name="icon_type"
                            value={formData.icon_type}
                            onChange={handleInputChange}
                            className="w-full px-3 py-2 bg-bgSecondary border border-border rounded-lg text-textPrimary focus:outline-none focus:border-accentInfo"
                        >
                            <option value="city">Stadt</option>
                            <option value="flag">Flagge</option>
                            <option value="house">Haus</option>
                            <option value="chest">Kiste</option>
                            <option value="star">Stern</option>
                        </select>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-textMuted mb-2">
                            Farbe
                        </label>
                        <input
                            type="color"
                            name="color"
                            value={formData.color}
                            onChange={handleInputChange}
                            className="w-full px-3 py-2 bg-bgSecondary border border-border rounded-lg text-textPrimary focus:outline-none focus:border-accentInfo"
                        />
                    </div>
                </div>

                <div className="flex items-center gap-4">
                    <label className="flex items-center gap-2 text-textMuted cursor-pointer">
                        <input
                            type="checkbox"
                            name="is_public"
                            checked={formData.is_public}
                            onChange={handleInputChange}
                            className="w-4 h-4 text-accentInfo bg-bgSecondary border-border rounded focus:ring-accentInfo"
                        />
                        Öffentlich sichtbar
                    </label>
                </div>

                <div className="flex gap-4">
                    <button
                        type="submit"
                        className="px-6 py-2 bg-accentInfo text-white rounded-lg hover:bg-accentInfo/90 transition-colors"
                    >
                        Speichern
                    </button>
                    <button
                        type="button"
                        onClick={handleDelete}
                        className="px-6 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
                    >
                        Löschen
                    </button>
                </div>
            </form>
        </div>
    );
};

export default EditMarker;
