"use client";

import { useState, useEffect, useCallback } from "react";
import { cn } from "@/lib/utils";
import { ThumbsUp, ThumbsDown, Star, MessageSquare } from "lucide-react";
import { Card } from "@/components/ui/card";

interface FeedbackEntry {
  id: string;
  requestId: string | null;
  rating: number | null;
  thumbsUp: boolean;
  comment: string | null;
  model: string | null;
  createdAt: string;
}

interface FeedbackStats {
  total: number;
  thumbsUpCount: number;
  thumbsDownCount: number;
  averageRating: number | null;
  ratedCount: number;
  ratingDistribution: Record<number, number>;
}

export function FeedbackList({ className }: { className?: string }) {
  const [feedback, setFeedback] = useState<FeedbackEntry[]>([]);
  const [stats, setStats] = useState<FeedbackStats | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async () => {
    try {
      const [feedbackRes, statsRes] = await Promise.all([
        fetch("/api/feedback?limit=20"),
        fetch("/api/feedback/stats"),
      ]);

      if (feedbackRes.ok) {
        const data = await feedbackRes.json();
        setFeedback(data.feedback);
      }
      if (statsRes.ok) {
        setStats(await statsRes.json());
      }
    } catch {
      // silently handle - empty state is fine
    } finally {
      setLoading(false);
    }
  }, []);

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

  if (loading) {
    return (
      <p className="py-8 text-center text-sm text-gray-500">Loading feedback...</p>
    );
  }

  return (
    <div className={cn("space-y-6", className)}>
      {/* Stats summary */}
      {stats && stats.total > 0 && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <Card className="p-4">
            <p className="text-xs text-gray-400">Total Feedback</p>
            <p className="text-2xl font-bold text-gray-100">{stats.total}</p>
          </Card>
          <Card className="p-4">
            <div className="flex items-center gap-2">
              <ThumbsUp size={14} className="text-emerald-400" />
              <p className="text-xs text-gray-400">Positive</p>
            </div>
            <p className="text-2xl font-bold text-emerald-400">
              {stats.thumbsUpCount}
            </p>
            {stats.total > 0 && (
              <p className="text-xs text-gray-500">
                {Math.round((stats.thumbsUpCount / stats.total) * 100)}%
              </p>
            )}
          </Card>
          <Card className="p-4">
            <div className="flex items-center gap-2">
              <ThumbsDown size={14} className="text-red-400" />
              <p className="text-xs text-gray-400">Negative</p>
            </div>
            <p className="text-2xl font-bold text-red-400">
              {stats.thumbsDownCount}
            </p>
            {stats.total > 0 && (
              <p className="text-xs text-gray-500">
                {Math.round((stats.thumbsDownCount / stats.total) * 100)}%
              </p>
            )}
          </Card>
          <Card className="p-4">
            <div className="flex items-center gap-2">
              <Star size={14} className="text-amber-400" />
              <p className="text-xs text-gray-400">Avg Rating</p>
            </div>
            <p className="text-2xl font-bold text-amber-400">
              {stats.averageRating !== null ? stats.averageRating.toFixed(1) : "--"}
            </p>
            <p className="text-xs text-gray-500">
              {stats.ratedCount} rated
            </p>
          </Card>
        </div>
      )}

      {/* Feedback list */}
      {feedback.length === 0 ? (
        <Card title="No Feedback Yet" description="Rate AI responses to see your history here">
          <p className="py-4 text-center text-sm text-gray-400">
            Use the feedback widget to rate responses and help improve routing.
          </p>
        </Card>
      ) : (
        <Card
          title="Recent Feedback"
          description={`Showing ${feedback.length} of ${stats?.total ?? feedback.length}`}
          icon={<MessageSquare size={20} />}
        >
          <div className="divide-y divide-gray-800">
            {feedback.map((entry) => (
              <div key={entry.id} className="py-3 first:pt-0 last:pb-0">
                <div className="flex items-start justify-between gap-3">
                  <div className="flex items-center gap-2">
                    {entry.thumbsUp ? (
                      <ThumbsUp size={14} className="text-emerald-400" />
                    ) : (
                      <ThumbsDown size={14} className="text-red-400" />
                    )}
                    {entry.rating !== null && (
                      <div className="flex items-center gap-0.5">
                        {[1, 2, 3, 4, 5].map((star) => (
                          <Star
                            key={star}
                            size={12}
                            className={cn(
                              entry.rating !== null && entry.rating >= star
                                ? "fill-amber-400 text-amber-400"
                                : "text-gray-700"
                            )}
                          />
                        ))}
                      </div>
                    )}
                    {entry.model && (
                      <span className="rounded bg-gray-800 px-1.5 py-0.5 text-xs text-gray-400">
                        {entry.model}
                      </span>
                    )}
                  </div>
                  <span className="shrink-0 text-xs text-gray-500">
                    {new Date(entry.createdAt).toLocaleDateString()}
                  </span>
                </div>
                {entry.comment && (
                  <p className="mt-1 text-sm text-gray-300">{entry.comment}</p>
                )}
                {entry.requestId && (
                  <p className="mt-1 text-xs text-gray-500">
                    Request: {entry.requestId.slice(0, 12)}...
                  </p>
                )}
              </div>
            ))}
          </div>
        </Card>
      )}
    </div>
  );
}
