"use client";

import {
  Document,
  Page,
  Text,
  View,
  StyleSheet,
  Image,
} from "@react-pdf/renderer";
import type { ContactSubmission } from "@/services/contacts";

// ─── Brand tokens ─────────────────────────────────────────────────────────────
const C = {
  navy:     "#1d3658",
  gold:     "#c69b39",
  darkNavy: "#121926",
  white:    "#ffffff",
  textDark: "#1a2235",
  textMid:  "#3d4d6a",
  textMute: "#6b7a99",
  border:   "#dde3ef",
  rowAlt:   "#f8fafd",
};

// ─── Styles ───────────────────────────────────────────────────────────────────
const s = StyleSheet.create({
  page: {
    backgroundColor: C.white,
    fontFamily: "Helvetica",
    fontSize: 9,
    color: C.textDark,
    paddingTop: 104,
    paddingBottom: 64,
  },

  // ─── Header (fixed) ─────────────────────────────────────────────────────────
  header: { position: "absolute", top: 0, left: 0, right: 0 },
  headerInner: {
    backgroundColor: C.navy,
    paddingHorizontal: 40,
    paddingTop: 20,
    paddingBottom: 18,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  logo: { width: 128, height: 32, objectFit: "contain" },
  headerRight: { alignItems: "flex-end" },
  headerEyebrow: {
    fontSize: 6.5,
    fontFamily: "Helvetica-Bold",
    color: C.gold,
    letterSpacing: 2.5,
    textTransform: "uppercase",
  },
  headerTitle: {
    fontSize: 16,
    fontFamily: "Helvetica-Bold",
    color: C.white,
    letterSpacing: 1.5,
    marginTop: 3,
  },
  headerMeta: { fontSize: 7.5, color: "rgba(255,255,255,0.45)", marginTop: 4 },
  goldStripe: { height: 4, backgroundColor: C.gold },

  // ─── Body ────────────────────────────────────────────────────────────────────
  body: { paddingHorizontal: 40, paddingTop: 18 },

  // ─── Notice banner ──────────────────────────────────────────────────────────
  notice: {
    backgroundColor: "#fffbf0",
    borderLeftWidth: 3,
    borderLeftColor: C.gold,
    borderRadius: 2,
    paddingHorizontal: 12,
    paddingVertical: 9,
    marginBottom: 24,
  },
  noticeLabel: {
    fontSize: 7,
    fontFamily: "Helvetica-Bold",
    color: C.gold,
    letterSpacing: 1.5,
    textTransform: "uppercase",
    marginBottom: 3,
  },
  noticeText: { fontSize: 8, color: C.textMute, lineHeight: 1.6 },

  // ─── Section ────────────────────────────────────────────────────────────────
  section: { marginBottom: 22 },
  sectionHeading: { flexDirection: "row", alignItems: "center", marginBottom: 10 },
  sectionDot: { width: 7, height: 7, backgroundColor: C.gold, borderRadius: 1, marginRight: 7 },
  sectionTitle: {
    fontSize: 7.5,
    fontFamily: "Helvetica-Bold",
    color: C.navy,
    letterSpacing: 1.8,
    textTransform: "uppercase",
  },

  // ─── Field table ────────────────────────────────────────────────────────────
  table: { borderWidth: 1, borderColor: C.border, borderRadius: 3, overflow: "hidden" },
  fieldRow: { flexDirection: "row", borderBottomWidth: 1, borderBottomColor: C.border },
  fieldRowLast: { flexDirection: "row" },
  fieldRowAlt: { backgroundColor: C.rowAlt },
  fieldLabel: {
    width: 148,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRightWidth: 1,
    borderRightColor: C.border,
    backgroundColor: "#f1f5fb",
  },
  fieldLabelText: {
    fontSize: 7.5,
    fontFamily: "Helvetica-Bold",
    color: C.textMid,
    textTransform: "uppercase",
    letterSpacing: 0.5,
  },
  fieldValue: { flex: 1, paddingHorizontal: 12, paddingVertical: 8 },
  fieldValueText: { fontSize: 9, color: C.textDark, lineHeight: 1.55 },

  // ─── Message block ──────────────────────────────────────────────────────────
  messageBox: {
    borderWidth: 1,
    borderColor: C.border,
    borderRadius: 3,
    padding: 14,
    backgroundColor: C.rowAlt,
  },
  messageText: { fontSize: 9, color: C.textDark, lineHeight: 1.7 },

  // ─── Badge ──────────────────────────────────────────────────────────────────
  badge: {
    backgroundColor: "#e4ecf9",
    borderRadius: 3,
    paddingHorizontal: 8,
    paddingVertical: 3,
    alignSelf: "flex-start",
  },
  badgeText: { fontSize: 7.5, fontFamily: "Helvetica-Bold", color: C.navy, letterSpacing: 0.3 },

  // ─── Footer (fixed) ─────────────────────────────────────────────────────────
  footer: {
    position: "absolute",
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: C.darkNavy,
    paddingHorizontal: 40,
    paddingVertical: 13,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
  },
  footerLeft: { flex: 1 },
  footerAddrLine: { fontSize: 7, color: "rgba(255,255,255,0.38)", lineHeight: 1.7 },
  footerCenter: { flex: 1, alignItems: "center" },
  footerLogo: { width: 90, height: 23, objectFit: "contain" },
  footerConfidential: {
    fontSize: 6,
    fontFamily: "Helvetica-Bold",
    color: C.gold,
    letterSpacing: 2,
    textTransform: "uppercase",
    marginTop: 4,
    textAlign: "center",
  },
  footerRight: { flex: 1, alignItems: "flex-end" },
  footerContactLine: { fontSize: 7, color: "rgba(255,255,255,0.38)", lineHeight: 1.7 },
  footerPage: { fontSize: 6.5, color: "rgba(255,255,255,0.25)", marginTop: 4 },
});

// ─── Helpers ─────────────────────────────────────────────────────────────────
function fmtDate(iso: string) {
  return new Date(iso).toLocaleDateString("en-GB", {
    day: "numeric", month: "long", year: "numeric",
  });
}

function refNumber(id: number, iso: string) {
  const year = new Date(iso).getFullYear();
  return `PBG-CS-${year}-${String(id).padStart(4, "0")}`;
}

// ─── Sub-components ──────────────────────────────────────────────────────────
function SectionTitle({ label }: { label: string }) {
  return (
    <View style={s.sectionHeading}>
      <View style={s.sectionDot} />
      <Text style={s.sectionTitle}>{label}</Text>
    </View>
  );
}

function FieldText({
  label, value, last = false, alt = false,
}: { label: string; value: string; last?: boolean; alt?: boolean }) {
  return (
    <View style={[last ? s.fieldRowLast : s.fieldRow, alt ? s.fieldRowAlt : {}]}>
      <View style={s.fieldLabel}>
        <Text style={s.fieldLabelText}>{label}</Text>
      </View>
      <View style={s.fieldValue}>
        <Text style={s.fieldValueText}>{value}</Text>
      </View>
    </View>
  );
}

function FieldBadge({
  label, value, last = false,
}: { label: string; value: string; last?: boolean }) {
  return (
    <View style={last ? s.fieldRowLast : s.fieldRow}>
      <View style={s.fieldLabel}>
        <Text style={s.fieldLabelText}>{label}</Text>
      </View>
      <View style={s.fieldValue}>
        <View style={s.badge}>
          <Text style={s.badgeText}>{value}</Text>
        </View>
      </View>
    </View>
  );
}

// ─── Document ────────────────────────────────────────────────────────────────
export function ContactPDF({
  contact,
  logoUrl,
}: {
  contact: ContactSubmission;
  logoUrl: string;
}) {
  const ref = refNumber(contact.id, contact.created_at);
  const receivedDate = fmtDate(contact.created_at);

  return (
    <Document
      title={`Contact Enquiry – ${contact.full_name}`}
      author="Petro-Base Group"
      subject="Contact Form Submission"
      creator="Petro-Base Group Admin Portal"
    >
      <Page size="A4" style={s.page}>

        {/* ── Fixed Header ─────────────────────────────────────────────── */}
        <View style={s.header} fixed>
          <View style={s.headerInner}>
            <Image src={logoUrl} style={s.logo} />
            <View style={s.headerRight}>
              <Text style={s.headerEyebrow}>Petro-Base Group</Text>
              <Text style={s.headerTitle}>CONTACT ENQUIRY</Text>
              <Text style={s.headerMeta}>
                Ref: {ref}   ·   Received: {receivedDate}
              </Text>
            </View>
          </View>
          <View style={s.goldStripe} />
        </View>

        {/* ── Body ─────────────────────────────────────────────────────── */}
        <View style={s.body}>

          {/* Confidential notice */}
          <View style={s.notice}>
            <Text style={s.noticeLabel}>Confidential Document</Text>
            <Text style={s.noticeText}>
              This document contains a contact enquiry submitted through the
              Petro-Base Group website. The information herein is strictly
              confidential and intended solely for authorised internal review
              and response.
            </Text>
          </View>

          {/* ── Sender Information ──────────────────────────────────── */}
          <View style={s.section}>
            <SectionTitle label="Sender Information" />
            <View style={s.table}>
              <FieldText label="Full Name"  value={contact.full_name} alt />
              <FieldText label="Email"      value={contact.email} />
              <FieldText label="Phone"      value={contact.phone_number} alt />
              <FieldText label="Company"    value={contact.company} />
              <FieldBadge
                label="Service Enquired"
                value={contact.service?.title ?? "Others"}
                last
              />
            </View>
          </View>

          {/* ── Message ─────────────────────────────────────────────── */}
          <View style={s.section}>
            <SectionTitle label="Message" />
            <View style={s.messageBox}>
              <Text style={s.messageText}>{contact.message}</Text>
            </View>
          </View>

        </View>

        {/* ── Fixed Footer ─────────────────────────────────────────────── */}
        <View style={s.footer} fixed>
          <View style={s.footerLeft}>
            <Text style={s.footerAddrLine}>
              KM 17 Port Harcourt Aba Expressway (By Old Toll Gate)
            </Text>
            <Text style={s.footerAddrLine}>
              Iriebe, Port Harcourt, Rivers State, Nigeria
            </Text>
          </View>

          <View style={s.footerCenter}>
            <Image src={logoUrl} style={s.footerLogo} />
            <Text style={s.footerConfidential}>Confidential</Text>
          </View>

          <View style={s.footerRight}>
            <Text style={s.footerContactLine}>+234-706-749-5538</Text>
            <Text style={s.footerContactLine}>info@petrobasegroup.com</Text>
            <Text
              style={s.footerPage}
              render={({ pageNumber, totalPages }) =>
                `Page ${pageNumber} of ${totalPages}`
              }
            />
          </View>
        </View>

      </Page>
    </Document>
  );
}
