"use client";

import { useEffect, useState } from "react";
import { Frown, Laugh, Meh, Smile, Star } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { apiRequest, apiUrl } from "@/lib/api";

type GuideRating = {
  id: string;
  reviewerName: string;
  reviewerEmail: string;
  rating: number;
  comment: string;
  createdAt: string;
  relevance: number;
  satisfaction: 1 | 2 | 3 | 4 | 5;
};

type ApiReview = {
  id?: number | string;
  uuid?: string;
  customer_name?: string | null;
  customer_email?: string | null;
  reviewer_name?: string | null;
  reviewer_email?: string | null;
  name?: string | null;
  email?: string | null;
  rating?: number | string | null;
  satisfaction?: number | string | null;
  feedback?: string | null;
  comment?: string | null;
  review?: string | null;
  created_at?: string | null;
  createdAt?: string | null;
  relevance?: number | string | null;
};

type ApiReviewsResponse = {
  data?:
    | ApiReview[]
    | {
        reviews?: ApiReview[] | { data?: ApiReview[] };
      };
};

type GuideRatingListProps = {
  guideUuid: string;
  refreshKey?: number;
};

const satisfactionMeta = {
  1: {
    label: "Very poor",
    icon: Frown,
    className: "bg-red-50 text-red-700 ring-red-100",
  },
  2: {
    label: "Poor",
    icon: Frown,
    className: "bg-orange-50 text-orange-700 ring-orange-100",
  },
  3: {
    label: "Average",
    icon: Meh,
    className: "bg-yellow-50 text-yellow-700 ring-yellow-100",
  },
  4: {
    label: "Good",
    icon: Smile,
    className: "bg-emerald-50 text-emerald-700 ring-emerald-100",
  },
  5: {
    label: "Excellent",
    icon: Laugh,
    className: "bg-sky-50 text-sky-700 ring-sky-100",
  },
} as const;

const sortOptions = [
  { value: "most_relevant", label: "Most relevant" },
  { value: "newest", label: "Newest" },
  { value: "highest_rating", label: "Highest rating" },
  { value: "lowest_rating", label: "Lowest rating" },
];

function toNumber(value: unknown, fallback = 0) {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
}

function toSatisfaction(value: unknown): GuideRating["satisfaction"] {
  const parsed = Math.round(toNumber(value, 3));

  if (parsed >= 1 && parsed <= 5) {
    return parsed as GuideRating["satisfaction"];
  }

  return 3;
}

function getReviewItems(result: ApiReviewsResponse): ApiReview[] {
  if (Array.isArray(result.data)) {
    return result.data;
  }

  const reviews = result.data?.reviews;

  if (Array.isArray(reviews)) {
    return reviews;
  }

  if (reviews && Array.isArray(reviews.data)) {
    return reviews.data;
  }

  return [];
}

function normalizeReview(review: ApiReview, index: number): GuideRating {
  return {
    id: String(review.uuid || review.id || `review-${index}`),
    reviewerName:
      review.customer_name || review.reviewer_name || review.name || "Reviewer",
    reviewerEmail:
      review.customer_email || review.reviewer_email || review.email || "",
    rating: Math.min(5, Math.max(0, toNumber(review.rating))),
    comment: review.feedback || review.comment || review.review || "",
    createdAt:
      review.created_at || review.createdAt || new Date().toISOString(),
    relevance: toNumber(review.relevance, 0),
    satisfaction: toSatisfaction(review.satisfaction),
  };
}

function RatingStars({ rating }: { rating: number }) {
  return (
    <div className="flex gap-0.5">
      {[1, 2, 3, 4, 5].map((value) => (
        <Star
          key={value}
          className={`h-4 w-4 ${
            value <= rating
              ? "fill-yellow-400 text-yellow-400"
              : "fill-slate-200 text-slate-200"
          }`}
        />
      ))}
    </div>
  );
}

