"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 DriverDetailPage({
  params,
}: {
  params: { id: string };
}) {
  const router = useRouter();
  const { data: session } = useSession();
  const [driver, setDriver] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phoneNumber: "",
    vehiclePlate: "",
    vehicleModel: "",
    available: true,
  });

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

  const fetchDriver = async () => {
    try {
      const res = await fetch(`/api/drivers/${params.id}`);
      const data = await res.json();
      setDriver(data.driver);
      setFormData({
        name: data.driver.name,
        email: data.driver.email,
        phoneNumber: data.driver.phoneNumber || "",
        vehiclePlate: data.driver.vehiclePlate || "",
        vehicleModel: data.driver.vehicleModel || "",
        available: data.driver.available,
      });
    } catch (error) {
      console.error("Fetch error:", error);
    } finally {
      setLoading(false);
    }
  };

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

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

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

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

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

      if (res.ok) {
        router.push("/dashboard/drivers");
      } 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-gray-300">Lädt...</p>
          </div>
        </div>
      </div>
    );
  }

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

            <div className="bg-gradient-to-br from-gray-800 to-gray-900 rounded-xl shadow-2xl p-8 mb-6 border border-gray-700">
              <div className="flex justify-between items-start mb-6">
                <div>
                  <h1 className="text-3xl font-bold text-white">
                    {driver.name}
                  </h1>
                  <p className="text-gray-400 mt-1">{driver.email}</p>
                </div>
                <div className="flex gap-3">
                  <button
                    onClick={() => setEditing(!editing)}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold"
                  >
                    {editing ? "Abbrechen" : "Bearbeiten"}
                  </button>
                  <button
                    onClick={handleDelete}
                    className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 font-semibold"
                  >
                    Löschen
                  </button>
                </div>
              </div>

              {editing ? (
                <form onSubmit={handleUpdate} className="space-y-6">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Name
                      </label>
                      <input
                        type="text"
                        value={formData.name}
                        onChange={(e) =>
                          setFormData({ ...formData, name: e.target.value })
                        }
                        className="w-full px-4 py-2 bg-gray-700 border border-gray-600 text-white rounded-lg"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        E-Mail
                      </label>
                      <input
                        type="email"
                        value={formData.email}
                        onChange={(e) =>
                          setFormData({ ...formData, email: e.target.value })
                        }
                        className="w-full px-4 py-2 bg-gray-700 border border-gray-600 text-white rounded-lg"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Telefon
                      </label>
                      <input
                        type="tel"
                        value={formData.phoneNumber}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            phoneNumber: e.target.value,
                          })
                        }
                        className="w-full px-4 py-2 bg-gray-700 border border-gray-600 text-white rounded-lg"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Kennzeichen
                      </label>
                      <input
                        type="text"
                        value={formData.vehiclePlate}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            vehiclePlate: e.target.value,
                          })
                        }
                        className="w-full px-4 py-2 bg-gray-700 border border-gray-600 text-white rounded-lg"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Fahrzeug
                      </label>
                      <input
                        type="text"
                        value={formData.vehicleModel}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            vehicleModel: e.target.value,
                          })
                        }
                        className="w-full px-4 py-2 bg-gray-700 border border-gray-600 text-white rounded-lg"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-2">
                        Verfügbarkeit
                      </label>
                      <select
                        value={formData.available ? "true" : "false"}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            available: e.target.value === "true",
                          })
                        }
                        className="w-full px-4 py-2 bg-gray-700 border border-gray-600 text-white rounded-lg"
                      >
                        <option value="true">Verfügbar</option>
                        <option value="false">Nicht verfügbar</option>
                      </select>
                    </div>
                  </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"
                  >
                    Speichern
                  </button>
                </form>
              ) : (
                <div className="grid grid-cols-2 gap-6">
                  <div>
                    <p className="text-sm text-gray-400">Telefon</p>
                    <p className="text-lg font-semibold text-white">
                      {driver.phoneNumber || "Nicht angegeben"}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-400">Kennzeichen</p>
                    <p className="text-lg font-semibold text-white">
                      {driver.vehiclePlate || "Nicht angegeben"}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-400">Fahrzeug</p>
                    <p className="text-lg font-semibold text-white">
                      {driver.vehicleModel || "Nicht angegeben"}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-400">Verfügbarkeit</p>
                    <p className="text-lg font-semibold text-white">
                      {driver.available ? "✓ Verfügbar" : "✗ Nicht verfügbar"}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-400">Erstellt</p>
                    <p className="text-lg font-semibold text-white">
                      {formatDate(driver.createdAt)}
                    </p>
                  </div>
                </div>
              )}
            </div>

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