"use client";

import { useState, useEffect, useCallback } from "react";
import { Star, Loader2, Globe, AlertCircle } from "lucide-react";

const t = {
  en: {
    loading: "Loading review form...",
    invalidLink: "Invalid Review Link",
    invalidDesc: "This review link is invalid or has expired.",
    expired: "This review link has expired.",
    alreadySubmitted: "You have already submitted a review. Thank you!",
    overallRating: "How was your overall experience?",
    comment: "Additional comments (optional)",
    commentPlaceholder: "Tell us about your experience...",
    submit: "Submit Review",
    submitting: "Submitting...",
    required: "Please provide an overall rating",
    errorSubmit: "Failed to submit review. Please try again.",
    poweredBy: "Powered by Mawidi",
  },
  ar: {
    loading: "جاري تحميل نموذج التقييم...",
    invalidLink: "رابط تقييم غير صالح",
    invalidDesc: "رابط التقييم هذا غير صالح أو منتهي الصلاحية.",
    expired: "انتهت صلاحية رابط التقييم هذا.",
    alreadySubmitted: "لقد قمت بإرسال تقييم بالفعل. شكراً لك!",
    overallRating: "كيف كانت تجربتك بشكل عام؟",
    comment: "تعليقات إضافية (اختياري)",
    commentPlaceholder: "أخبرنا عن تجربتك...",
    submit: "إرسال التقييم",
    submitting: "جاري الإرسال...",
    required: "يرجى تقديم تقييم عام",
    errorSubmit: "فشل في إرسال التقييم. يرجى المحاولة مرة أخرى.",
    poweredBy: "مدعوم من Mawidi",
  },
};

interface TokenData {
  customerName: string;
  language: string;
  businessName: string;
  logoUrl: string | null;
  primaryColor: string;
  bgColor: string;
  showPoweredBy: boolean;
  questions: {
    id: string;
    questionEn: string;
    questionAr: string;
    type: "rating" | "text" | "yesno";
  }[];
}

interface PageProps {
  params: { lang: string; token: string };
}

