import React from "react";

const primaryOf = (arr = []) => {
  if (!Array.isArray(arr) || arr.length === 0) return null;
  return arr.find((item) => item?.meta?.rank === 0) || arr[0];
};

const safe = (val, fallback = "—") =>
  val === undefined || val === null || val === "" ? fallback : val;

const fmtName = (n) => {
  if (!n) return "—";
  return n.data || [n.first, n.middle, n.last].filter(Boolean).join(" ");
};

const fmtAddress = (a) => {
  if (!a) return "—";
  return a.data || a.complete || "—";
};

const fmtMoney = (n) =>
  typeof n === "number"
    ? n.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 })
    : "—";

const relationshipLabel = (type, subType) => {
  const typeMap = { R: "Relative", A: "Associate" };
  const subMap = {
    M: "Spouse",
    C: "Child",
    P: "Parent",
    S: "Sibling",
    I: "Relative",
    O: "Associate",
    A: "Associate",
    R: "Relative",
  };
  const base = typeMap[type] || "Contact";
  const sub = subMap[subType];
  return sub ? `${base} (${sub})` : base;
};

const Section = ({ title, count, children }) => (
  <div className="mb-4">
    <h6 className="fw-bold border-bottom pb-1 mb-2">
      {title}
      {typeof count === "number" && (
        <span className="text-muted fw-normal"> &nbsp;( Found {count} {count === 1 ? "entry" : "entries"} )</span>
      )}
    </h6>
    {children}
  </div>
);

const EmptyRow = ({ colSpan = 1, label = "Found None" }) => (
  <tr>
    <td colSpan={colSpan} className="text-muted text-center py-2">
      {label}
    </td>
  </tr>
);

const SummaryRow = ({ label, count }) => (
  <div className="d-flex justify-content-between align-items-center py-1 border-bottom">
    <span className="text-muted">{label}</span>
    <span className="fw-semibold">{count > 0 ? `Found ${count}` : "Found None"}</span>
  </div>
);

const findEnvelope = (reportResponse) => {
  const candidates = [
    reportResponse?.data?.data,
    reportResponse?.data,
    reportResponse,
  ];

  return candidates.find((c) => c && Array.isArray(c.result)) || {};
};

