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

interface ReviewSubmissionPageProps {
  token: string;
}

export default function ReviewSubmissionPage({ token }: ReviewSubmissionPageProps) {
  const [rating, setRating] = useState<number | null>(null);
  const [hoverRating, setHoverRating] = useState<number | null>(null);
  const [comment, setComment] = useState("");
  const [submitResult, setSubmitResult] = useState<{ success: boolean; message: string } | null>(null);

  // Fetch booking info by token
  const bookingQuery = useQuery({
    ...queryClient.cancellation.getBookingByToken.queryOptions({ input: { token } }),
    staleTime: 0,
  });

  const isCompleted = bookingQuery.data?.status === "completed";

  const submitMutation = useMutation({
    ...queryClient.reviews.submitReview.mutationOptions(),
    onSuccess: () => {
      setSubmitResult({ success: true, message: "Danke für deine Bewertung! Sie wird nach Prüfung veröffentlicht." });
    },
    onError: (error: any) => {
      setSubmitResult({ success: false, message: error?.message || "Ein Fehler ist aufgetreten." });
    },
  });

  const canSubmit = useMemo(() => {
    return !!rating && comment.trim().length >= 10 && isCompleted && !submitMutation.isPending;
  }, [rating, comment, isCompleted, submitMutation.isPending]);

  const handleSubmit = () => {
    setSubmitResult(null);
    const trimmedComment = comment.trim();
    if (rating == null || rating < 1 || rating > 5) {
      setSubmitResult({ success: false, message: "Bitte wähle eine Bewertung von 1 bis 5 Sternen." });
      return;
    }
    if (trimmedComment.length < 10) {
      setSubmitResult({ success: false, message: "Der Kommentar muss mindestens 10 Zeichen enthalten." });
      return;
    }
    if (!isCompleted) {
      setSubmitResult({ success: false, message: "Bewertungen sind nur für abgeschlossene Termine möglich." });
      return;
    }
    submitMutation.mutate({ bookingToken: token, rating, comment: trimmedComment });
  };

  if (bookingQuery.isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-pink-50 to-purple-50 flex items-center justify-center p-4">
        <div className="bg-white p-8 rounded-lg shadow-lg max-w-md w-full">
          <div className="flex items-center justify-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-pink-500"></div>
            <span className="ml-3 text-gray-600">Lade Buchung...</span>
          </div>
        </div>
      </div>
    );
  }

  if (bookingQuery.error || !bookingQuery.data) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-pink-50 to-purple-50 flex items-center justify-center p-4">
        <div className="bg-white p-8 rounded-lg shadow-lg max-w-md w-full text-center">
          <div className="w-16 h-16 mx-auto mb-4 bg-red-100 rounded-full flex items-center justify-center">
            <svg className="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </div>
          <h2 className="text-xl font-bold text-gray-900 mb-2">Link nicht verfügbar</h2>
          <p className="text-gray-600 mb-4">Dieser Link ist ungültig oder abgelaufen.</p>
          <a href="/" className="inline-flex items-center px-4 py-2 bg-pink-600 text-white rounded-lg hover:bg-pink-700 transition-colors">Zur Startseite</a>
        </div>
      </div>
    );
  }

  // Guard: Only allow reviews for completed bookings
  if (!isCompleted) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-pink-50 to-purple-50 flex items-center justify-center p-4">
        <div className="bg-white p-8 rounded-lg shadow-lg max-w-lg w-full">
          <div className="text-center">
            <img src="/assets/stargilnails_logo_transparent_112.png" alt="Stargil Nails Logo" className="w-16 h-16 mx-auto mb-4 object-contain" />
            <h1 className="text-2xl font-bold text-gray-900">Bewertung abgeben</h1>
            <p className="text-gray-600 mt-2">Bewertungen sind nur für abgeschlossene Termine möglich.</p>
            <div className="mt-6">
              <a href="/" className="inline-flex items-center text-pink-600 hover:text-pink-700 font-medium">
                <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                </svg>
                Zurück zur Startseite
              </a>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const booking = bookingQuery.data;

  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-50 to-purple-50 py-8 px-4">
      <div className="max-w-2xl mx-auto">
        {/* Header */}
        <div className="bg-white rounded-lg shadow-lg p-6 mb-6">
          <div className="flex items-center justify-between mb-4">
            <img src="/assets/stargilnails_logo_transparent_112.png" alt="Stargil Nails Logo" className="w-16 h-16 object-contain" />
            <span className="px-4 py-2 rounded-full text-sm font-semibold bg-pink-100 text-pink-800">⭐ Bewertung</span>
          </div>
          <h1 className="text-2xl font-bold text-gray-900">Bewertung abgeben</h1>
          <p className="text-gray-600 mt-1">Teile deine Erfahrung mit uns – das hilft anderen Kundinnen!</p>
        </div>

        {/* Booking Details */}
        <div className="bg-white rounded-lg shadow-lg p-6 mb-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
            <svg className="w-5 h-5 mr-2 text-pink-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
            Termin-Details
          </h2>
          <div className="space-y-3 text-sm">
            <div className="flex justify-between py-2 border-b border-gray-100">
              <span className="text-gray-600">Datum:</span>
              <span className="font-medium text-gray-900">{booking.formattedDate}</span>
            </div>
            <div className="flex justify-between py-2 border-b border-gray-100">
              <span className="text-gray-600">Uhrzeit:</span>
              <span className="font-medium text-gray-900">{booking.appointmentTime} Uhr</span>
            </div>
            <div className="flex justify-between py-2 border-b border-gray-100">
              <span className="text-gray-600">Behandlung:</span>
              <span className="font-medium text-gray-900">
                {booking.treatments && booking.treatments.length > 0
                  ? booking.treatments.map((t: any) => t.name).join(", ")
                  : "Keine Behandlung"}
              </span>
            </div>
            <div className="flex justify-between py-2">
              <span className="text-gray-600">Name:</span>
              <span className="font-medium text-gray-900">{booking.customerName}</span>
            </div>
          </div>
        </div>

        {/* Result Banner */}
        {submitResult && (
          <div className={`mb-6 p-4 rounded-lg ${submitResult.success ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'}`}>
            <p className={submitResult.success ? 'text-green-800' : 'text-red-800'}>{submitResult.message}</p>
          </div>
        )}

        {/* Review Form */}
        <div className="bg-white rounded-lg shadow-lg p-6 mb-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Deine Bewertung</h2>

          {/* Stars */}
          <div className="flex items-center mb-4">
            {[1,2,3,4,5].map((star) => {
              const isActive = (hoverRating ?? rating ?? 0) >= star;
              return (
                <button
                  key={star}
                  type="button"
                  className={`text-3xl mr-2 transition-colors ${isActive ? 'text-yellow-400' : 'text-gray-300'} ${submitMutation.isPending ? 'cursor-not-allowed' : 'cursor-pointer'}`}
                  onMouseEnter={() => !submitMutation.isPending && setHoverRating(star)}
                  onMouseLeave={() => !submitMutation.isPending && setHoverRating(null)}
                  onClick={() => !submitMutation.isPending && setRating(star)}
                  aria-label={`${star} Sterne`}
                >
                  ★
                </button>
              );
            })}
          </div>
          {!rating && <p className="text-sm text-red-600 mb-2">Bitte wähle eine Bewertung von 1 bis 5 Sternen.</p>}

          {/* Comment */}
          <label className="block text-sm font-medium text-gray-700 mb-1">Kommentar</label>
          <textarea
            value={comment}
            onChange={(e) => setComment(e.target.value)}
            placeholder="Teile deine Erfahrung mit uns..."
            rows={5}
            className="w-full p-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500"
            disabled={submitMutation.isPending || !!submitResult?.success}
          />
          {comment.trim().length > 0 && comment.trim().length < 10 && (
            <p className="text-sm text-red-600 mt-1">Der Kommentar muss mindestens 10 Zeichen enthalten.</p>
          )}

          {/* Submit */}
          <button
            onClick={handleSubmit}
            disabled={!canSubmit || !!submitResult?.success}
            className="mt-4 w-full bg-pink-600 text-white py-3 px-4 rounded-lg font-medium hover:bg-pink-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {submitMutation.isPending ? 'Sende Bewertung...' : 'Bewertung absenden'}
          </button>
          <p className="text-xs text-gray-500 mt-3">Mit dem Absenden stimmst du der Veröffentlichung deiner Bewertung nach Prüfung zu.</p>
        </div>

        {/* Footer */}
        <div className="text-center">
          <a href="/" className="inline-flex items-center text-pink-600 hover:text-pink-700 font-medium">
            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
            </svg>
            Zurück zur Startseite
          </a>
        </div>
      </div>
    </div>
  );
}


