import React, { useState, useEffect } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { queryClient } from "@/client/rpc-client";

type ReviewStatus = "pending" | "approved" | "rejected";

type Review = {
  id: string;
  bookingId: string;
  customerName: string;
  customerEmail?: string;
  rating: number;
  comment: string;
  status: "pending" | "approved" | "rejected";
  createdAt: string;
  reviewedAt?: string;
  reviewedBy?: string;
};

function getStatusText(status: string) {
  switch (status) {
    case "pending":
      return "Ausstehend";
    case "approved":
      return "Genehmigt";
    case "rejected":
      return "Abgelehnt";
    default:
      return status;
  }
}

function getStatusColor(status: string) {
  switch (status) {
    case "pending":
      return "bg-yellow-100 text-yellow-800";
    case "approved":
      return "bg-green-100 text-green-800";
    case "rejected":
      return "bg-red-100 text-red-800";
    default:
      return "bg-gray-100 text-gray-800";
  }
}

function renderStars(rating: number) {
  const stars = [] as React.ReactElement[];
  for (let i = 1; i <= 5; i++) {
    const filled = i <= rating;
    stars.push(
      <span key={i} className={filled ? "text-yellow-500" : "text-gray-300"}>
        {filled ? "★" : "☆"}
      </span>
    );
  }
  return <div className="text-lg">{stars}</div>;
}

