import { useQuery } from "@tanstack/react-query";
import { queryClient } from "@/client/rpc-client";

interface ProfileLandingProps {
  onNavigateToBooking: () => void;
}

function StarRating({ rating }: { rating: number }) {
  return (
    <div className="flex space-x-1">
      {[1, 2, 3, 4, 5].map((star) => (
        <span
          key={star}
          className={star <= rating ? "text-yellow-400" : "text-gray-300"}
        >
          ★
        </span>
      ))}
    </div>
  );
}

function getDayName(dayOfWeek: number): string {
  const days = [
    "Sonntag",
    "Montag",
    "Dienstag",
    "Mittwoch",
    "Donnerstag",
    "Freitag",
    "Samstag",
  ];
  return days[dayOfWeek];
}

function formatDate(date: Date): string {
  return date.toLocaleDateString("de-DE", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  });
}

export function ProfileLanding({ onNavigateToBooking }: ProfileLandingProps) {
  // Data fetching with live queries
  const { data: galleryPhotos = [] } = useQuery(
    queryClient.gallery.live.listPhotos.experimental_liveOptions()
  );
  const sortedPhotos = ([...galleryPhotos] as any[]).sort((a, b) => (a.order || 0) - (b.order || 0));
  const featuredPhoto = sortedPhotos[0];

  const { data: reviews = [] } = useQuery(
    queryClient.reviews.live.listPublishedReviews.experimental_liveOptions()
  );

  const { data: recurringRules = [] } = useQuery(
    queryClient.recurringAvailability.live.listRules.experimental_liveOptions()
  );

  const { data: socialMedia } = useQuery(
    queryClient.social.getSocialMedia.queryOptions()
  );

  // Calculate next 7 days for opening hours
  const getNext7Days = () => {
    const days: Date[] = [];
    const today = new Date();
    for (let i = 0; i < 7; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);
      days.push(date);
    }
    return days;
  };

  const next7Days = getNext7Days();

  return (
    <div className="max-w-6xl mx-auto space-y-12 py-8">
      {/* Hero Section */}
      <div className="bg-gradient-to-r from-pink-500 to-purple-600 rounded-lg shadow-lg p-8 text-white">
        <h1 className="text-4xl md:text-5xl font-bold mb-4">
          Stargirlnails Kiel
        </h1>
        <p className="text-xl mb-2">Professionelles Nageldesign und -Pflege in Kiel</p>
        <p className="text-lg mb-8 opacity-90">
          Lass dich von mir verwöhnen und genieße hochwertige Nail Art und Pflegebehandlungen.
        </p>
        <button
          onClick={onNavigateToBooking}
          className="bg-[#790dc6] text-white py-4 px-8 rounded-lg hover:bg-[#6609ad] text-lg font-semibold shadow-lg transition-colors w-full md:w-auto"
        >
          Termin buchen
        </button>
      </div>

      {/* Social Media Badges */}
      {((socialMedia as any)?.tiktokProfile || (socialMedia as any)?.instagramProfile) && (
        <div className="flex justify-center items-center gap-4">
          {(socialMedia as any)?.instagramProfile && (
            <a
              href={(socialMedia as any).instagramProfile}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 bg-gradient-to-r from-purple-500 via-pink-500 to-orange-500 text-white px-6 py-3 rounded-full hover:shadow-lg transition-all hover:scale-105 font-semibold"
            >
              <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/>
              </svg>
              Instagram
            </a>
          )}
          {(socialMedia as any)?.tiktokProfile && (
            <a
              href={(socialMedia as any).tiktokProfile}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 bg-black text-white px-6 py-3 rounded-full hover:shadow-lg transition-all hover:scale-105 font-semibold"
            >
              <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-5.2 1.74 2.89 2.89 0 0 1 2.31-4.64 2.93 2.93 0 0 1 .88.13V9.4a6.84 6.84 0 0 0-1-.05A6.33 6.33 0 0 0 5 20.1a6.34 6.34 0 0 0 10.86-4.43v-7a8.16 8.16 0 0 0 4.77 1.52v-3.4a4.85 4.85 0 0 1-1-.1z"/>
              </svg>
              TikTok
            </a>
          )}
        </div>
      )}

      {/* Featured Section: Erstes Foto (Reihenfolge 0) */}
      {featuredPhoto && (
        <div className="bg-white rounded-lg shadow-lg p-0 overflow-hidden">
          <img
            src={(featuredPhoto as any).base64Data}
            alt={(featuredPhoto as any).title || "Featured"}
            className="w-full h-auto object-contain"
            loading="eager"
            decoding="async"
          />
          {(featuredPhoto as any).title && (
            <div className="p-4 border-t">
              <h2 className="text-xl font-semibold text-gray-900">{(featuredPhoto as any).title}</h2>
            </div>
          )}
        </div>
      )}

      {/* Photo Gallery Section */}
      <div className="bg-white rounded-lg shadow-lg p-6">
        <h2 className="text-2xl font-bold text-gray-900 mb-6">Unsere Arbeiten</h2>
        {galleryPhotos.length > 0 ? (
          <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
            {(sortedPhotos as typeof galleryPhotos)
              .filter((p) => (featuredPhoto ? (p as any).id !== (featuredPhoto as any).id : true))
              .slice(0, 9)
              .map((photo, index) => (
                <img
                  key={photo.id || index}
                  src={photo.base64Data}
                  alt={photo.title || "Gallery"}
                  loading="lazy"
                  decoding="async"
                  className="w-full h-48 object-cover rounded-lg shadow-md"
                />
              ))}
          </div>
        ) : (
          <p className="text-gray-600 text-center py-8">
            Galerie wird bald aktualisiert
          </p>
        )}
      </div>

      {/* Opening Hours Section */}
      <div className="bg-white rounded-lg shadow-lg p-6">
        <h2 className="text-2xl font-bold text-gray-900 mb-6">
          Öffnungszeiten (Nächste 7 Tage)
        </h2>
        <div className="space-y-2">
          {next7Days.map((date, index) => {
            const dayOfWeek = date.getDay();
            const dayRules = recurringRules.filter(
              (rule) => rule.isActive && rule.dayOfWeek === dayOfWeek
            );
            const sorted = [...dayRules].sort((a, b) =>
              a.startTime.localeCompare(b.startTime)
            );

            return (
              <div
                key={index}
                className={`p-4 rounded-lg ${
                  index % 2 === 0 ? "bg-gray-50" : "bg-white"
                }`}
              >
                <div className="flex justify-between items-center">
                  <span className="font-semibold text-gray-900">
                    {getDayName(dayOfWeek)}, {formatDate(date)}
                  </span>
                  <div className="text-gray-700">
                    {dayRules.length > 0 ? (
                      <div className="space-y-1">
                        {sorted.map((rule) => (
                          <div
                            key={`${rule.dayOfWeek}-${rule.startTime}-${rule.endTime}`}
                          >
                            {rule.startTime} - {rule.endTime} Uhr
                          </div>
                        ))}
                      </div>
                    ) : (
                      <span className="text-gray-500">Geschlossen</span>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Customer Reviews Section */}
      <div className="bg-white rounded-lg shadow-lg p-6">
        <h2 className="text-2xl font-bold text-gray-900 mb-6">
          Kundenbewertungen
        </h2>
        {reviews.length > 0 ? (
          <div className="space-y-4">
            {reviews.slice(0, 10).map((review) => (
              <div
                key={
                  (review as any).id ||
                  (review as any).bookingId ||
                  `${(review as any).createdAt}-${(review as any).customerName}`
                }
                className="bg-gray-50 p-4 rounded-lg shadow-md"
              >
                <div className="flex justify-between items-start mb-2">
                  <div>
                    <h3 className="font-semibold text-gray-900">
                      {review.customerName}
                    </h3>
                    <StarRating rating={review.rating} />
                  </div>
                  <span className="text-sm text-gray-500">
                    {new Date(review.createdAt).toLocaleDateString("de-DE")}
                  </span>
                </div>
                {review.comment && (
                  <p className="text-gray-700 mt-2">{review.comment}</p>
                )}
              </div>
            ))}
          </div>
        ) : (
          <p className="text-gray-600 text-center py-8">
            Noch keine Bewertungen vorhanden
          </p>
        )}
      </div>
    </div>
  );
}
