'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import DashboardSidebar from '@/components/DashboardSidebar';
import { useSession } from 'next-auth/react';

export default function PhotoboxesPage() {
  const router = useRouter();
  const { data: session } = useSession();
  const [photoboxes, setPhotoboxes] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [locations, setLocations] = useState<any[]>([]);

  const [formData, setFormData] = useState({
    locationId: '',
    model: 'VINTAGE_SMILE',
    serialNumber: '',
    description: '',
  });

  useEffect(() => {
    fetchPhotoboxes();
    fetchLocations();
  }, []);

  const fetchPhotoboxes = async () => {
    try {
      const res = await fetch('/api/photoboxes');
      const data = await res.json();
      setPhotoboxes(data.photoboxes || []);
    } catch (error) {
      console.error('Fetch error:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchLocations = async () => {
    try {
      const res = await fetch('/api/locations');
      const data = await res.json();
      setLocations(data.locations || []);
    } catch (error) {
      console.error('Locations fetch error:', error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      const res = await fetch('/api/photoboxes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      if (res.ok) {
        setShowForm(false);
        setFormData({
          locationId: '',
          model: 'VINTAGE_SMILE',
          serialNumber: '',
          description: '',
        });
        fetchPhotoboxes();
      } else {
        alert('Fehler beim Erstellen');
      }
    } catch (error) {
      console.error('Create error:', error);
      alert('Fehler beim Erstellen');
    }
  };

  const getStatusBadge = (status: string) => {
    const styles: Record<string, string> = {
      AVAILABLE: 'bg-green-500/20 text-green-400 border border-green-500/50',
      IN_USE: 'bg-blue-500/20 text-blue-400 border border-blue-500/50',
      MAINTENANCE: 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/50',
      DAMAGED: 'bg-red-500/20 text-red-400 border border-red-500/50',
    };
    return styles[status] || 'bg-gray-500/20 text-gray-400 border border-gray-500/50';
  };

  const getStatusLabel = (status: string) => {
    const labels: Record<string, string> = {
      AVAILABLE: 'Verfügbar',
      IN_USE: 'Im Einsatz',
      MAINTENANCE: 'Wartung',
      DAMAGED: 'Defekt',
    };
    return labels[status] || status;
  };

  const getModelLabel = (model: string) => {
    const labels: Record<string, string> = {
      VINTAGE_SMILE: 'Vintage Smile',
      VINTAGE_PHOTOS: 'Vintage Photos',
      NOSTALGIE: 'Nostalgie',
      MAGIC_MIRROR: 'Magic Mirror',
    };
    return labels[model] || model;
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900">
        <div className="flex">
          <DashboardSidebar user={session?.user} />
          <div className="flex-1 p-8">
            <p className="text-white">Lädt...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900">
      <div className="flex">
        <DashboardSidebar user={session?.user} />
        <main className="flex-1 p-8">
          <div className="max-w-7xl mx-auto">
            <div className="flex justify-between items-center mb-8">
              <div>
                <h1 className="text-3xl font-bold text-white">Fotoboxen</h1>
                <p className="text-gray-400 mt-1">Verwalten Sie alle Fotoboxen</p>
              </div>
              <button
                onClick={() => setShowForm(true)}
                className="px-6 py-3 bg-gradient-to-r from-red-600 to-pink-600 text-white rounded-lg hover:from-red-700 hover:to-pink-700 font-semibold shadow-lg transition-all"
              >
                + Neue Fotobox
              </button>
            </div>

            {showForm && (
              <div className="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center p-4 z-50">
                <div className="bg-gradient-to-br from-gray-800 to-gray-900 border border-gray-700 rounded-xl shadow-2xl max-w-2xl w-full p-8">
                  <h2 className="text-2xl font-bold text-white mb-6">Neue Fotobox erstellen</h2>
                  <form onSubmit={handleSubmit} className="space-y-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Standort
                      </label>
                      <select
                        value={formData.locationId}
                        onChange={(e) => setFormData({ ...formData, locationId: e.target.value })}
                        className="w-full px-4 py-2 bg-gray-700 border border-gray-600 text-white rounded-lg focus:ring-2 focus:ring-red-500"
                        required
                      >
                        <option value="">Standort wählen</option>
                        {locations.map((loc) => (
                          <option key={loc.id} value={loc.id}>
                            {loc.name} ({loc.city})
                          </option>
                        ))}
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Modell
                      </label>
                      <select
                        value={formData.model}
                        onChange={(e) => setFormData({ ...formData, model: e.target.value })}
                        className="w-full px-4 py-2 bg-gray-700 border border-gray-600 text-white rounded-lg focus:ring-2 focus:ring-red-500"
                      >
                        <option value="VINTAGE_SMILE">Vintage Smile</option>
                        <option value="VINTAGE_PHOTOS">Vintage Photos</option>
                        <option value="NOSTALGIE">Nostalgie</option>
                        <option value="MAGIC_MIRROR">Magic Mirror</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Seriennummer
                      </label>
                      <input
                        type="text"
                        value={formData.serialNumber}
                        onChange={(e) => setFormData({ ...formData, serialNumber: e.target.value })}
                        className="w-full px-4 py-2 bg-gray-700 border border-gray-600 text-white rounded-lg focus:ring-2 focus:ring-red-500"
                        required
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Beschreibung (optional)
                      </label>
                      <textarea
                        value={formData.description}
                        onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                        className="w-full px-4 py-2 bg-gray-700 border border-gray-600 text-white rounded-lg focus:ring-2 focus:ring-red-500"
                        rows={3}
                      />
                    </div>

                    <div className="flex gap-4">
                      <button
                        type="button"
                        onClick={() => setShowForm(false)}
                        className="flex-1 px-6 py-3 bg-gray-700 text-gray-300 rounded-lg hover:bg-gray-600 font-semibold transition-colors"
                      >
                        Abbrechen
                      </button>
                      <button
                        type="submit"
                        className="flex-1 px-6 py-3 bg-gradient-to-r from-red-600 to-pink-600 text-white rounded-lg hover:from-red-700 hover:to-pink-700 font-semibold transition-all"
                      >
                        Erstellen
                      </button>
                    </div>
                  </form>
                </div>
              </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {photoboxes.map((box) => (
                <div
                  key={box.id}
                  onClick={() => router.push(`/dashboard/photoboxes/${box.id}`)}
                  className="bg-gradient-to-br from-gray-800 to-gray-900 border border-gray-700 rounded-lg shadow-md p-6 hover:shadow-xl hover:border-gray-600 transition-all cursor-pointer"
                >
                  <div className="flex justify-between items-start mb-4">
                    <div>
                      <h3 className="text-lg font-bold text-white">{getModelLabel(box.model)}</h3>
                      <p className="text-sm text-gray-400">{box.serialNumber}</p>
                    </div>
                    <span className={`px-3 py-1 text-xs font-semibold rounded-full ${getStatusBadge(box.status)}`}>
                      {getStatusLabel(box.status)}
                    </span>
                  </div>
                  
                  <div className="text-sm text-gray-400 space-y-1">
                    <p><span className="font-medium text-gray-300">Standort:</span> {box.location.name}</p>
                    <p><span className="font-medium text-gray-300">Buchungen:</span> {box._count.bookings}</p>
                  </div>
                </div>
              ))}
            </div>

            {photoboxes.length === 0 && (
              <div className="text-center py-12">
                <p className="text-gray-400">Noch keine Fotoboxen vorhanden</p>
              </div>
            )}
          </div>
        </main>
      </div>
    </div>
  );
}