function formatDate(isoString?: string) {
  if (!isoString) return "";
  try {
    return new Date(isoString).toLocaleDateString("de-DE", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return isoString || "";
  }
}

export function AdminReviews() {
  const [activeStatusTab, setActiveStatusTab] = useState<ReviewStatus>("pending");
  const [successMsg, setSuccessMsg] = useState<string>("");
  const [errorMsg, setErrorMsg] = useState<string>("");
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null);

  useEffect(() => {
    if (errorMsg) {
      const t = setTimeout(() => setErrorMsg(""), 5000);
      return () => clearTimeout(t);
    }
  }, [errorMsg]);

  useEffect(() => {
    if (successMsg) {
      const t = setTimeout(() => setSuccessMsg(""), 5000);
      return () => clearTimeout(t);
    }
  }, [successMsg]);

  const sessionId = typeof window !== "undefined" ? localStorage.getItem("sessionId") || "" : "";

  const { data: reviews } = useQuery(
    queryClient.reviews.live.adminListReviews.experimental_liveOptions({
      input: { sessionId, statusFilter: activeStatusTab },
    })
  );

  // Separate queries for quick stats calculation
  const { data: allReviews } = useQuery(
    queryClient.reviews.live.adminListReviews.experimental_liveOptions({
      input: { sessionId },
    })
  );

  const { mutate: approveReview } = useMutation(
    queryClient.reviews.approveReview.mutationOptions({
      onSuccess: () => {
        setSuccessMsg("Bewertung wurde genehmigt.");
      },
      onError: (err: any) => {
        setErrorMsg(err?.message || "Fehler beim Genehmigen der Bewertung.");
      },
    })
  );

  const { mutate: rejectReview } = useMutation(
    queryClient.reviews.rejectReview.mutationOptions({
      onSuccess: () => {
        setSuccessMsg("Bewertung wurde abgelehnt.");
      },
      onError: (err: any) => {
        setErrorMsg(err?.message || "Fehler beim Ablehnen der Bewertung.");
      },
    })
  );

  const { mutate: deleteReview } = useMutation(
    queryClient.reviews.deleteReview.mutationOptions({
      onSuccess: () => {
        setSuccessMsg("Bewertung wurde gelöscht.");
        setShowDeleteConfirm(null);
      },
      onError: (err: any) => {
        setErrorMsg(err?.message || "Fehler beim Löschen der Bewertung.");
        setShowDeleteConfirm(null);
      },
    })
  );

  // Calculate quick stats from full dataset
  const pendingCount = allReviews?.filter((r: Review) => r.status === "pending").length || 0;
  const approvedCount = allReviews?.filter((r: Review) => r.status === "approved").length || 0;
  const rejectedCount = allReviews?.filter((r: Review) => r.status === "rejected").length || 0;
  const totalCount = allReviews?.length || 0;

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      {(successMsg || errorMsg) && (
        <div className="mb-4">
          {errorMsg && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md">
              <div className="flex items-center">
                <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                </svg>
                <span className="font-medium">Fehler:</span>
                <span className="ml-1">{errorMsg}</span>
              </div>
            </div>
          )}
          {successMsg && (
            <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-md">
              <div className="flex items-center">
                <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                </svg>
                <span className="font-medium">Erfolg:</span>
                <span className="ml-1">{successMsg}</span>
              </div>
            </div>
          )}
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-yellow-600">{pendingCount}</div>
          <div className="text-sm text-gray-600">Ausstehend</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-green-600">{approvedCount}</div>
          <div className="text-sm text-gray-600">Genehmigt</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-red-600">{rejectedCount}</div>
          <div className="text-sm text-gray-600">Abgelehnt</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-gray-600">{totalCount}</div>
          <div className="text-sm text-gray-600">Summe</div>
        </div>
      </div>

      <div className="bg-white rounded-lg shadow">
        <div className="border-b border-gray-200">
          <nav className="-mb-px flex space-x-8 px-6">
            <button
              onClick={() => setActiveStatusTab("pending")}
              className={`py-4 px-1 border-b-2 font-medium text-sm ${
                activeStatusTab === "pending"
                  ? "border-pink-500 text-pink-600"
                  : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
              }`}
            >
              ⏳ Ausstehend
            </button>
            <button
              onClick={() => setActiveStatusTab("approved")}
              className={`py-4 px-1 border-b-2 font-medium text-sm ${
                activeStatusTab === "approved"
                  ? "border-pink-500 text-pink-600"
                  : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
              }`}
            >
              ✅ Genehmigt
            </button>
            <button
              onClick={() => setActiveStatusTab("rejected")}
              className={`py-4 px-1 border-b-2 font-medium text-sm ${
                activeStatusTab === "rejected"
                  ? "border-pink-500 text-pink-600"
                  : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
              }`}
            >
              ❌ Abgelehnt
            </button>
          </nav>
        </div>
      </div>

      <div className="bg-white rounded-lg shadow">
        {(!reviews || reviews.length === 0) && (
          <div className="p-8 text-center text-gray-500">
            <div className="text-lg font-medium mb-2">Keine Bewertungen gefunden</div>
            <div className="text-sm">Es liegen aktuell keine Bewertungen in dieser Ansicht vor.</div>
          </div>
        )}

        <div className="divide-y">
          {reviews?.map((review: Review) => (
            <div key={review.id} className="p-6 hover:bg-gray-50 transition-colors">
              <div className="flex items-start justify-between">
                <div>
                  <div className="text-lg font-semibold text-gray-900">{review.customerName}</div>
                  <div className="text-sm text-gray-500">{review.customerEmail || "—"}</div>
                </div>
                <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(review.status)}`}>
                  {getStatusText(review.status)}
                </span>
              </div>

              <div className="mt-2">{renderStars(review.rating)}</div>
              <div className="mt-2 text-gray-700 whitespace-pre-wrap break-words">{review.comment}</div>

              <div className="mt-2 text-sm text-gray-500 space-x-4">
                <span>Buchung: {review.bookingId}</span>
                <span>Eingereicht am: {formatDate(review.createdAt)}</span>
                {review.reviewedAt && <span>Geprüft am: {formatDate(review.reviewedAt)}</span>}
              </div>

              <div className="mt-4 flex items-center gap-2">
                {review.status === "pending" && (
                  <>
                    <button
                      onClick={() => approveReview({ sessionId, id: review.id })}
                      className="bg-green-600 hover:bg-green-700 text-white px-3 py-1.5 rounded-md text-sm"
                    >
                      Genehmigen
                    </button>
                    <button
                      onClick={() => rejectReview({ sessionId, id: review.id })}
                      className="bg-red-600 hover:bg-red-700 text-white px-3 py-1.5 rounded-md text-sm"
                    >
                      Ablehnen
                    </button>
                    <button
                      onClick={() => setShowDeleteConfirm(review.id)}
                      className="bg-gray-600 hover:bg-gray-700 text-white px-3 py-1.5 rounded-md text-sm"
                    >
                      Löschen
                    </button>
                  </>
                )}

                {review.status === "approved" && (
                  <>
                    <button
                      onClick={() => rejectReview({ sessionId, id: review.id })}
                      className="bg-red-600 hover:bg-red-700 text-white px-3 py-1.5 rounded-md text-sm"
                    >
                      Ablehnen
                    </button>
                    <button
                      onClick={() => setShowDeleteConfirm(review.id)}
                      className="bg-gray-600 hover:bg-gray-700 text-white px-3 py-1.5 rounded-md text-sm"
                    >
                      Löschen
                    </button>
                  </>
                )}

                {review.status === "rejected" && (
                  <>
                    <button
                      onClick={() => approveReview({ sessionId, id: review.id })}
                      className="bg-green-600 hover:bg-green-700 text-white px-3 py-1.5 rounded-md text-sm"
                    >
                      Genehmigen
                    </button>
                    <button
                      onClick={() => setShowDeleteConfirm(review.id)}
                      className="bg-gray-600 hover:bg-gray-700 text-white px-3 py-1.5 rounded-md text-sm"
                    >
                      Löschen
                    </button>
                  </>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>

      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 max-w-md w-full mx-4">
            <h3 className="text-lg font-medium text-gray-900 mb-4">Bewertung löschen</h3>
            <p className="text-gray-600 mb-6">
              Bist du sicher, dass du diese Bewertung löschen möchtest? Diese Aktion kann nicht rückgängig gemacht werden.
            </p>
            <div className="flex space-x-3">
              <button
                onClick={() => deleteReview({ sessionId, id: showDeleteConfirm })}
                className="flex-1 bg-red-600 text-white py-2 px-4 rounded-md hover:bg-red-700 transition-colors"
              >
                Ja, löschen
              </button>
              <button
                onClick={() => setShowDeleteConfirm(null)}
                className="flex-1 bg-gray-200 text-gray-800 py-2 px-4 rounded-md hover:bg-gray-300 transition-colors"
              >
                Abbrechen
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}


