"use client";
import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { X, Star, CheckCircle, ChevronDown } from "lucide-react";
import { useSeller } from "@/lib/SellerContext";

interface Props {
  open: boolean;
  onClose: () => void;
}

const STAR_LABELS = ["", "Poor", "Fair", "Good", "Great", "Excellent"];

export function LeaveReviewModal({ open, onClose }: Props) {
  const { profile, submitReview } = useSeller();
  const [rating, setRating] = useState(0);
  const [hover, setHover] = useState(0);
  const [title, setTitle] = useState("");
  const [text, setText] = useState("");
  const [productId, setProductId] = useState(profile.listings[0]?.id ?? "");
  const [submitted, setSubmitted] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showProductPicker, setShowProductPicker] = useState(false);

  const canSubmit = rating > 0 && title.trim().length >= 3 && text.trim().length >= 10;

  const handleSubmit = async () => {
    if (!canSubmit) return;
    setLoading(true);
    await new Promise((r) => setTimeout(r, 900));
    submitReview({ rating, title, text, productId });
    setLoading(false);
    setSubmitted(true);
  };

  const handleClose = () => {
    setRating(0);
    setHover(0);
    setTitle("");
    setText("");
    setSubmitted(false);
    setLoading(false);
    onClose();
  };

  const selectedListing = profile.listings.find((l) => l.id === productId);
  const activeRating = hover || rating;

  return (
    <AnimatePresence>
      {open && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50"
            style={{ background: "rgba(0,0,0,0.7)", backdropFilter: "blur(6px)" }}
            onClick={handleClose}
          />

          {/* Sheet — slides up from bottom on mobile, centered on desktop */}
          <motion.div
            initial={{ opacity: 0, y: "100%" }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: "100%" }}
            transition={{ type: "spring", stiffness: 320, damping: 32 }}
            className="fixed bottom-0 left-0 right-0 z-50 rounded-t-3xl overflow-hidden sm:inset-auto sm:top-1/2 sm:left-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 sm:w-full sm:max-w-md sm:rounded-2xl"
            style={{ background: "var(--deep)", border: "1px solid var(--border)" }}
          >
            {submitted ? (
              /* Success State */
              <motion.div
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                className="flex flex-col items-center py-12 px-6 text-center"
              >
                <motion.div
                  initial={{ scale: 0 }}
                  animate={{ scale: 1 }}
                  transition={{ type: "spring", stiffness: 400, damping: 20, delay: 0.1 }}
                >
                  <CheckCircle size={56} color="#22c55e" />
                </motion.div>
                <h3 className="text-xl font-black text-[var(--text-primary)] mt-4 mb-2">Review Submitted!</h3>
                <p className="text-sm text-[var(--text-muted)] mb-6">
                  Thank you for sharing your experience. Your review helps the community.
                </p>
                <button
                  onClick={handleClose}
                  className="px-8 py-3 rounded-xl font-bold text-white"
                  style={{ background: "var(--accent)" }}
                >
                  Done
                </button>
              </motion.div>
            ) : (
              <>
                {/* Header */}
                <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--border)]">
                  <h3 className="text-base font-black text-[var(--text-primary)]">Leave a Review</h3>
                  <button onClick={handleClose} className="p-1.5 rounded-lg" style={{ color: "var(--text-muted)" }}>
                    <X size={18} />
                  </button>
                </div>

                <div className="px-5 py-5 space-y-5 overflow-y-auto max-h-[75vh] sm:max-h-[70vh]">
                  {/* Product selector */}
                  <div>
                    <label className="text-xs font-semibold text-[var(--text-muted)] block mb-2">
                      Product Purchased
                    </label>
                    <button
                      onClick={() => setShowProductPicker((v) => !v)}
                      className="w-full flex items-center gap-3 p-3 rounded-xl transition-all"
                      style={{ background: "var(--card)", border: "1px solid var(--border)" }}
                    >
                      {selectedListing && (
                        <img src={selectedListing.image} alt="" className="w-10 h-10 rounded-lg object-cover shrink-0" />
                      )}
                      <div className="flex-1 min-w-0 text-left">
                        <p className="text-sm font-semibold text-[var(--text-primary)] line-clamp-1">
                          {selectedListing?.title ?? "Select a product"}
                        </p>
                      </div>
                      <ChevronDown size={15} className={showProductPicker ? "rotate-180" : ""} style={{ color: "var(--text-muted)", transition: "transform 0.2s" }} />
                    </button>

                    <AnimatePresence>
                      {showProductPicker && (
                        <motion.div
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: "auto" }}
                          exit={{ opacity: 0, height: 0 }}
                          className="mt-1 rounded-xl overflow-hidden"
                          style={{ background: "var(--card)", border: "1px solid var(--border)" }}
                        >
                          {profile.listings.map((l) => (
                            <button
                              key={l.id}
                              onClick={() => { setProductId(l.id); setShowProductPicker(false); }}
                              className="w-full flex items-center gap-3 px-3 py-2.5 hover:bg-[rgba(255,255,255,0.04)] transition-colors"
                              style={{ borderBottom: "1px solid var(--border)" }}
                            >
                              <img src={l.image} alt="" className="w-8 h-8 rounded-lg object-cover shrink-0" />
                              <p className="text-sm text-[var(--text-primary)] line-clamp-1 flex-1 text-left">{l.title}</p>
                              {l.id === productId && <div className="w-2 h-2 rounded-full shrink-0" style={{ background: "var(--accent)" }} />}
                            </button>
                          ))}
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>

                  {/* Star rating */}
                  <div className="text-center">
                    <label className="text-xs font-semibold text-[var(--text-muted)] block mb-3">
                      Overall Rating
                    </label>
                    <div className="flex justify-center gap-2 mb-2">
                      {[1, 2, 3, 4, 5].map((s) => (
                        <motion.button
                          key={s}
                          whileTap={{ scale: 0.85 }}
                          onClick={() => setRating(s)}
                          onMouseEnter={() => setHover(s)}
                          onMouseLeave={() => setHover(0)}
                          className="focus:outline-none"
                          aria-label={`Rate ${s} stars`}
                        >
                          <Star
                            size={36}
                            fill={s <= activeRating ? "#f0c040" : "none"}
                            color={s <= activeRating ? "#f0c040" : "rgba(255,255,255,0.15)"}
                            style={{ transition: "fill 0.1s, color 0.1s" }}
                          />
                        </motion.button>
                      ))}
                    </div>
                    {activeRating > 0 && (
                      <motion.p
                        key={activeRating}
                        initial={{ opacity: 0, y: -4 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="text-sm font-bold"
                        style={{ color: "#f0c040" }}
                      >
                        {STAR_LABELS[activeRating]}
                      </motion.p>
                    )}
                  </div>

                  {/* Title */}
                  <div>
                    <label className="text-xs font-semibold text-[var(--text-muted)] block mb-2">
                      Review Title
                    </label>
                    <input
                      value={title}
                      onChange={(e) => setTitle(e.target.value)}
                      placeholder="Summarize your experience…"
                      maxLength={80}
                      className="w-full px-4 py-3 rounded-xl text-sm outline-none transition-all placeholder:text-[var(--text-muted)] text-[var(--text-primary)]"
                      style={{
                        background: "var(--card)",
                        border: `1px solid ${title.length >= 3 ? "rgba(34,197,94,0.4)" : "var(--border)"}`,
                      }}
                    />
                  </div>

                  {/* Body */}
                  <div>
                    <label className="text-xs font-semibold text-[var(--text-muted)] block mb-2">
                      Review Details
                    </label>
                    <textarea
                      value={text}
                      onChange={(e) => setText(e.target.value)}
                      placeholder="Describe your experience with the seller and the product…"
                      rows={4}
                      maxLength={500}
                      className="w-full px-4 py-3 rounded-xl text-sm outline-none resize-none transition-all placeholder:text-[var(--text-muted)] text-[var(--text-primary)]"
                      style={{
                        background: "var(--card)",
                        border: `1px solid ${text.length >= 10 ? "rgba(34,197,94,0.4)" : "var(--border)"}`,
                      }}
                    />
                    <p className="text-[10px] text-[var(--text-muted)] text-right mt-1">{text.length}/500</p>
                  </div>

                  {/* Submit */}
                  <button
                    onClick={handleSubmit}
                    disabled={!canSubmit || loading}
                    className="w-full py-3.5 rounded-xl font-bold text-white text-sm transition-all"
                    style={{
                      background: canSubmit ? "var(--accent)" : "rgba(255,255,255,0.08)",
                      color: canSubmit ? "#fff" : "var(--text-muted)",
                      cursor: canSubmit ? "pointer" : "not-allowed",
                      boxShadow: canSubmit ? "0 4px 14px rgba(252,0,0,0.3)" : "none",
                    }}
                  >
                    {loading ? "Submitting…" : "Submit Review"}
                  </button>
                </div>
              </>
            )}
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
