import { ShowcaseSection } from "@/components/Layouts/showcase-section";
import type { TTenderDetails } from "@/lib/api/types/Tenders";
import { isoStringToDate, truncateString, unixToDate } from "@/utils/shared";
import Link from "next/link";
import {
  HEADER_SCROLL_MARGIN,
  SHOWCASE_CENTERED_BODY,
  TENDER_SECTION_IDS,
} from "../constants";
import {
  hasAddressContent,
  hasWinningTendererContent,
  isNonEmptyTrimmed,
  isValidHttpUrl,
  isValidIsoDateTimeString,
  isValidPositiveUnix,
  shouldShowExternalLinksBlock,
} from "../tender-display-utils";
import { ExternalLinkIcon } from "./external-link-icon";
import { SectionHeading } from "./section-heading";

type TenderTimelineSectionProps = {
  tender: TTenderDetails;
};

function formatWinnerAddress(tender: TTenderDetails): string[] {
  const w = tender.winning_tenderer;
  if (!w?.address || !hasAddressContent(w.address)) return [];
  const a = w.address;
  const lines: string[] = [];
  if (isNonEmptyTrimmed(a.street_name)) lines.push(a.street_name!.trim());
  const cityLine = [a.postal_zone, a.city_name]
    .map((s) => s?.trim())
    .filter(Boolean)
    .join(" ");
  if (cityLine) lines.push(cityLine);
  const tail = [a.country_subentity_code, a.country_code]
    .map((s) => s?.trim())
    .filter(Boolean)
    .join(" · ");
  if (tail) lines.push(tail);
  return lines;
}

export function TenderTimelineSection({ tender }: TenderTimelineSectionProps) {
  const submissionUrl = tender.submission_url?.trim();
  const dispatchIso = tender.notice_dispatch_date_with_timezone?.trim();
  const dispatchLabel = isValidIsoDateTimeString(dispatchIso)
    ? isoStringToDate({ isoString: dispatchIso!, hasTime: true })
    : isValidPositiveUnix(tender.notice_dispatch_at)
      ? unixToDate({
          unix: tender.notice_dispatch_at!,
          hasTime: true,
        })
      : null;

  const winnerName = tender.winning_tenderer?.name?.trim();
  const winnerLines = formatWinnerAddress(tender);
  const showWinnerBlock =
    hasWinningTendererContent(tender) &&
    (Boolean(winnerName) || winnerLines.length > 0);

  const showSubmissionUrl = Boolean(submissionUrl) && isValidHttpUrl(submissionUrl);
  const showExternal = shouldShowExternalLinksBlock(tender);

  const deadlineCards = [
    {
      key: "application",
      title: "Application deadline",
      unix: tender.application_deadline,
    },
    {
      key: "publication",
      title: "Publication date",
      unix: tender.publication_date,
    },
    {
      key: "submission",
      title: "Submission deadline",
      unix: tender.submission_deadline,
    },
    {
      key: "tender",
      title: "Tender deadline",
      unix: tender.tender_deadline,
    },
  ].filter((d) => isValidPositiveUnix(d.unix));

  return (
    <div id={TENDER_SECTION_IDS.timeline} className={HEADER_SCROLL_MARGIN}>
      <SectionHeading>Timeline</SectionHeading>
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
        {isValidPositiveUnix(tender.award_date) ? (
          <ShowcaseSection title="Award date" {...SHOWCASE_CENTERED_BODY}>
            <time className="font-medium tabular-nums text-dark dark:text-white">
              {unixToDate({
                unix: tender.award_date!,
                hasTime: true,
              })}
            </time>
          </ShowcaseSection>
        ) : null}

        {showWinnerBlock ? (
          <ShowcaseSection
            title="Winning tenderer"
            rootClassName="sm:col-span-2 lg:col-span-3 xl:col-span-5"
            className="text-start"
          >
            {winnerName ? (
              <p className="font-medium text-dark dark:text-white">{winnerName}</p>
            ) : null}
            {winnerLines.length > 0 ? (
              <div className={winnerName ? "mt-2 space-y-1" : "space-y-1"}>
                {winnerLines.map((line, i) => (
                  <p
                    key={`w-${i}`}
                    className="text-sm text-dark dark:text-white/90"
                  >
                    {line}
                  </p>
                ))}
              </div>
            ) : null}
          </ShowcaseSection>
        ) : null}

        {dispatchLabel ? (
          <ShowcaseSection title="Notice dispatch" {...SHOWCASE_CENTERED_BODY}>
            <time className="font-medium tabular-nums text-dark dark:text-white">
              {dispatchLabel}
            </time>
          </ShowcaseSection>
        ) : null}

        {isValidPositiveUnix(tender.issue_date) ? (
          <ShowcaseSection title="Issue date" {...SHOWCASE_CENTERED_BODY}>
            <time className="font-medium tabular-nums text-dark dark:text-white">
              {unixToDate({
                unix: tender.issue_date!,
                hasTime: false,
              })}
            </time>
          </ShowcaseSection>
        ) : null}

        {isValidPositiveUnix(tender.issue_time) ? (
          <ShowcaseSection title="Issue time" {...SHOWCASE_CENTERED_BODY}>
            <time className="font-medium tabular-nums text-dark dark:text-white">
              {unixToDate({
                unix: tender.issue_time!,
                hasTime: true,
              })}
            </time>
          </ShowcaseSection>
        ) : null}

        {deadlineCards.map((d) => (
          <ShowcaseSection key={d.key} title={d.title} {...SHOWCASE_CENTERED_BODY}>
            <time className="font-medium tabular-nums text-dark dark:text-white">
              {unixToDate({
                unix: d.unix as number,
                hasTime: true,
              })}
            </time>
          </ShowcaseSection>
        ))}

        {showSubmissionUrl ? (
          <ShowcaseSection title="Submission URL" {...SHOWCASE_CENTERED_BODY}>
            <Link
              href={submissionUrl!}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex max-w-full items-center gap-1.5 break-all font-medium text-primary underline-offset-4 hover:underline"
            >
              <ExternalLinkIcon className="shrink-0" />
              {truncateString(submissionUrl!, 42)}
            </Link>
          </ShowcaseSection>
        ) : null}

        {showExternal ? (
          <ShowcaseSection
            title="External links"
            rootClassName="sm:col-span-2 lg:col-span-3 xl:col-span-5"
            className="text-start"
          >
            <ul className="flex flex-col gap-2">
              {isValidHttpUrl(tender.document_url) ? (
                <li>
                  <Link
                    href={tender.document_url!.trim()}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1.5 break-all font-medium text-primary underline-offset-4 hover:underline"
                  >
                    <ExternalLinkIcon className="shrink-0" />
                    Document (TED)
                  </Link>
                </li>
              ) : null}
              {isValidHttpUrl(tender.tender_url) ? (
                <li>
                  <Link
                    href={tender.tender_url!.trim()}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1.5 break-all font-medium text-primary underline-offset-4 hover:underline"
                  >
                    <ExternalLinkIcon className="shrink-0" />
                    {truncateString(tender.tender_url!.trim(), 56)}
                  </Link>
                </li>
              ) : null}
              {isValidHttpUrl(tender.buyer_profile_url) ? (
                <li>
                  <Link
                    href={tender.buyer_profile_url!.trim()}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1.5 break-all font-medium text-primary underline-offset-4 hover:underline"
                  >
                    <ExternalLinkIcon className="shrink-0" />
                    Buyer profile
                  </Link>
                </li>
              ) : null}
            </ul>
          </ShowcaseSection>
        ) : null}
      </div>
    </div>
  );
}
