import { ShowcaseSection } from "@/components/Layouts/showcase-section";
import type { TTenderAddress, TTenderDetails } from "@/lib/api/types/Tenders";
import { cn } from "@/lib/utils";
import Link from "next/link";
import {
  HEADER_SCROLL_MARGIN,
  SHOWCASE_CENTERED_BODY,
  TENDER_SECTION_IDS,
} from "../constants";
import {
  hasBuyerExtendedDetails,
  isNonEmptyTrimmed,
  isValidHttpUrl,
} from "../tender-display-utils";
import { SectionHeading } from "./section-heading";

type TenderProcurementSectionProps = {
  tender: TTenderDetails;
};

const TED_NOTICE_DETAIL = "https://ted.europa.eu/en/notice/-/detail";

function uniqueTrimmedNoticeIds(ids: string[] | undefined): string[] {
  if (!ids?.length) return [];
  const seen = new Set<string>();
  const out: string[] = [];
  for (const id of ids) {
    const trimmed = id?.trim();
    if (!trimmed || seen.has(trimmed)) continue;
    seen.add(trimmed);
    out.push(trimmed);
  }
  return out;
}

function formatAddressLines(addr: TTenderAddress | undefined): string[] {
  if (!addr) return [];
  const lines: string[] = [];
  if (isNonEmptyTrimmed(addr.street_name)) lines.push(addr.street_name!.trim());
  const cityLine = [addr.postal_zone, addr.city_name]
    .map((s) => s?.trim())
    .filter(Boolean)
    .join(" ");
  if (cityLine) lines.push(cityLine);
  const regionCountry = [addr.country_subentity_code, addr.country_code]
    .map((s) => s?.trim())
    .filter(Boolean)
    .join(" · ");
  if (regionCountry) lines.push(regionCountry);
  return lines;
}

