/* eslint-disable jsx-a11y/alt-text -- react-pdf <Image> is a PDF primitive, not an HTML img; it has no alt prop. */
import path from "node:path";
import { Document, Font, Image, Page, StyleSheet, Text, View } from "@react-pdf/renderer";
import type { Locale, PropertyDetailDto } from "@alterra/shared";
import { getBrandCopy } from "./brand";
import { contactInfo } from "./i18n";
import type { PropertyCopy } from "./propertyCopy";

/**
 * Branded, printable property sheet (A4) built with @react-pdf/renderer.
 * Fonts are TTF copies of the site fonts in assets/pdf-fonts (react-pdf does not render WOFF2 glyphs).
 * Images arrive already converted to JPEG data URIs (react-pdf cannot read WebP/AVIF).
 */

const fontDir = path.join(process.cwd(), "assets/pdf-fonts");
let fontsReady = false;
const registerFonts = () => {
  if (fontsReady) return;
  Font.register({
    family: "Cormorant",
    fonts: [
      { src: path.join(fontDir, "cormorant-garamond-500-normal.ttf"), fontWeight: 500 },
      { src: path.join(fontDir, "cormorant-garamond-500-italic.ttf"), fontWeight: 500, fontStyle: "italic" },
      { src: path.join(fontDir, "cormorant-garamond-600-normal.ttf"), fontWeight: 600 },
    ],
  });
  Font.register({
    family: "Manrope",
    fonts: [
      { src: path.join(fontDir, "manrope-400.ttf"), fontWeight: 400 },
      { src: path.join(fontDir, "manrope-600.ttf"), fontWeight: 600 },
    ],
  });
  Font.registerHyphenationCallback((word) => [word]);
  fontsReady = true;
};

const C = { ink: "#102B1E", forest: "#2B4D3F", gold: "#CC9E42", goldInk: "#7A5A1C", goldLight: "#DDB868", cream: "#F4EFE6", sand: "#E6DDCE", stone: "#575449" };

const s = StyleSheet.create({
  page: { backgroundColor: "#FFFFFF", color: C.ink, fontFamily: "Manrope", fontSize: 9, paddingTop: 86, paddingBottom: 78 },
  header: { position: "absolute", top: 0, left: 0, right: 0, height: 66, backgroundColor: C.ink, paddingHorizontal: 36, flexDirection: "row", justifyContent: "space-between", alignItems: "center" },
  ref: { color: C.goldLight, fontSize: 8, letterSpacing: 2.5, textTransform: "uppercase" },
  body: { paddingHorizontal: 36 },
  hero: { width: "100%", height: 300, objectFit: "cover", marginTop: -20 },
  eyebrow: { fontSize: 7.5, letterSpacing: 2.4, textTransform: "uppercase", color: C.goldInk },
  title: { fontFamily: "Cormorant", fontWeight: 600, fontSize: 28, lineHeight: 1.1, marginTop: 6 },
  rule: { width: 46, height: 1, backgroundColor: C.gold, marginVertical: 12 },
  priceRow: { flexDirection: "row", alignItems: "flex-end", justifyContent: "space-between" },
  price: { fontFamily: "Cormorant", fontWeight: 600, fontSize: 22 },
  muted: { color: C.stone },
  facts: { flexDirection: "row", flexWrap: "wrap", marginTop: 16, borderTopWidth: 1, borderTopColor: C.sand },
  fact: { width: "25%", paddingVertical: 9, paddingRight: 8, borderBottomWidth: 1, borderBottomColor: C.sand },
  factLabel: { fontSize: 7, letterSpacing: 1.4, textTransform: "uppercase", color: C.stone },
  factValue: { fontFamily: "Cormorant", fontWeight: 600, fontSize: 14, marginTop: 3 },
  h2: { fontFamily: "Cormorant", fontWeight: 600, fontSize: 17, marginTop: 22, marginBottom: 8 },
  para: { fontSize: 9.5, lineHeight: 1.55, marginBottom: 6 },
  cols: { flexDirection: "row", flexWrap: "wrap" },
  bullet: { width: "50%", flexDirection: "row", marginBottom: 4, paddingRight: 10 },
  dot: { width: 3, height: 3, backgroundColor: C.gold, marginTop: 4, marginRight: 6 },
  gallery: { flexDirection: "row", marginTop: 20, gap: 6 },
  thumb: { flex: 1, height: 120, objectFit: "cover" },
  invest: { backgroundColor: C.forest, color: C.cream, padding: 16, marginTop: 20 },
  investText: { fontFamily: "Cormorant", fontWeight: 500, fontSize: 14, lineHeight: 1.3, marginTop: 6 },
  footer: { position: "absolute", left: 0, right: 0, bottom: 0, backgroundColor: C.ink, color: C.cream, paddingHorizontal: 36, paddingVertical: 14 },
  footerRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "center" },
  signature: { color: C.goldLight, fontSize: 7, letterSpacing: 2.6, textTransform: "uppercase" },
  footerText: { fontSize: 7.5, color: C.cream, opacity: 0.8 },
  sample: { marginTop: 10, padding: 8, borderWidth: 1, borderColor: C.gold, color: C.goldInk, fontSize: 8 },
});

