"use client";

import { useState } from "react";
type Transcript = {
  id: string;
  title: string | null;
  call_date: string;
  content: string;
  created_at: string | Date;
};

function TranscriptCard({ transcript }: { transcript: Transcript }) {
  const [expanded, setExpanded] = useState(false);

  const date = new Date(transcript.call_date).toLocaleDateString("it-IT", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  });

  return (
    <div className="rounded-xl border border-border-light bg-card shadow-card overflow-hidden">
      <button
        type="button"
        onClick={() => setExpanded((v) => !v)}
        className="w-full flex items-center justify-between px-5 py-4 text-left hover:bg-muted transition-colors group"
        aria-expanded={expanded}
      >
        <div className="flex items-center gap-3 min-w-0">
          {/* Icona microfono */}
          <svg
            className="w-4 h-4 text-muted-foreground shrink-0"
            fill="none"
            stroke="currentColor"
            strokeWidth={2}
            viewBox="0 0 24 24"
            aria-hidden="true"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M12 18.75a6 6 0 006-6v-1.5m-6 7.5a6 6 0 01-6-6v-1.5m6 7.5v3.75m-3.75 0h7.5M12 15.75a3 3 0 01-3-3V4.5a3 3 0 116 0v8.25a3 3 0 01-3 3z"
            />
          </svg>
          <div className="min-w-0">
            <p className="text-xs font-semibold text-foreground truncate group-hover:text-primary transition-colors">
              {transcript.title ?? "Transcript chiamata"}
            </p>
            <p className="text-[11px] text-muted-foreground mt-0.5">{date}</p>
          </div>
        </div>
        <svg
          className={`w-4 h-4 text-muted-foreground shrink-0 ml-3 transition-transform ${expanded ? "rotate-180" : ""}`}
          fill="none"
          stroke="currentColor"
          strokeWidth={2}
          viewBox="0 0 24 24"
          aria-hidden="true"
        >
          <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {expanded && (
        <div className="px-5 pb-5 pt-1 border-t border-border-light">
          <pre className="text-[11px] text-muted-foreground whitespace-pre-wrap font-sans leading-relaxed max-h-80 overflow-y-auto">
            {transcript.content}
          </pre>
        </div>
      )}
    </div>
  );
}

interface TranscriptsSectionProps {
  transcripts: Transcript[];
}

export function TranscriptsSection({ transcripts }: TranscriptsSectionProps) {
  if (transcripts.length === 0) {
    return (
      <p className="text-sm text-[#999999] italic">
        Nessun transcript disponibile.
      </p>
    );
  }

  return (
    <div className="space-y-2">
      {transcripts.map((t) => (
        <TranscriptCard key={t.id} transcript={t} />
      ))}
    </div>
  );
}
