"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { formatDate } from "@/lib/date-utils";
import DashboardSidebar from "@/components/DashboardSidebar";
import { useSession } from "next-auth/react";

export default function PhotoboxDetailPage({
  params,
}: {
  params: { id: string };
}) {
  const router = useRouter();
  const { data: session } = useSession();
  const [photobox, setPhotobox] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(false);
  const [formData, setFormData] = useState({
    status: "",
    description: "",
  });

  useEffect(() => {
    fetchPhotobox();
  }, [params.id]);

  const fetchPhotobox = async () => {
    try {
      const res = await fetch(`/api/photoboxes/${params.id}`);
      const data = await res.json();
      setPhotobox(data.photobox);
      setFormData({
        status: data.photobox.status,
        description: data.photobox.description || "",
      });
    } catch (error) {
      console.error("Fetch error:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      const res = await fetch(`/api/photoboxes/${params.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (res.ok) {
        setEditing(false);
        fetchPhotobox();
      } else {
        alert("Fehler beim Aktualisieren");
      }
    } catch (error) {
      console.error("Update error:", error);
      alert("Fehler beim Aktualisieren");
    }
  };

  const handleDelete = async () => {
    if (!confirm("Möchten Sie diese Fotobox wirklich löschen?")) return;

    try {
      const res = await fetch(`/api/photoboxes/${params.id}`, {
        method: "DELETE",
      });

      if (res.ok) {
        router.push("/dashboard/photoboxes");
      } else {
        alert("Fehler beim Löschen");
      }
    } catch (error) {
      console.error("Delete error:", error);
      alert("Fehler beim Löschen");
    }
  };

  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>
    );
  }

  if (!photobox) {
    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">Fotobox nicht gefunden</p>
          </div>
        </div>
      </div>
    );
  }

  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;
  };

  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-5xl mx-auto">
            <button
              onClick={() => router.back()}
              className="mb-6 text-red-400 hover:text-red-300 font-medium transition-colors"
            >
              ← Zurück
            </button>

            <div className="bg-gradient-to-br from-gray-800 to-gray-900 border border-gray-700 rounded-xl shadow-lg p-8 mb-6">
              <div className="flex justify-between items-start mb-6">
                <div>
                  <h1 className="text-3xl font-bold text-white">
                    {getModelLabel(photobox.model)}
                  </h1>
                  <p className="text-gray-400 mt-1">
                    SN: {photobox.serialNumber}
                  </p>
                </div>
                <div className="flex gap-3">
                  <button
                    onClick={() => setEditing(!editing)}
                    className="px-4 py-2 bg-gradient-to-r from-blue-600 to-cyan-600 text-white rounded-lg hover:from-blue-700 hover:to-cyan-700 font-semibold shadow-lg transition-all"
                  >
                    {editing ? "Abbrechen" : "Bearbeiten"}
                  </button>
                  <button
                    onClick={handleDelete}
                    className="px-4 py-2 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"
                  >
                    Löschen
                  </button>
                </div>
              </div>

              {editing ? (
                <form onSubmit={handleUpdate} className="space-y-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      Status
                    </label>
                    <select
                      value={formData.status}
                      onChange={(e) =>
                        setFormData({ ...formData, status: 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="AVAILABLE">Verfügbar</option>
                      <option value="IN_USE">Im Einsatz</option>
                      <option value="MAINTENANCE">Wartung</option>
                      <option value="DAMAGED">Defekt</option>
                    </select>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      Beschreibung
                    </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={4}
                    />
                  </div>

                  <button
                    type="submit"
                    className="px-6 py-3 bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-lg hover:from-green-700 hover:to-emerald-700 font-semibold shadow-lg transition-all"
                  >
                    Speichern
                  </button>
                </form>
              ) : (
                <div className="grid grid-cols-2 gap-6">
                  <div>
                    <p className="text-sm text-gray-400">Standort</p>
                    <p className="text-lg font-semibold text-white">
                      {photobox.location.name}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-400">Status</p>
                    <p className="text-lg font-semibold text-white">
                      {photobox.status}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-400">Erstellt</p>
                    <p className="text-lg font-semibold text-white">
                      {formatDate(photobox.createdAt)}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-400">Letzte Wartung</p>
                    <p className="text-lg font-semibold text-white">
                      {photobox.lastMaintenance
                        ? formatDate(photobox.lastMaintenance)
                        : "Keine"}
                    </p>
                  </div>
                  {photobox.description && (
                    <div className="col-span-2">
                      <p className="text-sm text-gray-400">Beschreibung</p>
                      <p className="text-lg text-white">
                        {photobox.description}
                      </p>
                    </div>
                  )}
                </div>
              )}
            </div>

            <div className="bg-gradient-to-br from-gray-800 to-gray-900 border border-gray-700 rounded-xl shadow-lg p-8">
              <h2 className="text-2xl font-bold text-white mb-6">
                Buchungen ({photobox.bookings.length})
              </h2>
              {photobox.bookings.length > 0 ? (
                <div className="space-y-3">
                  {photobox.bookings.map((booking: any) => (
                    <div
                      key={booking.id}
                      onClick={() =>
                        router.push(`/dashboard/bookings/${booking.id}`)
                      }
                      className="p-4 bg-gray-700/50 border border-gray-600 rounded-lg hover:bg-gray-700 hover:border-gray-500 cursor-pointer transition-all"
                    >
                      <div className="flex justify-between items-center">
                        <div>
                          <p className="font-semibold text-white">
                            {booking.bookingNumber}
                          </p>
                          <p className="text-sm text-gray-400">
                            {booking.customerName}
                          </p>
                        </div>
                        <div className="text-right">
                          <p className="font-medium text-white">
                            {formatDate(booking.eventDate)}
                          </p>
                          <p className="text-sm text-gray-400">
                            {booking.status}
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-gray-400">Keine Buchungen vorhanden</p>
              )}
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}
