"use client";

import { useState } from "react";
import { Source } from "@/types/chat";

interface SourceCardProps {
  sources: Source[];
}

export default function SourceCard({ sources }: SourceCardProps) {
  const [open, setOpen] = useState(false);

  const relevant = sources.filter((s) => s.score > 0.3);
  if (relevant.length === 0) return null;

  return (
    <div className="mt-3">
      <button
        onClick={() => setOpen((o) => !o)}
        className="flex items-center gap-1.5 text-xs text-[#47C3A6] hover:text-[#8FD15E] transition-colors"
      >
        <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
          <path d="M6 0L7.5 4.5H12L8.5 7.2L9.8 12L6 9.5L2.2 12L3.5 7.2L0 4.5H4.5L6 0Z" />
        </svg>
        <span>{relevant.length} source{relevant.length > 1 ? "s" : ""}</span>
        <svg
          width="10" height="10" viewBox="0 0 10 10" fill="currentColor"
          className={`transition-transform duration-200 ${open ? "rotate-180" : ""}`}
        >
          <path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" />
        </svg>
      </button>

      {open && (
        <div className="mt-2 flex flex-col gap-1.5 animate-fade-in">
          {relevant.map((source, i) => (
            <div
              key={i}
              className="flex items-start gap-2 bg-[#F8FAFC] border border-[#E2E8F0] rounded px-3 py-2"
            >
              <div className="mt-0.5 w-1.5 h-1.5 rounded-full bg-gradient-to-br from-[#47C3A6] to-[#14B7CC] flex-shrink-0" />
              <div className="min-w-0">
                <p className="text-xs text-[#1A202C] font-medium truncate">
                  {source.document.split("/").pop()}
                </p>
                {source.section && (
                  <p className="text-xs text-[#94A3B8] mt-0.5 truncate">{source.section}</p>
                )}
              </div>
              <span className="ml-auto text-xs text-[#47C3A6] flex-shrink-0 font-mono">
                {Math.round(source.score * 100)}%
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
