import React, { useMemo } from "react";

type Person = { name: string; email?: string };

export type CourseInfo = {
  id: string;
  name: string;
  instructor?: Person;
  teachingAssistant?: Person;
};

function gmailCompose(email: string, subject: string, body?: string) {
  const s = encodeURIComponent(subject);
  const b = body ? `&body=${encodeURIComponent(body)}` : "";
  return `https://mail.google.com/mail/?view=cm&fs=1&to=${encodeURIComponent(email)}&su=${s}${b}`;
}

export function CourseInfoHeader({
  course,
  className,
}: {
  course: CourseInfo;
  className?: string;
}) {
  const instructorLink = useMemo(() => {
    const p = course.instructor;
    if (!p?.email) return "";
    return gmailCompose(
      p.email,
      `[Clare] Question about ${course.name}`,
      `Hi ${p.name},\n\nI have a question about ${course.name}:\n\n(Write your question here)\n\nThanks,\n`
    );
  }, [course]);

  const taLink = useMemo(() => {
    const p = course.teachingAssistant;
    if (!p?.email) return "";
    return gmailCompose(
      p.email,
      `[Clare] Help request for ${course.name}`,
      `Hi ${p.name},\n\nI need help with ${course.name}:\n\n(Write your question here)\n\nThanks,\n`
    );
  }, [course]);

  const instructorName = course.instructor?.name ?? "N/A";
  const taName = course.teachingAssistant?.name ?? "N/A";

  return (
    <div className={className ?? "px-4 pt-4 pb-3"}>
      <div className="space-y-1">
        <div className="text-base font-semibold text-foreground truncate">
          {course.name}
        </div>

        <div className="text-sm text-muted-foreground">
          Instructor:{" "}
          {instructorLink ? (
            <a
              href={instructorLink}
              target="_blank"
              rel="noopener noreferrer"
              className="text-primary hover:underline"
              title={`Message ${instructorName} in Gmail`}
              onClick={(e) => e.stopPropagation()}
            >
              {instructorName}
            </a>
          ) : (
            <span className="text-muted-foreground/60">{instructorName}</span>
          )}
        </div>

        <div className="text-sm text-muted-foreground">
          TA:{" "}
          {taLink ? (
            <a
              href={taLink}
              target="_blank"
              rel="noopener noreferrer"
              className="text-primary hover:underline"
              title={`Message ${taName} in Gmail`}
              onClick={(e) => e.stopPropagation()}
            >
              {taName}
            </a>
          ) : (
            <span className="text-muted-foreground/60">{taName}</span>
          )}
        </div>
      </div>
    </div>
  );
}
