"use client";

import { useState } from "react";
import Link from "next/link";
import { useLocale, useTranslations } from "next-intl";
import { useQuery } from "@tanstack/react-query";
import {
  fetchPublicCafe,
  fetchPublicCafeReviews,
  type WorkingHours,
} from "@/lib/api/public-discover";
import { resolveMediaUrl } from "@/lib/api/client";
import { formatNumber } from "@/lib/format";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CoffeeAdvisorPanel } from "@/components/discover/coffee-advisor-panel";
import { cn } from "@/lib/utils";

type Props = { slug: string };

const DAY_KEYS: (keyof WorkingHours)[] = ["sat", "sun", "mon", "tue", "wed", "thu", "fri"];

export function PublicCafeDetailScreen({ slug }: Props) {
  const t = useTranslations("discoverPublic");
  const tProfile = useTranslations("discoverProfile");
  const locale = useLocale();
  const [galleryIndex, setGalleryIndex] = useState(0);

  const { data: cafe, isLoading, error } = useQuery({
    queryKey: ["public-cafe", slug],
    queryFn: () => fetchPublicCafe(slug),
  });

  const { data: reviews = [] } = useQuery({
    queryKey: ["public-cafe-reviews", slug],
    queryFn: () => fetchPublicCafeReviews(slug),
    enabled: !!slug,
  });

  const label = (key: string) => {
    const groups = ["themes", "vibes", "occasions", "spaceFeatures", "noiseLevels", "priceTiers"] as const;
    for (const g of groups) {
      try { return tProfile(`${g}.${key}` as "themes.modern"); } catch { /* next */ }
    }
    return key;
  };

  const mapSrc =
    cafe?.address || cafe?.city
      ? `https://map.neshan.org/search?term=${encodeURIComponent(
          [cafe.address, cafe.city].filter(Boolean).join("، ")
        )}`
      : null;

  if (isLoading) {
    return (
      <div className="flex min-h-svh items-center justify-center bg-[#f5f5f4]">
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      </div>
    );
  }

  if (error || !cafe) {
    return (
      <div className="flex min-h-svh flex-col items-center justify-center gap-4 bg-[#f5f5f4] p-6">
        <p className="text-sm text-muted-foreground">{t("notFound")}</p>
        <Button asChild variant="outline">
          <Link href={`/${locale}/discover`}>{t("backToList")}</Link>
        </Button>
      </div>
    );
  }

  // Build image list: gallery first, then cover/logo fallback
  const allImages = cafe.galleryUrls?.length
    ? cafe.galleryUrls
    : [cafe.coverImageUrl ?? cafe.logoUrl].filter(Boolean) as string[];
  const currentImage = resolveMediaUrl(allImages[galleryIndex] ?? null);

  const profile = cafe.discoverProfile;
  const allTags = [
    ...profile.occasions,
    ...profile.vibes,
    ...profile.spaceFeatures,
    ...profile.themes,
  ];

  return (
    <div className="min-h-svh bg-[#f5f5f4]">
      <header className="border-b bg-white px-4 py-4">
        <Link href={`/${locale}/discover`} className="text-sm text-[#0F6E56] hover:underline">
          ← {t("backToList")}
        </Link>
        <div className="mt-2 flex items-center gap-2">
          <h1 className="text-lg font-medium">{cafe.name}</h1>
          {cafe.isOpenNow && (
            <span className="flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-[11px] font-medium text-emerald-700">
              <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
              {t("openNowLabel")}
            </span>
          )}
        </div>
        {cafe.city && (
          <p className="text-sm text-muted-foreground">
            {cafe.city}{cafe.address ? ` — ${cafe.address}` : ""}
          </p>
        )}
      </header>

      <main className="mx-auto max-w-3xl space-y-4 p-4">

        {/* Gallery carousel */}
        {allImages.length > 0 && (
          <div className="space-y-2">
            {currentImage && (
              <div
                className="h-52 w-full rounded-xl bg-cover bg-center"
                style={{ backgroundImage: `url(${currentImage})` }}
              />
            )}
            {allImages.length > 1 && (
              <div className="flex gap-2 overflow-x-auto pb-1">
                {allImages.map((img, i) => {
                  const url = resolveMediaUrl(img);
                  return (
                    <button
                      key={i}
                      type="button"
                      onClick={() => setGalleryIndex(i)}
                      className={cn(
                        "h-14 w-20 shrink-0 rounded-lg bg-cover bg-center transition-all cursor-pointer",
                        i === galleryIndex
                          ? "ring-2 ring-[#0F6E56]"
                          : "opacity-70 hover:opacity-100"
                      )}
                      style={{ backgroundImage: url ? `url(${url})` : undefined }}
                    />
                  );
                })}
              </div>
            )}
          </div>
        )}

        {/* Info card */}
        <Card className="rounded-xl border border-border/80">
          <CardContent className="space-y-3 p-4">
            {cafe.averageRating > 0 && (
              <p className="text-sm font-medium text-[#0F6E56]">
                ★ {formatNumber(cafe.averageRating, locale)} —{" "}
                {t("reviewCount", { count: cafe.reviewCount })}
              </p>
            )}
            {cafe.description && (
              <p className="text-sm leading-relaxed text-muted-foreground">{cafe.description}</p>
            )}
            <div className="flex flex-wrap gap-1">
              {allTags.map((tag) => (
                <Badge key={tag} variant="secondary" className="text-[10px]">
                  {label(tag)}
                </Badge>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Working hours */}
        {cafe.workingHours && <WorkingHoursCard hours={cafe.workingHours} t={t} locale={locale} />}

        {/* Social links */}
        {(cafe.instagramHandle || cafe.websiteUrl) && (
          <Card className="rounded-xl border border-border/80">
            <CardContent className="flex flex-wrap gap-3 p-4">
              {cafe.instagramHandle && (
                <a
                  href={`https://instagram.com/${cafe.instagramHandle}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-1.5 rounded-lg border border-border/80 bg-white px-3 py-2 text-sm transition hover:border-pink-400 cursor-pointer"
                >
                  <svg className="h-4 w-4 text-pink-500" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 2.163c3.204 0 3.584.012 4.85.07 1.366.062 2.633.336 3.608 1.31.975.975 1.249 2.242 1.311 3.608.058 1.265.069 1.645.069 4.849 0 3.205-.011 3.584-.069 4.849-.062 1.366-.336 2.633-1.311 3.608-.975.975-2.242 1.249-3.608 1.311-1.266.058-1.644.069-4.85.069-3.204 0-3.584-.011-4.849-.069-1.366-.062-2.633-.336-3.608-1.311-.975-.975-1.249-2.242-1.311-3.608C2.175 15.584 2.163 15.205 2.163 12c0-3.204.012-3.584.07-4.849.062-1.366.336-2.633 1.311-3.608.975-.974 2.242-1.248 3.608-1.31C8.416 2.175 8.796 2.163 12 2.163zm0-2.163C8.741 0 8.333.014 7.053.072 5.197.157 3.355.673 1.965 2.063.573 3.453.157 5.197.072 7.053.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.085 1.856.5 3.598 1.893 4.99C3.355 23.327 5.197 23.843 7.053 23.928 8.333 23.986 8.741 24 12 24s3.667-.014 4.947-.072c1.856-.085 3.598-.501 4.99-1.893 1.393-1.392 1.808-3.134 1.893-4.99.058-1.28.072-1.689.072-4.948 0-3.259-.014-3.667-.072-4.947-.085-1.856-.5-3.598-1.893-4.99C20.645.673 18.803.157 16.947.072 15.667.014 15.259 0 12 0z"/>
                    <path d="M12 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z"/>
                  </svg>
                  <span>@{cafe.instagramHandle}</span>
                </a>
              )}
              {cafe.websiteUrl && (
                <a
                  href={cafe.websiteUrl.startsWith("http") ? cafe.websiteUrl : `https://${cafe.websiteUrl}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-1.5 rounded-lg border border-border/80 bg-white px-3 py-2 text-sm transition hover:border-blue-400 cursor-pointer"
                >
                  <svg className="h-4 w-4 text-blue-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/>
                    <path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z"/>
                  </svg>
                  <span>{t("websiteLabel")}</span>
                </a>
              )}
            </CardContent>
          </Card>
        )}

        <CoffeeAdvisorPanel cafeSlug={slug} />

        {/* Map */}
        {mapSrc && (
          <Card className="overflow-hidden rounded-xl border border-border/80">
            <CardHeader className="pb-2">
              <CardTitle className="text-base">{t("mapTitle")}</CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <iframe
                title={t("mapTitle")}
                src={mapSrc}
                className="h-64 w-full border-0"
                loading="lazy"
                referrerPolicy="no-referrer-when-downgrade"
              />
              <div className="border-t p-3">
                <a
                  href={mapSrc}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-sm font-medium text-[#0C447C] hover:underline"
                >
                  {t("openInNeshan")}
                </a>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Reviews */}
        {reviews.length > 0 && (
          <Card className="rounded-xl border border-border/80">
            <CardHeader>
              <CardTitle className="text-base">{t("reviewsTitle")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4 p-4 pt-0">
              {reviews.map((r) => (
                <div key={r.id} className="space-y-2 border-b border-border/60 pb-3 last:border-0">
                  <p className="text-sm font-medium">{r.authorName}</p>
                  <p className="text-xs text-amber-600">{"★".repeat(r.rating)}</p>
                  {r.comment && <p className="text-sm text-muted-foreground">{r.comment}</p>}
                  {r.ownerReply && (
                    <p className="rounded-lg bg-[#E1F5EE] px-3 py-2 text-sm text-[#0F6E56]">
                      {t("ownerReply")}: {r.ownerReply}
                    </p>
                  )}
                </div>
              ))}
            </CardContent>
          </Card>
        )}

        <Button asChild className="w-full bg-[#0F6E56]">
          <Link href={`/${locale}/discover`}>{t("exploreMore")}</Link>
        </Button>
      </main>
    </div>
  );
}

// ── Working hours sub-component ───────────────────────────────────────────────

function WorkingHoursCard({
  hours,
  t,
  locale,
}: {
  hours: WorkingHours;
  t: ReturnType<typeof useTranslations<"discoverPublic">>;
  locale: string;
}) {
  // Detect today's day key in Iran time (UTC+3:30)
  const iranOffset = 210; // minutes
  const iranNow = new Date(Date.now() + iranOffset * 60_000);
  const dayIndex = iranNow.getUTCDay(); // 0=Sun ... 6=Sat
  const dayKeyMap: Record<number, keyof WorkingHours> = {
    6: "sat", 0: "sun", 1: "mon", 2: "tue", 3: "wed", 4: "thu", 5: "fri",
  };
  const todayKey = dayKeyMap[dayIndex];

  const DAY_KEYS: (keyof WorkingHours)[] = ["sat", "sun", "mon", "tue", "wed", "thu", "fri"];

  return (
    <Card className="rounded-xl border border-border/80">
      <CardHeader className="pb-2">
        <CardTitle className="text-base">{t("workingHoursTitle")}</CardTitle>
      </CardHeader>
      <CardContent className="p-0 pb-2">
        <table className="w-full text-sm">
          <tbody>
            {DAY_KEYS.map((day) => {
              const schedule = hours[day];
              const isToday = day === todayKey;
              return (
                <tr
                  key={day}
                  className={cn(
                    "border-b border-border/40 last:border-0",
                    isToday && "bg-[#E1F5EE]/60"
                  )}
                >
                  <td className={cn(
                    "px-4 py-2 font-medium",
                    isToday ? "text-[#0F6E56]" : "text-foreground"
                  )}>
                    {t(`days.${day}`)}
                    {isToday && (
                      <span className="ms-1.5 text-[10px] font-normal text-[#0F6E56]">
                        (امروز)
                      </span>
                    )}
                  </td>
                  <td className="px-4 py-2 text-end text-muted-foreground">
                    {!schedule || !schedule.isOpen ? (
                      <span className="text-red-500">{t("closedLabel")}</span>
                    ) : schedule.open && schedule.close ? (
                      <span dir="ltr">{schedule.open} – {schedule.close}</span>
                    ) : (
                      <span className="text-emerald-600">{t("openNowLabel")}</span>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </CardContent>
    </Card>
  );
}
