import { useState } from 'preact/hooks';
import './Cards.css';
import type { CuratorOutput, CuratorCategory } from '../types/index.js';

interface RecommendationCardProps {
  show: CuratorOutput;
  verified?: boolean;
  existingFeedback?: { stars: number; feedback: string };
  onFeedback: (item_name: string, stars: number, feedback: string) => Promise<void>;
}

const CATEGORY_COLORS: Record<CuratorCategory, string> = {
  'Full Match': 'badge-magenta',
  'Definitely Like': 'badge-green',
  'Might Like': 'badge-blue',
  'Questionable': 'badge-yellow',
  'Will Not Like': 'badge-red',
};

export function RecommendationCard({ show, verified, existingFeedback, onFeedback }: RecommendationCardProps) {
  const [selectedStars, setSelectedStars] = useState(existingFeedback?.stars ?? 0);
  const [hoverStar, setHoverStar] = useState(0);
  const [comment, setComment] = useState(existingFeedback?.feedback ?? '');
  const [showComment, setShowComment] = useState(false);
  const [submitted, setSubmitted] = useState(!!existingFeedback);
  const [saving, setSaving] = useState(false);

  const handleStarClick = (stars: number) => {
    setSelectedStars(stars);
    setShowComment(true);
  };

  const handleSubmit = async () => {
    if (!selectedStars) return;
    setSaving(true);
    try {
      await onFeedback(show.title, selectedStars, comment);
      setSubmitted(true);
      setShowComment(false);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div class="card">
      <div class="card-header">
        <span class={`badge ${CATEGORY_COLORS[show.category]}`}>{show.category}</span>
        <h3 class="card-title">{show.title}</h3>
      </div>
      <p class="card-explanation">{show.explanation}</p>

      <div class="card-badges">
        {show.genre && <span class="badge genre-badge">{show.genre}</span>}
        {verified && <span class="badge badge-verified">Verified</span>}
      </div>

      {(show.pros?.length > 0 || show.cons?.length > 0) && (
        <div class="pros-cons-table">
          <div class="pros-col">
            {show.pros?.map((p) => <span class="pro-item">+ {p}</span>)}
          </div>
          <div class="cons-col">
            {show.cons?.map((c) => <span class="con-item">- {c}</span>)}
          </div>
        </div>
      )}

      <div class="card-feedback">
        <div class="star-rating">
          {[1, 2, 3].map((star) => {
            const effective = hoverStar || selectedStars;
            return (
              <button
                key={star}
                class={`star-btn${effective >= star ? ' star-active' : ''}`}
                onClick={() => handleStarClick(star)}
                onMouseEnter={() => setHoverStar(star)}
                onMouseLeave={() => setHoverStar(0)}
                aria-label={`Rate ${star} star${star > 1 ? 's' : ''}`}
              >
                {effective >= star ? '★' : '☆'}
              </button>
            );
          })}
          {submitted && <span class="feedback-saved">Saved</span>}
        </div>

        {showComment && !submitted && (
          <div class="comment-area">
            <textarea
              class="form-textarea comment-input"
              placeholder="Optional comment…"
              value={comment}
              onInput={(e) => setComment((e.target as HTMLTextAreaElement).value)}
              rows={2}
            />
            <button
              class="btn-primary btn-sm"
              onClick={handleSubmit}
              disabled={saving || !selectedStars}
            >
              {saving ? 'Saving…' : 'Save Feedback'}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