export default function IdiReportDisplay({ reportResponse }) {
  const envelope = findEnvelope(reportResponse);
  const results = envelope.result || [];
  const result = results[0];
  const reportId = envelope.id;

  const disclaimer = 'Interactive Data, LLC (“IDI”) is not a “consumer reporting agency” and its services do not constitute “consumer reports,” as these terms are defined by the Fair Credit Reporting Act, 15 U.S.C. § 1681 et seq. (“FCRA”) or similar state statutes. Accordingly, IDI services may not be used in whole or in part as a factor in establishing an individual`’`s eligibility for credit, insurance, employment, or for any other eligibility purpose permitted by the FCRA' +

    'idiCORE may only be accessed and used in accordance with your Subscriber Agreement, the Gramm-Leach-Bliley Act (“GLBA”), the Driver’s Privacy Protection Act (“DPPA”), and other applicable laws. By accessing and using idiCORE, Subscriber reaffirms its understanding and agreement to the foregoing. Subscriber shall be liable for its use of this system. Any misuse, or violation of Subscriber agreements and/or applicable law, will result in investigation and termination of access.'

  if (!result) {
    return <p className="text-muted">No report data available.</p>;
  }

  const names = result.name || [];
  const dobs = result.dob || [];
  const addresses = result.address || [];
  const phones = result.phone || [];
  const emails = result.email || [];
  const bankruptcies = result.bankruptcy || [];
  const employments = result.employment || [];
  const properties = result.property || [];
  const relationships = result.relationship || [];
  const vehicles = result.motorVehicle || [];
  const criminals = result.criminal || [];
  const judgments = result.judgment || [];
  const liens = result.lien || [];
  const aircraft = result.aircraft || [];
  const businesses = result.business || [];
  const professional = result.professional || [];

  const primaryName = primaryOf(names);
  const primaryDob = primaryOf(dobs);
  const primaryAddress = primaryOf(addresses);
  const primaryPhone = primaryOf(phones);
  const aliases = names.filter((n) => n !== primaryName);

  const summaryItems = [
    ["Bankruptcies", bankruptcies.length],
    ["Employments", employments.length],
    ["Properties", properties.length],
    ["Addresses", addresses.length],
    ["Phones", phones.length],
    ["Emails", emails.length],
    ["Relationships", relationships.length],
    ["Motor Vehicles", vehicles.length],
    ["Criminal/Infractions", criminals.length],
    ["Judgments", judgments.length],
    ["Liens", liens.length],
    ["Aircraft", aircraft.length],
    ["Businesses", businesses.length],
    ["Professional Licenses", professional.length],
  ];

  return (
    <div className="idi-report">
      <header className="mb-4 text-center">
        <h4 className="fw-bold mb-1">Mayer Consulting Solutions, Inc.</h4>
        <p className="text-muted text-uppercase small mb-1" style={{ letterSpacing: "2px" }}>
          Comprehensive Background Report on
        </p>
        <h5 className="text-uppercase fw-semibold mb-1" style={{ letterSpacing: "1px" }}>
          {fmtName(primaryName)}
        </h5>
        <p className="text-muted small mb-0">
          Report id: {safe(reportId)}
        </p>
      </header>
      <div className="mb-3 w-100 text-start">
        <div
          className="p-3 rounded-end text-start"
          style={{
            backgroundColor: "#fffbeb",
            borderLeft: "4px solid #facc15",
            textAlign: "left",
          }}
        >
          <div className="d-flex align-items-start gap-2">
            <svg
              width="20"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              stroke="#eab308"
              strokeWidth="2"
              style={{ flexShrink: 0, marginTop: "2px" }}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"
              />
            </svg>

            <div className="text-start" style={{ textAlign: "left" }}>
              <p className="mb-1 fw-semibold" style={{ color: "#92400e", fontSize: "0.9rem", textAlign: "left" }}>
                Compliance Notice
              </p>
              <p className="mb-0" style={{ color: "#b45309", fontSize: "0.8rem", textAlign: "left" }}>
                {disclaimer}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* ---------------- Subject Info + Profile Summary (side by side) ---------------- */}
      <div className="row mb-4">

        {/* Left: subject info */}
        <div className="col-md-6 mb-3 mb-md-0">
          <div className="p-3 border rounded bg-light h-100">
            <h5 className="fw-bold mb-1">{fmtName(primaryName)}</h5>

            {aliases.length > 0 && (
              <div className="mb-2">
                <span className="text-muted">Also known as: </span>
                {aliases.map(fmtName).join("; ")}
              </div>
            )}

            <div className="mb-2">
              <div className="text-muted small">Date of Birth / Age</div>
              <div>
                {safe(primaryDob?.date?.data)}
                {primaryDob?.age ? ` (${primaryDob.age} yrs)` : ""}
              </div>
            </div>

            <div className="mb-2">
              <div className="text-muted small">Primary Phone</div>
              <div>
                {primaryPhone
                  ? `${primaryPhone.number}${primaryPhone.type ? ` (${primaryPhone.type})` : ""}`
                  : "—"}
              </div>
            </div>

            <div>
              <div className="text-muted small">Current Address</div>
              <div>{fmtAddress(primaryAddress)}</div>
            </div>
          </div>
        </div>

        {/* Right: profile summary, plain rows */}
        <div className="col-md-6">
          <h6 className="fw-bold mb-2">Profile Summary</h6>
          <div>
            {summaryItems.map(([label, count]) => (
              <SummaryRow key={label} label={label} count={count} />
            ))}
          </div>
        </div>
      </div>

      <Section title="City Summary" count={addresses.length}>
        <table className="table table-bordered table-sm">
          <thead>
            <tr>
              <th>City</th>
              <th>Date Range</th>
            </tr>
          </thead>
          <tbody>
            {addresses.length === 0 ? (
              <EmptyRow colSpan={2} />
            ) : (
              addresses.map((a, i) => (
                <tr key={i}>
                  <td>
                    {a.city ? `${a.city}${a.state ? `, ${a.state}` : ""}` : "—"}
                  </td>
                  <td>{safe(a.dateRange)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </Section>

      {/* ---------------- County Summary ---------------- */}
      <Section title="County Summary" count={addresses.length}>
        <table className="table table-bordered table-sm">
          <thead>
            <tr>
              <th>County</th>
              <th>Date Range</th>
            </tr>
          </thead>
          <tbody>
            {addresses.length === 0 ? (
              <EmptyRow colSpan={2} />
            ) : (
              addresses.map((a, i) => (
                <tr key={i}>
                  <td>
                    {a.county ? `${a.county}${a.state ? `, ${a.state}` : ""}` : "—"}
                  </td>
                  <td>{safe(a.dateRange)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </Section>

      {/* ---------------- Addresses ---------------- */}
      <Section title="Addresses" count={addresses.length}>
        <table className="table table-bordered table-sm">
          <thead>
            <tr>
              <th>Address</th>
              <th>County</th>
              <th>Date Range</th>
            </tr>
          </thead>
          <tbody>
            {addresses.length === 0 ? (
              <EmptyRow colSpan={3} />
            ) : (
              addresses.map((a, i) => (
                <tr key={i}>
                  <td>{fmtAddress(a)}</td>
                  <td>{safe(a.county)}</td>
                  <td>{safe(a.dateRange)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </Section>

      {/* ---------------- Phones ---------------- */}
      <Section title="Known Phone Numbers" count={phones.length}>
        <table className="table table-bordered table-sm">
          <thead>
            <tr>
              <th>Number</th>
              <th>Type</th>
              <th>Provider</th>
              <th>Last Seen</th>
            </tr>
          </thead>
          <tbody>
            {phones.length === 0 ? (
              <EmptyRow colSpan={4} />
            ) : (
              phones.map((p, i) => (
                <tr key={i}>
                  <td>{safe(p.number)}</td>
                  <td>{safe(p.type)}</td>
                  <td>{safe(p.providerName)}</td>
                  <td>{safe(p.meta?.lastSeen)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </Section>

      {/* ---------------- Emails ---------------- */}
      <Section title="Known Email Addresses" count={emails.length}>
        <table className="table table-bordered table-sm">
          <thead>
            <tr>
              <th>Email Address</th>
              <th>Last Seen</th>
            </tr>
          </thead>
          <tbody>
            {emails.length === 0 ? (
              <EmptyRow colSpan={2} />
            ) : (
              emails.map((e, i) => (
                <tr key={i}>
                  <td>{safe(e.data)}</td>
                  <td>{safe(e.meta?.lastSeen)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </Section>

      {/* ---------------- Bankruptcy ---------------- */}
      <Section title="Bankruptcy Records" count={bankruptcies.length}>
        <table className="table table-bordered table-sm">
          <thead>
            <tr>
              <th>Chapter</th>
              <th>Filing Date</th>
              <th>Case Number</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {bankruptcies.length === 0 ? (
              <EmptyRow colSpan={4} />
            ) : (
              bankruptcies.map((b, i) => (
                <tr key={i}>
                  <td>{safe(b.chapter)}</td>
                  <td>{safe(b.filingDate?.data)}</td>
                  <td>{safe(b.fullCaseNumber)}</td>
                  <td>{safe(b.caseStatus)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </Section>

      {/* ---------------- Employment ---------------- */}
      <Section title="Known Employments" count={employments.length}>
        <table className="table table-bordered table-sm">
          <thead>
            <tr>
              <th>Employer</th>
              <th>Address</th>
              <th>Last Seen</th>
            </tr>
          </thead>
          <tbody>
            {employments.length === 0 ? (
              <EmptyRow colSpan={3} />
            ) : (
              employments.map((e, i) => (
                <tr key={i}>
                  <td>{safe(e.employerName)}</td>
                  <td>{fmtAddress(e.address)}</td>
                  <td>{safe(e.date?.data)}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </Section>

      {/* ---------------- Properties ---------------- */}
      <Section title="Known Properties" count={properties.length}>
        <table className="table table-bordered table-sm">
          <thead>
            <tr>
              <th>Address</th>
              <th>Assessed Value</th>
              <th>Market Value</th>
              <th>Owners</th>
            </tr>
          </thead>
          <tbody>
            {properties.length === 0 ? (
              <EmptyRow colSpan={4} />
            ) : (
              properties.map((p, i) => (
                <tr key={i}>
                  <td>{fmtAddress(p.address)}</td>
                  <td>{fmtMoney(p.assessment?.assessedValue)}</td>
                  <td>{fmtMoney(p.assessment?.marketValue)}</td>
                  <td>
                    {(p.owner || [])
                      .map((o) => o.name)
                      .filter(Boolean)
                      .join(", ") || "—"}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </Section>

      {/* ---------------- Known Associates / Relationships ---------------- */}
      <Section title="Known Associates" count={relationships.length}>
        <div className="row row-cols-1 row-cols-md-2 g-2">
          {relationships.length === 0 ? (
            <div className="text-muted">Found None</div>
          ) : (
            relationships.map((r, i) => (
              <div key={i} className="border rounded p-2">
                <div className="fw-bold">{fmtName(r.name)}</div>
                <div className="small text-muted">
                  {relationshipLabel(r.type, r.subType)}
                  {r.dob?.age ? ` • Age: ${r.dob.age}` : ""}
                </div>
                {r.phone?.[0]?.number && (
                  <div className="small">{r.phone[0].number}</div>
                )}
              </div>
            ))
          )}
        </div>
      </Section>

      {/* ---------------- Vehicles ---------------- */}
      <Section title="Known Vehicles" count={vehicles.length}>
        <div className="row row-cols-1 row-cols-md-2 g-2">
          {vehicles.length === 0 ? (
            <div className="text-muted">Found None</div>
          ) : (
            vehicles.map((v, i) => {
              const d = v.detail?.[0] || {};
              return (
                <div key={i} className="border rounded p-2">
                  <div className="fw-bold">
                    {[d.modelYear, d.make, d.model, d.trim].filter(Boolean).join(" ")}
                  </div>
                  <div className="small text-muted">VIN: {safe(d.vin)}</div>
                  <div className="small text-muted">Body Style: {safe(d.bodyStyle)}</div>
                </div>
              );
            })
          )}
        </div>
      </Section>

      {/* ---------------- Criminal / Infractions ---------------- */}
      <Section title="Possible Criminal/Infractions" count={criminals.length}>
        {criminals.length === 0 ? (
          <p className="text-muted mb-0">Found None</p>
        ) : (
          <table className="table table-bordered table-sm">
            <tbody>
              {criminals.map((c, i) => (
                <tr key={i}>
                  <td>{JSON.stringify(c)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Section>

      {/* ---------------- Judgments / Liens / Aircraft / Business / Professional ---------------- */}
      <div className="row">
        {[
          ["Judgments", judgments],
          ["Liens", liens],
          ["Aircraft", aircraft],
          ["Known Businesses", businesses],
          ["Professional Licenses", professional],
        ].map(([label, arr]) => (
          <div key={label} className="col-md-4 mb-3">
            <div className="border rounded p-2 h-100">
              <div className="fw-bold small">{label}</div>
              <div className="text-muted small">
                {arr.length === 0 ? "Found None" : `Found ${arr.length}`}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}