"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { Star } from "lucide-react";
import { apiGet, apiPatch } from "@/lib/api/client";
import { useAuthStore } from "@/lib/stores/auth.store";
import { formatNumber } from "@/lib/format";
import { Button } from "@/components/ui/button";
import { LabeledField } from "@/components/ui/labeled-field";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

type CafeReview = {
  id: string;
  authorName: string;
  rating: number;
  comment: string | null;
  ownerReply: string | null;
  createdAt: string;
};

function Stars({ rating }: { rating: number }) {
  return (
    <span className="inline-flex gap-0.5 text-amber-500" aria-label={`${rating}/5`}>
      {[1, 2, 3, 4, 5].map((n) => (
        <Star
          key={n}
          className="h-4 w-4"
          fill={n <= rating ? "currentColor" : "none"}
          strokeWidth={n <= rating ? 0 : 1.5}
        />
      ))}
    </span>
  );
}

export function ReviewsScreen() {
  const t = useTranslations("reviews");
  const tCommon = useTranslations("common");
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const queryClient = useQueryClient();

  const [replyingId, setReplyingId] = useState<string | null>(null);
  const [replyText, setReplyText] = useState("");

  const { data: reviews = [], isLoading } = useQuery({
    queryKey: ["cafe-reviews", cafeId],
    queryFn: () => apiGet<CafeReview[]>(`/api/cafes/${cafeId}/reviews?pageSize=50`),
    enabled: !!cafeId,
  });

  const replyMutation = useMutation({
    mutationFn: ({ reviewId, reply }: { reviewId: string; reply: string }) =>
      apiPatch<CafeReview>(`/api/cafes/${cafeId}/reviews/${reviewId}/reply`, { reply }),
    onSuccess: () => {
      setReplyingId(null);
      setReplyText("");
      queryClient.invalidateQueries({ queryKey: ["cafe-reviews", cafeId] });
    },
  });

  if (!cafeId) return null;

  const avg =
    reviews.length > 0
      ? Math.round((reviews.reduce((s, r) => s + r.rating, 0) / reviews.length) * 10) / 10
      : 0;

  return (
    <div className="space-y-4">
      <h2 className="text-xl font-bold">{t("title")}</h2>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t("summary")}</CardTitle>
        </CardHeader>
        <CardContent className="flex flex-wrap items-center gap-4">
          <div>
            <p className="text-3xl font-bold text-primary">{formatNumber(avg)}</p>
            <Stars rating={Math.round(avg)} />
          </div>
          <p className="text-sm text-muted-foreground">
            {t("reviewCount", { count: formatNumber(reviews.length) })}
          </p>
        </CardContent>
      </Card>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">{tCommon("loading")}</p>
      ) : reviews.length === 0 ? (
        <p className="text-sm text-muted-foreground">{t("empty")}</p>
      ) : (
        <ul className="space-y-3">
          {reviews.map((review) => (
            <li key={review.id}>
              <Card>
                <CardContent className="space-y-3 pt-6">
                  <div className="flex flex-wrap items-start justify-between gap-2">
                    <div>
                      <p className="font-medium">{review.authorName}</p>
                      <Stars rating={review.rating} />
                    </div>
                    <time className="text-xs text-muted-foreground">
                      {new Date(review.createdAt).toLocaleDateString("fa-IR")}
                    </time>
                  </div>
                  {review.comment && (
                    <p className="text-sm text-foreground">{review.comment}</p>
                  )}
                  {review.ownerReply ? (
                    <div className="rounded-md bg-muted p-3 text-sm">
                      <p className="mb-1 font-medium text-primary">{t("ownerReply")}</p>
                      <p>{review.ownerReply}</p>
                    </div>
                  ) : replyingId === review.id ? (
                    <div className="space-y-2">
                      <LabeledField label={t("reply")} htmlFor={`reply-${review.id}`}>
                        <textarea
                          id={`reply-${review.id}`}
                          className="min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                          value={replyText}
                          onChange={(e) => setReplyText(e.target.value)}
                        />
                      </LabeledField>
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          disabled={!replyText.trim() || replyMutation.isPending}
                          onClick={() =>
                            replyMutation.mutate({ reviewId: review.id, reply: replyText })
                          }
                        >
                          {tCommon("save")}
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            setReplyingId(null);
                            setReplyText("");
                          }}
                        >
                          {tCommon("cancel")}
                        </Button>
                      </div>
                    </div>
                  ) : (
                    <Button size="sm" variant="outline" onClick={() => setReplyingId(review.id)}>
                      {t("reply")}
                    </Button>
                  )}
                </CardContent>
              </Card>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