export function TenderProcurementSection({
  tender,
}: TenderProcurementSectionProps) {
  const relatedNoticeIds = uniqueTrimmedNoticeIds(
    tender.related_notice_publication_ids,
  );
  const noticeTypeCode = tender.notice_type_code?.trim();
  const mainCpv =
    tender.main_classification_display?.trim() ||
    tender.main_classification?.trim();
  const noticePubId = tender.notice_publication_id?.trim();
  const durationParts = [
    tender.duration?.trim(),
    tender.duration_unit?.trim(),
  ].filter(Boolean);
  const durationLabel = durationParts.join(" ");

  const buyer = tender.buyer_organization;
  const buyerAddressLines = formatAddressLines(buyer.address);
  const showBuyerOrgName = isNonEmptyTrimmed(buyer.name);
  const showBuyerExtended = hasBuyerExtendedDetails(tender);

  return (
    <div id={TENDER_SECTION_IDS.procurement} className={HEADER_SCROLL_MARGIN}>
      <SectionHeading>Procurement</SectionHeading>
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-5">
        {isNonEmptyTrimmed(tender.tender_id) ? (
          <ShowcaseSection title="Tender ID" {...SHOWCASE_CENTERED_BODY}>
            <span className="font-medium text-dark dark:text-white">
              {tender.tender_id}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.project_name) ? (
          <ShowcaseSection title="Project name" {...SHOWCASE_CENTERED_BODY}>
            <span className="break-words font-medium text-dark dark:text-white">
              {tender.project_name}
            </span>
          </ShowcaseSection>
        ) : null}

        {showBuyerOrgName ? (
          <ShowcaseSection
            title="Buyer organization"
            rootClassName={SHOWCASE_CENTERED_BODY.rootClassName}
            className={cn(
              "sm:col-span-2 xl:col-span-1 2xl:col-span-2",
              SHOWCASE_CENTERED_BODY.className,
            )}
          >
            <span className="font-medium text-dark dark:text-white">
              {buyer.name}
            </span>
          </ShowcaseSection>
        ) : null}

        {noticePubId ? (
          <ShowcaseSection
            title="Notice publication ID"
            {...SHOWCASE_CENTERED_BODY}
          >
            <span className="font-medium text-primary underline-offset-4 hover:underline">
              <Link
                href={`${TED_NOTICE_DETAIL}/${noticePubId}`}
                target="_blank"
                rel="noopener noreferrer"
              >
                {noticePubId}
              </Link>
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.procurement_project_id) ? (
          <ShowcaseSection
            title="Procurement project ID"
            {...SHOWCASE_CENTERED_BODY}
          >
            <span className="break-all font-medium text-dark dark:text-white">
              {tender.procurement_project_id}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.contract_folder_id) ? (
          <ShowcaseSection
            title="Procedure Identifier"
            {...SHOWCASE_CENTERED_BODY}
          >
            <span className="break-all font-medium text-dark dark:text-white">
              {tender.contract_folder_id}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.contract_notice_id) ? (
          <ShowcaseSection
            title="Contract notice ID"
            {...SHOWCASE_CENTERED_BODY}
          >
            <span className="break-all font-medium text-dark dark:text-white">
              {tender.contract_notice_id}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.notice_identifier) ? (
          <ShowcaseSection
            title="Notice identifier"
            {...SHOWCASE_CENTERED_BODY}
          >
            <span className="break-all font-medium text-dark dark:text-white">
              {tender.notice_identifier}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.notice_version) ? (
          <ShowcaseSection title="Notice version" {...SHOWCASE_CENTERED_BODY}>
            <span className="font-medium text-dark dark:text-white">
              {tender.notice_version}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.gazette_id) ? (
          <ShowcaseSection title="Gazette ID" {...SHOWCASE_CENTERED_BODY}>
            <span className="font-medium text-dark dark:text-white">
              {tender.gazette_id}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.form_type) ? (
          <ShowcaseSection title="Form type" {...SHOWCASE_CENTERED_BODY}>
            <span className="font-medium text-dark dark:text-white">
              {tender.form_type}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.notice_sub_type_code) ? (
          <ShowcaseSection
            title="Notice sub-type code"
            {...SHOWCASE_CENTERED_BODY}
          >
            <span className="font-medium text-dark dark:text-white">
              {tender.notice_sub_type_code}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.source) ? (
          <ShowcaseSection title="Source" {...SHOWCASE_CENTERED_BODY}>
            <span className="font-medium text-dark dark:text-white">
              {tender.source}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.procedure_code) ? (
          <ShowcaseSection title="Procedure code" {...SHOWCASE_CENTERED_BODY}>
            <span className="font-medium text-dark dark:text-white">
              {tender.procedure_code}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.procurement_type_code) ? (
          <ShowcaseSection title="Procurement type" {...SHOWCASE_CENTERED_BODY}>
            <span className="font-medium text-dark dark:text-white">
              {tender.procurement_type_code}
            </span>
          </ShowcaseSection>
        ) : null}

        {noticeTypeCode ? (
          <ShowcaseSection title="Notice type code" {...SHOWCASE_CENTERED_BODY}>
            <span className="font-medium text-dark dark:text-white">
              {noticeTypeCode}
            </span>
          </ShowcaseSection>
        ) : null}

        {mainCpv ? (
          <ShowcaseSection
            title="Main classification (CPV)"
            {...SHOWCASE_CENTERED_BODY}
          >
            <span className="font-medium text-dark dark:text-white">
              {mainCpv}
            </span>
          </ShowcaseSection>
        ) : null}

        {isNonEmptyTrimmed(tender.estimated_value_vat_basis) ? (
          <ShowcaseSection
            title="Estimated value (VAT basis)"
            {...SHOWCASE_CENTERED_BODY}
          >
            <span className="font-medium text-dark dark:text-white">
              {tender.estimated_value_vat_basis}
            </span>
          </ShowcaseSection>
        ) : null}

        {durationLabel ? (
          <ShowcaseSection title="Duration" {...SHOWCASE_CENTERED_BODY}>
            <span className="font-medium text-dark dark:text-white">
              {durationLabel}
            </span>
          </ShowcaseSection>
        ) : null}

        {relatedNoticeIds.length > 0 ? (
          <ShowcaseSection
            title="Related notice publications"
            rootClassName={cn(
              SHOWCASE_CENTERED_BODY.rootClassName,
              "sm:col-span-2 xl:col-span-3 2xl:col-span-5",
            )}
            className="flex min-h-0 flex-1 flex-col items-stretch justify-center"
          >
            <ul className="flex flex-wrap justify-center gap-x-3 gap-y-2">
              {relatedNoticeIds.map((noticeId) => (
                <li key={noticeId}>
                  <Link
                    href={`${TED_NOTICE_DETAIL}/${noticeId}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="font-medium text-primary underline-offset-4 hover:underline"
                  >
                    {noticeId}
                  </Link>
                </li>
              ))}
            </ul>
          </ShowcaseSection>
        ) : null}
      </div>

      {showBuyerExtended ? (
        <div className="mt-8 space-y-4">
          <h3 className="text-sm font-semibold uppercase tracking-wide text-dark-5 dark:text-dark-6">
            Buyer contact &amp; address
          </h3>
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-5">
            {isNonEmptyTrimmed(buyer.company_id) ? (
              <ShowcaseSection title="Company ID" {...SHOWCASE_CENTERED_BODY}>
                <span className="font-medium text-dark dark:text-white">
                  {buyer.company_id}
                </span>
              </ShowcaseSection>
            ) : null}
            {isValidHttpUrl(buyer.website_uri) ? (
              <ShowcaseSection
                title="Buyer website"
                {...SHOWCASE_CENTERED_BODY}
              >
                <Link
                  href={buyer.website_uri!.trim()}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="break-all font-medium text-primary underline-offset-4 hover:underline"
                >
                  {buyer.website_uri!.trim()}
                </Link>
              </ShowcaseSection>
            ) : null}
            {isNonEmptyTrimmed(buyer.contact_name) ? (
              <ShowcaseSection title="Contact name" {...SHOWCASE_CENTERED_BODY}>
                <span className="font-medium text-dark dark:text-white">
                  {buyer.contact_name}
                </span>
              </ShowcaseSection>
            ) : null}
            {isNonEmptyTrimmed(buyer.contact_telephone) ? (
              <ShowcaseSection
                title="Contact telephone"
                {...SHOWCASE_CENTERED_BODY}
              >
                <span className="font-medium text-dark dark:text-white">
                  {buyer.contact_telephone}
                </span>
              </ShowcaseSection>
            ) : null}
            {isNonEmptyTrimmed(buyer.contact_email) ? (
              <ShowcaseSection
                title="Contact email"
                {...SHOWCASE_CENTERED_BODY}
              >
                <a
                  href={`mailto:${buyer.contact_email!.trim()}`}
                  className="break-all font-medium text-primary underline-offset-4 hover:underline"
                >
                  {buyer.contact_email!.trim()}
                </a>
              </ShowcaseSection>
            ) : null}
            {buyerAddressLines.length > 0 ? (
              <ShowcaseSection
                title="Address"
                rootClassName={cn(
                  SHOWCASE_CENTERED_BODY.rootClassName,
                  "sm:col-span-2 xl:col-span-2 2xl:col-span-3",
                )}
                className="text-start"
              >
                <address className="not-italic">
                  {buyerAddressLines.map((line, i) => (
                    <div
                      key={`${line}-${i}`}
                      className="text-sm font-medium text-dark dark:text-white"
                    >
                      {line}
                    </div>
                  ))}
                </address>
              </ShowcaseSection>
            ) : null}
          </div>
        </div>
      ) : null}
    </div>
  );
}
