"use client";

import { useState } from "react";
import toast from "react-hot-toast";
import {
  submitHoroscopeFeedback,
  HoroscopeFeedbackType,
} from "@/app/lib/horoscope";

interface Props {
  zodiacId: number;
  horoscopeType: "daily" | "weekly" | "yearly" | "daily-moon" | "daily-nakshatra";
}

const OPTIONS: { value: HoroscopeFeedbackType; label: string; emoji: string }[] = [
  { value: "Great", label: "Great", emoji: "😄" },
  { value: "Average", label: "Average", emoji: "😐" },
  { value: "Poor", label: "Poor", emoji: "😕" },
];

export default function HoroscopeFeedback({ zodiacId, horoscopeType }: Props) {
  const [selected, setSelected] = useState<HoroscopeFeedbackType | null>(null);
  const [text, setText] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  if (submitted) {
    return (
      <section className="horoscope-feedback horoscope-feedback-done">
        <p>Thanks for your feedback!</p>
      </section>
    );
  }

  const handleSubmit = async () => {
    if (!selected) return;

    setSubmitting(true);

    const result = await submitHoroscopeFeedback({
      feedbacktype: selected,
      zodiac: zodiacId,
      horoscopeType,
      feedback: text.trim() || undefined,
    });

    setSubmitting(false);

    if (!result.authenticated) {
      toast.error("Please sign in to leave feedback.");
      return;
    }

    if (!result.success) {
      toast.error(result.message || "Unable to submit feedback.");
      return;
    }

    setSubmitted(true);
  };

  return (
    <section className="horoscope-feedback">
      <h3>How accurate was this horoscope?</h3>

      <div className="horoscope-feedback-options">
        {OPTIONS.map((option) => (
          <button
            key={option.value}
            type="button"
            className={`horoscope-feedback-pill ${
              selected === option.value ? "active" : ""
            }`}
            onClick={() => setSelected(option.value)}
          >
            <span>{option.emoji}</span>
            {option.label}
          </button>
        ))}
      </div>

      {selected && (
        <>
          <textarea
            className="horoscope-feedback-text"
            placeholder="Tell us more (optional)"
            maxLength={1000}
            value={text}
            onChange={(event) => setText(event.target.value)}
          />

          <button
            type="button"
            className="horoscope-feedback-submit"
            disabled={submitting}
            onClick={handleSubmit}
          >
            {submitting ? "Submitting..." : "Submit Feedback"}
          </button>
        </>
      )}
    </section>
  );
}