function SatisfactionBadge({ value }: { value: GuideRating["satisfaction"] }) {
  const meta = satisfactionMeta[value];
  const Icon = meta.icon;

  return (
    <span
      className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[11px] font-black ring-1 ${meta.className}`}
    >
      <Icon className="h-3.5 w-3.5" />
      {meta.label}
    </span>
  );
}

export function GuideRatingList({
  guideUuid,
  refreshKey = 0,
}: GuideRatingListProps) {
  const [sortBy, setSortBy] = useState("most_relevant");
  const [ratings, setRatings] = useState<GuideRating[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState("");

  useEffect(() => {
    let isMounted = true;

    async function fetchReviews() {
      setIsLoading(true);
      setErrorMessage("");

      try {
        if (!guideUuid) {
          throw new Error("Guide uuid is missing.");
        }

        const response = await apiRequest(
          apiUrl(
            `/guide/my-reviews/${encodeURIComponent(guideUuid)}?sort_by=${sortBy}`,
          ),
          {
            headers: {
              Accept: "application/json",
            },
          },
        );
        const result = (await response
          .json()
          .catch(() => ({}))) as ApiReviewsResponse;

        if (!response.ok) {
          throw new Error("Unable to load reviews.");
        }

        if (isMounted) {
          setRatings(getReviewItems(result).map(normalizeReview));
        }
      } catch {
        if (isMounted) {
          setErrorMessage("Unable to load guide reviews.");
          setRatings([]);
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    fetchReviews();

    return () => {
      isMounted = false;
    };
  }, [guideUuid, refreshKey, sortBy]);

  return (
    <Card>
      <CardHeader className="gap-4">
        <div>
          <CardTitle>Ratings & Reviews</CardTitle>
          <p className="mt-1 text-sm font-medium text-muted-foreground">
            Feedback shared by travellers for this guide.
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          {sortOptions.map((option) => {
            const active = sortBy === option.value;

            return (
              <button
                key={option.value}
                type="button"
                onClick={() => setSortBy(option.value)}
                className={`h-9 rounded-full px-4 text-xs font-black transition ${
                  active
                    ? "bg-[var(--theme-primary)] text-white shadow-sm"
                    : "border border-[var(--theme-border-soft)] bg-white text-muted-foreground hover:border-[var(--theme-primary)] hover:text-[var(--theme-primary)]"
                }`}
              >
                {option.label}
              </button>
            );
          })}
        </div>
      </CardHeader>
      <CardContent className="space-y-2.5">
        {isLoading && (
          <div className="rounded-xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] px-4 py-3 text-sm font-semibold text-muted-foreground">
            Loading reviews...
          </div>
        )}

        {!isLoading && errorMessage && (
          <div className="rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-semibold text-red-700">
            {errorMessage}
          </div>
        )}

        {!isLoading && !errorMessage && ratings.length === 0 && (
          <div className="rounded-xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] px-4 py-3 text-sm font-semibold text-muted-foreground">
            No reviews available yet.
          </div>
        )}

        {!isLoading &&
          !errorMessage &&
          ratings.map((review) => (
            <div
              key={review.id}
              className="rounded-xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] px-4 py-3"
            >
              <div className="flex flex-wrap items-start justify-between gap-2.5">
                <div>
                  <p className="text-sm font-black text-foreground">
                    {review.reviewerName}
                  </p>
                  <p className="mt-0.5 break-all text-xs font-semibold text-muted-foreground">
                    {review.reviewerEmail}
                  </p>
                </div>
                <div className="flex flex-wrap items-center justify-end gap-2">
                  {review.rating > 0 && <RatingStars rating={review.rating} />}
                  <SatisfactionBadge value={review.satisfaction} />
                </div>
              </div>
              <p className="mt-2 text-sm font-medium leading-5 text-foreground">
                {review.comment}
              </p>
              <p className="mt-2 text-right text-xs font-medium text-muted-foreground">
                {new Date(review.createdAt).toLocaleDateString("en-IN", {
                  day: "2-digit",
                  month: "short",
                  year: "numeric",
                })}
              </p>
            </div>
          ))}
      </CardContent>
    </Card>
  );
}
