"use client";

import { useState } from "react";
import { cn } from "@/lib/utils";
import { ThumbsUp, ThumbsDown, Star, Send } from "lucide-react";
import { Button } from "@/components/ui/button";

interface FeedbackWidgetProps {
  requestId?: string;
  model?: string;
  onSubmitted?: () => void;
  className?: string;
}

export function FeedbackWidget({
  requestId,
  model,
  onSubmitted,
  className,
}: FeedbackWidgetProps) {
  const [thumbsUp, setThumbsUp] = useState<boolean | null>(null);
  const [rating, setRating] = useState<number | null>(null);
  const [hoverRating, setHoverRating] = useState<number | null>(null);
  const [comment, setComment] = useState("");
  const [showDetails, setShowDetails] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit() {
    if (thumbsUp === null) return;

    setSubmitting(true);
    setError(null);

    try {
      const res = await fetch("/api/feedback", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          requestId: requestId || null,
          rating,
          thumbsUp,
          comment: comment.trim() || null,
          model: model || null,
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to submit feedback");
      }

      setSubmitted(true);
      onSubmitted?.();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to submit feedback");
    } finally {
      setSubmitting(false);
    }
  }

  if (submitted) {
    return (
      <div
        className={cn(
          "rounded-lg border border-gray-800 bg-gray-900 p-4 text-center",
          className
        )}
      >
        <p className="text-sm text-emerald-400">Thank you for your feedback!</p>
      </div>
    );
  }

  return (
    <div
      className={cn(
        "rounded-lg border border-gray-800 bg-gray-900 p-4",
        className
      )}
    >
      <p className="mb-3 text-sm font-medium text-gray-300">
        How was this response?
      </p>

      {/* Thumbs up/down */}
      <div className="flex items-center gap-2">
        <button
          type="button"
          onClick={() => {
            setThumbsUp(true);
            setShowDetails(true);
          }}
          className={cn(
            "rounded-lg p-2 transition-colors",
            thumbsUp === true
              ? "bg-emerald-500/20 text-emerald-400"
              : "text-gray-500 hover:bg-gray-800 hover:text-gray-300"
          )}
          aria-label="Thumbs up"
        >
          <ThumbsUp size={18} />
        </button>
        <button
          type="button"
          onClick={() => {
            setThumbsUp(false);
            setShowDetails(true);
          }}
          className={cn(
            "rounded-lg p-2 transition-colors",
            thumbsUp === false
              ? "bg-red-500/20 text-red-400"
              : "text-gray-500 hover:bg-gray-800 hover:text-gray-300"
          )}
          aria-label="Thumbs down"
        >
          <ThumbsDown size={18} />
        </button>
      </div>

      {/* Extended details (shown after thumbs selection) */}
      {showDetails && (
        <div className="mt-4 space-y-3">
          {/* Star rating */}
          <div>
            <p className="mb-1 text-xs text-gray-400">Rate quality (optional)</p>
            <div className="flex items-center gap-1">
              {[1, 2, 3, 4, 5].map((star) => (
                <button
                  key={star}
                  type="button"
                  onClick={() => setRating(star)}
                  onMouseEnter={() => setHoverRating(star)}
                  onMouseLeave={() => setHoverRating(null)}
                  className="p-0.5 transition-colors"
                  aria-label={`${star} star${star !== 1 ? "s" : ""}`}
                >
                  <Star
                    size={18}
                    className={cn(
                      "transition-colors",
                      (hoverRating ?? rating ?? 0) >= star
                        ? "fill-amber-400 text-amber-400"
                        : "text-gray-500"
                    )}
                  />
                </button>
              ))}
            </div>
          </div>

          {/* Comment */}
          <div>
            <textarea
              value={comment}
              onChange={(e) => setComment(e.target.value)}
              placeholder="Any additional comments? (optional)"
              maxLength={1000}
              rows={2}
              className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-100 placeholder-gray-500 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
            />
          </div>

          {/* Error message */}
          {error && (
            <p className="text-xs text-red-400">{error}</p>
          )}

          {/* Submit */}
          <Button
            size="sm"
            onClick={handleSubmit}
            disabled={submitting || thumbsUp === null}
          >
            <Send size={14} />
            {submitting ? "Submitting..." : "Submit Feedback"}
          </Button>
        </div>
      )}
    </div>
  );
}