const sheetCopy = {
  en: {
    features: "Highlights",
    distances: "Approximate travel times",
    contact: "Private viewings and information",
    disclaimer: "Reference information, subject to change and to verification during the purchase process.",
    page: "Page",
    usd: "USD for reference",
  },
  es: {
    features: "Destacados",
    distances: "Tiempos aproximados de desplazamiento",
    contact: "Visitas privadas e información",
    disclaimer: "Información de referencia, sujeta a cambios y a verificación durante el proceso de compra.",
    page: "Página",
    usd: "USD de referencia",
  },
} as const;

export type SheetImages = { logo: string; hero: string | null; gallery: string[] };

export function PropertySheet({
  property,
  lang,
  copy,
  images,
  pageUrl,
}: {
  property: PropertyDetailDto;
  lang: Locale;
  copy: PropertyCopy;
  images: SheetImages;
  pageUrl: string;
}) {
  registerFonts();
  const t = sheetCopy[lang];
  const d = copy.detail;
  const brand = getBrandCopy(lang);
  const num = (n: number) => n.toLocaleString(lang === "es" ? "es-CO" : "en-US");
  const cop = (n: number) => `$ ${num(n)} COP`;
  const rent = property.operation === "rent";

  const facts: [string, string][] = [
    [d.type, copy.types[property.type]],
    property.bedrooms ? [d.bedrooms, String(property.bedrooms)] : null,
    property.bathrooms ? [d.bathrooms, String(property.bathrooms)] : null,
    property.parking ? [d.parking, String(property.parking)] : null,
    property.builtAreaM2 ? [d.builtArea, `${num(property.builtAreaM2)} m²`] : null,
    property.lotAreaM2 ? [d.lotArea, `${num(property.lotAreaM2)} m²`] : null,
    property.yearBuilt ? [d.yearBuilt, String(property.yearBuilt)] : null,
    property.adminFee ? [d.adminFee, cop(property.adminFee.cop)] : null,
    property.propertyTax ? [d.propertyTax, cop(property.propertyTax.cop)] : null,
  ].filter((f): f is [string, string] => f !== null);

  const highlights = [...property.features.map((f) => copy.features[f]), ...property.amenities];
  const distances = Object.entries(property.distances ?? {}).filter(([, v]) => typeof v === "number") as [keyof typeof d.distances, number][];
  const contacts = [contactInfo.email, contactInfo.phoneDisplay, contactInfo.whatsapp ? `WhatsApp +${contactInfo.whatsapp}` : null].filter(Boolean).join("   ·   ");

  const Footer = () => (
    <View style={s.footer} fixed>
      <View style={s.footerRow}>
        <Text style={s.signature}>{brand.signature}</Text>
        <Text style={s.footerText} render={({ pageNumber, totalPages }) => `${t.page} ${pageNumber} / ${totalPages}`} />
      </View>
      <Text style={[s.footerText, { marginTop: 6 }]}>{contacts}</Text>
      <Text style={[s.footerText, { marginTop: 2 }]}>{pageUrl}</Text>
    </View>
  );

  return (
    <Document title={`${property.title} · ${property.referenceCode}`} author="Alterra Estates" language={lang}>
      <Page size="A4" style={s.page}>
        <View style={s.header} fixed>
          <Image src={images.logo} style={{ width: 150, height: 29 }} />
          <Text style={s.ref}>
            {d.reference} {property.referenceCode}
          </Text>
        </View>

        {images.hero && <Image src={images.hero} style={s.hero} />}

        <View style={[s.body, { marginTop: 20 }]}>
          <Text style={s.eyebrow}>{property.location.name} · Antioquia, Colombia</Text>
          <Text style={s.title}>{property.title}</Text>
          <View style={s.rule} />
          <View style={s.priceRow}>
            {property.price ? (
              <View>
                <Text style={s.price}>
                  {cop(property.price.cop)}
                  {rent ? ` ${copy.card.perMonth}` : ""}
                </Text>
                <Text style={[s.muted, { marginTop: 2 }]}>
                  US$ {num(property.price.usd)} · {t.usd}
                </Text>
              </View>
            ) : (
              <Text style={s.price}>{copy.card.priceOnRequest}</Text>
            )}
            {property.badges.length > 0 && <Text style={s.ref}>{property.badges.map((b) => copy.badges[b]).join("  ·  ")}</Text>}
          </View>

          <View style={s.facts}>
            {facts.map(([label, value]) => (
              <View key={label} style={s.fact}>
                <Text style={s.factLabel}>{label}</Text>
                <Text style={s.factValue}>{value}</Text>
              </View>
            ))}
          </View>

          {property.isSample && <Text style={s.sample}>{d.sampleNotice}</Text>}

          <Text style={s.h2} minPresenceAhead={80}>
            {d.description}
          </Text>
          {property.description
            .split(/\n{2,}/)
            .filter(Boolean)
            .map((p, i) => (
              <Text key={i} style={s.para}>
                {p.trim()}
              </Text>
            ))}

          {highlights.length > 0 && (
            <View wrap={false}>
              <Text style={s.h2}>{t.features}</Text>
              <View style={s.cols}>
                {highlights.map((h) => (
                  <View key={h} style={s.bullet}>
                    <View style={s.dot} />
                    <Text>{h}</Text>
                  </View>
                ))}
              </View>
            </View>
          )}

          {distances.length > 0 && (
            <View wrap={false}>
              <Text style={s.h2}>{t.distances}</Text>
              <View style={s.cols}>
                {distances.map(([key, min]) => (
                  <View key={key} style={s.bullet}>
                    <View style={s.dot} />
                    <Text>
                      {d.distances[key]}: {min} {d.minutes}
                    </Text>
                  </View>
                ))}
              </View>
              <Text style={[s.muted, { fontSize: 8, marginTop: 4 }]}>{d.locationNote}</Text>
            </View>
          )}

          {images.gallery.length > 0 && (
            <View style={s.gallery} wrap={false}>
              {images.gallery.map((src, i) => (
                <Image key={i} src={src} style={s.thumb} />
              ))}
            </View>
          )}

          {property.investmentNotes && (
            <View style={s.invest} wrap={false}>
              <Text style={s.signature}>{d.investment}</Text>
              <Text style={s.investText}>{property.investmentNotes}</Text>
              <Text style={{ fontSize: 7.5, marginTop: 8, opacity: 0.85 }}>{d.investmentDisclaimer}</Text>
            </View>
          )}

          <View wrap={false} style={{ marginTop: 22 }}>
            <Text style={s.eyebrow}>{t.contact}</Text>
            <Text style={[s.para, { marginTop: 6 }]}>{d.interestText}</Text>
            <Text style={[s.muted, { fontSize: 7.5 }]}>{t.disclaimer}</Text>
          </View>
        </View>
        <Footer />
      </Page>
    </Document>
  );
}
