"use client";

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

// ─── Brand tokens ─────────────────────────────────────────────────────────────
// hsl(215 50% 23%) → #1d3658   hsl(42 55% 50%) → #c69b39   hsl(218 35% 11%) → #121926
const C = {
  navy:     "#1d3658",
  gold:     "#c69b39",
  darkNavy: "#121926",
  lightBg:  "#f4f6fa",
  white:    "#ffffff",
  textDark: "#1a2235",
  textMid:  "#3d4d6a",
  textMute: "#6b7a99",
  border:   "#dde3ef",
  rowAlt:   "#f8fafd",
};

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

  // ─── 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: {
    flex: 1,
    fontSize: 7.5,
    fontFamily: "Helvetica-Bold",
    color: C.navy,
    letterSpacing: 1.8,
    textTransform: "uppercase",
  },
  sectionRule: {
    height: 1,
    backgroundColor: C.border,
    marginLeft: 8,
    flex: 1,
  },

  // ─── 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,
  },

  // ─── Badge (service) ────────────────────────────────────────────────────────
  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-QR-${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 Field({
  label,
  children,
  last = false,
  alt = false,
}: {
  label: string;
  children: React.ReactNode;
  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}>{children}</View>
    </View>
  );
}

function FieldText({
  label,
  value,
  last = false,
  alt = false,
}: {
  label: string;
  value: string;
  last?: boolean;
  alt?: boolean;
}) {
  return (
    <Field label={label} last={last} alt={alt}>
      <Text style={s.fieldValueText}>{value}</Text>
    </Field>
  );
}

// ─── Document ────────────────────────────────────────────────────────────────
export function QuotePDF({
  quote,
  logoUrl,
}: {
  quote: QuoteRequest;
  logoUrl: string;
}) {
  const ref = refNumber(quote.id, quote.created_at);
  const receivedDate = fmtDate(quote.created_at);

  // Build project fields list (for determining stripe + last)
  type PField = { label: string; value: string };
  const projectFields: PField[] = [
    { label: "Project Location", value: quote.project_location },
    ...(quote.delivery_deadline
      ? [{ label: "Delivery Deadline", value: fmtDate(quote.delivery_deadline) }]
      : []),
    ...(quote.personnel_required != null
      ? [{ label: "Personnel Required", value: String(quote.personnel_required) }]
      : []),
    ...(quote.scope_of_work
      ? [{ label: "Scope of Work", value: quote.scope_of_work }]
      : []),
    ...(quote.primary_concerns
      ? [{ label: "Primary Concerns", value: quote.primary_concerns }]
      : []),
    ...(quote.previous_inspections
      ? [{ label: "Previous Inspections", value: quote.previous_inspections }]
      : []),
  ];

  const logisticsFields: PField[] = [
    ...(quote.site_accessibility
      ? [{ label: "Site Accessibility", value: quote.site_accessibility }]
      : []),
    ...(quote.permits_required
      ? [{ label: "Permits Required", value: quote.permits_required }]
      : []),
    ...(quote.visas_required
      ? [{ label: "Visas Required", value: quote.visas_required }]
      : []),
    ...(quote.travel_provided
      ? [{ label: "Travel & Accommodation", value: quote.travel_provided }]
      : []),
  ];

  return (
    <Document
      title={`Quotation Request – ${quote.company_name}`}
      author="Petro-Base Group"
      subject="Project Quotation Request"
      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}>QUOTATION REQUEST</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 project quotation request submitted through
              the Petro-Base Group website. The information herein is strictly
              confidential and intended solely for authorised internal review and
              response.
            </Text>
          </View>

          {/* ── Contact Information ─────────────────────────────────────── */}
          <View style={s.section}>
            <SectionTitle label="Contact Information" />
            <View style={s.table}>
              <FieldText
                label="Full Name"
                value={`${quote.first_name} ${quote.last_name}`}
                alt
              />
              <FieldText label="Email Address" value={quote.email} />
              <FieldText label="Company" value={quote.company_name} alt />
              <Field label="Service Required" last>
                <View style={s.badge}>
                  <Text style={s.badgeText}>
                    {quote.service?.title ?? "Others"}
                  </Text>
                </View>
              </Field>
            </View>
          </View>

          {/* ── Project Details ─────────────────────────────────────────── */}
          <View style={s.section}>
            <SectionTitle label="Project Details" />
            <View style={s.table}>
              {projectFields.map((f, i) => (
                <FieldText
                  key={f.label}
                  label={f.label}
                  value={f.value}
                  alt={i % 2 !== 0}
                  last={i === projectFields.length - 1}
                />
              ))}
            </View>
          </View>

          {/* ── Logistics ───────────────────────────────────────────────── */}
          {logisticsFields.length > 0 && (
            <View style={s.section}>
              <SectionTitle label="Logistics & Site Access" />
              <View style={s.table}>
                {logisticsFields.map((f, i) => (
                  <FieldText
                    key={f.label}
                    label={f.label}
                    value={f.value}
                    alt={i % 2 !== 0}
                    last={i === logisticsFields.length - 1}
                  />
                ))}
              </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>
  );
}