export default function ReviewPage({ params }: PageProps) {
  const { lang, token } = params;
  const [currentLang, setCurrentLang] = useState(lang === "ar" ? "ar" : "en");
  const isAr = currentLang === "ar";
  const labels = t[isAr ? "ar" : "en"];

  const [tokenData, setTokenData] = useState<TokenData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");

  const [overallRating, setOverallRating] = useState(0);
  const [hoverRating, setHoverRating] = useState(0);
  const [comment, setComment] = useState("");
  const [questionAnswers, setQuestionAnswers] = useState<
    Record<string, number | string>
  >({});

  const fetchTokenData = useCallback(async () => {
    try {
      const res = await fetch(`/api/public/review/${token}`);
      if (res.status === 410) {
        setError(labels.expired);
        return;
      }
      if (res.status === 409) {
        setError(labels.alreadySubmitted);
        return;
      }
      if (!res.ok) {
        setError(labels.invalidDesc);
        return;
      }
      const data = await res.json();
      const ws = data.widgetSettings ?? {};
      setTokenData({
        customerName: data.customerName ?? "",
        language: data.language ?? "en",
        businessName: ws.businessName ?? data.businessName ?? "Mawidi",
        logoUrl: ws.logoUrl ?? null,
        primaryColor: ws.primaryColor ?? "#10b981",
        bgColor: ws.backgroundColor ?? ws.bgColor ?? "#ffffff",
        showPoweredBy: ws.showPoweredBy ?? true,
        questions: (data.questions ?? []).map(
          (
            q: {
              id?: string;
              questionEn: string;
              questionAr: string;
              type?: string;
            },
            i: number,
          ) => ({
            id: q.id ?? String(i),
            questionEn: q.questionEn,
            questionAr: q.questionAr,
            type: (q.type as "rating" | "text" | "yesno") ?? "text",
          }),
        ),
      });
    } catch {
      setError(labels.invalidDesc);
    } finally {
      setLoading(false);
    }
  }, [token, labels.expired, labels.alreadySubmitted, labels.invalidDesc]);

  useEffect(() => {
    fetchTokenData();
  }, [fetchTokenData]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitError("");

    if (overallRating === 0) {
      setSubmitError(labels.required);
      return;
    }

    setSubmitting(true);
    try {
      // Build questionResponses from questionAnswers
      const questionResponses = tokenData!.questions
        .map((q) => {
          const answer = questionAnswers[q.id];
          if (answer === undefined || answer === "") return null;
          return {
            questionEn: q.questionEn,
            questionAr: q.questionAr,
            answer: typeof answer === "number" ? String(answer) : answer,
            rating: typeof answer === "number" ? answer : undefined,
          };
        })
        .filter(Boolean);

      const res = await fetch(`/api/public/review/${token}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          rating: overallRating,
          content: comment.trim() || null,
          customerName: tokenData!.customerName || "Customer",
          language: (currentLang === "ar" ? "ar" : "en") as "en" | "ar",
          questionResponses,
        }),
      });
      if (!res.ok) throw new Error("Failed");
      // Redirect to thank-you page
      window.location.href = `/${currentLang}/review/${token}/thank-you`;
    } catch {
      setSubmitError(labels.errorSubmit);
    } finally {
      setSubmitting(false);
    }
  };

  const setQuestionAnswer = (questionId: string, value: number | string) => {
    setQuestionAnswers((prev) => ({ ...prev, [questionId]: value }));
  };

  // Loading state
  if (loading) {
    return (
      <div className="min-h-screen bg-white flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="w-10 h-10 text-emerald-500 animate-spin mx-auto mb-3" />
          <p className="text-slate-500">{labels.loading}</p>
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="min-h-screen bg-white flex items-center justify-center px-4">
        <div className="max-w-md w-full text-center">
          <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-4" />
          <h1 className="text-xl font-semibold text-slate-900 mb-2">
            {labels.invalidLink}
          </h1>
          <p className="text-slate-500">{error}</p>
        </div>
      </div>
    );
  }

  if (!tokenData) return null;

  const primaryColor = tokenData.primaryColor || "#10b981";
  const bgColor = tokenData.bgColor || "#ffffff";

  return (
    <div
      className="min-h-screen py-8 px-4"
      dir={isAr ? "rtl" : "ltr"}
      style={{ backgroundColor: bgColor }}
    >
      <div className="max-w-lg mx-auto">
        {/* Language toggle */}
        <div className="flex justify-end mb-4">
          <button
            onClick={() => setCurrentLang(isAr ? "en" : "ar")}
            className="flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-700 transition-colors"
          >
            <Globe className="w-4 h-4" />
            {isAr ? "English" : "العربية"}
          </button>
        </div>

        {/* Header */}
        <div className="text-center mb-8">
          {tokenData.logoUrl && (
            <img
              src={tokenData.logoUrl}
              alt={tokenData.businessName}
              className="h-12 mx-auto mb-4 object-contain"
            />
          )}
          <h1 className="text-2xl font-bold text-slate-900">
            {tokenData.businessName}
          </h1>
        </div>

        {/* Review Form */}
        <form
          onSubmit={handleSubmit}
          className="bg-white rounded-2xl shadow-lg border border-slate-100 p-6 space-y-6"
        >
          {/* Overall Rating */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-3">
              {labels.overallRating}
            </label>
            <div className="flex justify-center gap-2">
              {[1, 2, 3, 4, 5].map((s) => (
                <button
                  key={s}
                  type="button"
                  onClick={() => setOverallRating(s)}
                  onMouseEnter={() => setHoverRating(s)}
                  onMouseLeave={() => setHoverRating(0)}
                  className="transition-transform hover:scale-110"
                >
                  <Star
                    className="w-10 h-10 transition-colors"
                    style={{
                      color:
                        s <= (hoverRating || overallRating)
                          ? primaryColor
                          : "#d1d5db",
                      fill:
                        s <= (hoverRating || overallRating)
                          ? primaryColor
                          : "none",
                    }}
                  />
                </button>
              ))}
            </div>
          </div>

          {/* AI-generated questions */}
          {tokenData.questions.map((q) => (
            <div key={q.id}>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {isAr ? q.questionAr : q.questionEn}
              </label>
              {q.type === "rating" ? (
                <div className="flex gap-1.5">
                  {[1, 2, 3, 4, 5].map((s) => (
                    <button
                      key={s}
                      type="button"
                      onClick={() => setQuestionAnswer(q.id, s)}
                      className="transition-transform hover:scale-110"
                    >
                      <Star
                        className="w-7 h-7 transition-colors"
                        style={{
                          color:
                            s <= ((questionAnswers[q.id] as number) || 0)
                              ? primaryColor
                              : "#d1d5db",
                          fill:
                            s <= ((questionAnswers[q.id] as number) || 0)
                              ? primaryColor
                              : "none",
                        }}
                      />
                    </button>
                  ))}
                </div>
              ) : q.type === "yesno" ? (
                <div className="flex gap-3">
                  {[
                    { value: "yes", labelEn: "Yes", labelAr: "نعم" },
                    { value: "no", labelEn: "No", labelAr: "لا" },
                  ].map((opt) => {
                    const selected = questionAnswers[q.id] === opt.value;
                    return (
                      <button
                        key={opt.value}
                        type="button"
                        onClick={() => setQuestionAnswer(q.id, opt.value)}
                        className="flex-1 py-2.5 rounded-xl border-2 text-sm font-medium transition-all"
                        style={{
                          borderColor: selected ? primaryColor : "#e2e8f0",
                          backgroundColor: selected
                            ? primaryColor
                            : "transparent",
                          color: selected ? "#ffffff" : "#64748b",
                        }}
                      >
                        {isAr ? opt.labelAr : opt.labelEn}
                      </button>
                    );
                  })}
                </div>
              ) : (
                <input
                  type="text"
                  value={(questionAnswers[q.id] as string) || ""}
                  onChange={(e) => setQuestionAnswer(q.id, e.target.value)}
                  className="w-full px-4 py-2.5 border border-slate-200 rounded-xl text-slate-900 focus:ring-2 focus:border-transparent text-sm"
                  style={
                    { "--tw-ring-color": primaryColor } as React.CSSProperties
                  }
                />
              )}
            </div>
          ))}

          {/* Comment */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {labels.comment}
            </label>
            <textarea
              value={comment}
              onChange={(e) => setComment(e.target.value)}
              placeholder={labels.commentPlaceholder}
              rows={4}
              className="w-full px-4 py-3 border border-slate-200 rounded-xl text-slate-900 placeholder-slate-400 resize-none focus:ring-2 focus:border-transparent text-sm"
              style={{ "--tw-ring-color": primaryColor } as React.CSSProperties}
            />
          </div>

          {submitError && (
            <p className="text-sm text-red-600 bg-red-50 px-3 py-2 rounded-lg">
              {submitError}
            </p>
          )}

          {/* Submit */}
          <button
            type="submit"
            disabled={submitting}
            className="w-full py-3 rounded-xl text-white font-medium transition-opacity disabled:opacity-50 text-sm"
            style={{ backgroundColor: primaryColor }}
          >
            {submitting ? (
              <span className="flex items-center justify-center gap-2">
                <Loader2 className="w-4 h-4 animate-spin" />
                {labels.submitting}
              </span>
            ) : (
              labels.submit
            )}
          </button>
        </form>

        {/* Powered by */}
        {tokenData.showPoweredBy && (
          <p className="text-center text-xs text-slate-400 mt-6">
            {labels.poweredBy}
          </p>
        )}
      </div>
    </div>
  );
}
