// Components/CompanyImporters/HepiyiImporter.jsx
import { useRouter } from "next/router";
import { useState } from "react";
import * as XLSX from "xlsx";
import axios from "axios";
import ImportShell from "./ImportShell";

const TOKEN = process.env.NEXT_PUBLIC_SECRET_TOKEN;

// ✅ keep your current API path (change if you use another)
const IMPORT_API = "/api/Policy/Import";

export default function HepiyiImporter({ company }) {
  const router = useRouter();

  const [fileName, setFileName] = useState("");
  const [parsing, setParsing] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [parsed, setParsed] = useState([]);
  const [error, setError] = useState("");
  const [result, setResult] = useState(null);

  const onPickFile = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setError("");
    setResult(null);
    setFileName(file.name);
    setParsing(true);

    try {
      const buf = await file.arrayBuffer();
      const wb = XLSX.read(buf, { type: "array", cellDates: true });
      const sheet = wb.Sheets[wb.SheetNames[0]];
      if (!sheet) throw new Error("Excel sayfası bulunamadı.");

      const rows = XLSX.utils.sheet_to_json(sheet, { header: 1, defval: "" });
      if (!rows?.length) throw new Error("Excel boş görünüyor.");

      const headers = (rows[0] || []).map((h) => normalizeKey(h));
      const dataRows = rows
        .slice(1)
        .filter((r) => r && r.some((v) => String(v ?? "").trim() !== ""));

      const objects = dataRows.map((r) => {
        const obj = {};
        headers.forEach((key, idx) => (obj[key] = r[idx]));
        return obj;
      });

      const policies = objects.map((rowObj) => mapHepiyiRowToPolicy(rowObj, company.name));
      setParsed(policies);
    } catch (err) {
      console.error(err);
      setError(err?.message || "Dosya okunamadı.");
      setParsed([]);
    } finally {
      setParsing(false);
    }
  };

  const uploadToDb = async () => {
    if (!parsed.length) return;
    setUploading(true);
    setError("");
    setResult(null);

    try {
      const { data } = await axios.post(
        IMPORT_API,
        { policies: parsed },
        { headers: { Authorization: TOKEN ? `Bearer ${TOKEN}` : "" } }
      );

      if (!data?.success) throw new Error(data?.message || "Upload failed");
      setResult(data);
    } catch (e) {
      console.error(e);
      setError(
        e?.response?.data?.message ||
          e?.response?.data?.error ||
          e?.message ||
          "Upload error"
      );
    } finally {
      setUploading(false);
    }
  };

  return (
    <ImportShell
      company={company}
      fileName={fileName}
      parsing={parsing}
      uploading={uploading}
      parsedCount={parsed.length}
      error={error}
      result={result}
      onPickFile={onPickFile}
      onUpload={uploadToDb}
      onBack={() => router.push("/Policy")}
    />
  );
}

/* ---------------- Hepiyi mapping (your finished one) ---------------- */

function normalizeKey(h) {
  return String(h ?? "")
    .replace(/\u00A0/g, " ")
    .trim()
    .toLowerCase()
    .replace(/ı/g, "i")
    .replace(/İ/g, "i")
    .replace(/ş/g, "s")
    .replace(/ğ/g, "g")
    .replace(/ü/g, "u")
    .replace(/ö/g, "o")
    .replace(/ç/g, "c")
    .replace(/[–—]/g, "-")
    .replace(/\s+/g, " ")
    .replace(/[^\w\s-]/g, "");
}

function getCell(rowObj, headerVariants = []) {
  for (const h of headerVariants) {
    const key = normalizeKey(h);
    const v = rowObj[key];
    if (v !== undefined && v !== null && String(v).trim() !== "") return v;
  }
  return "";
}

function toInt(v) {
  const n = Number(String(v ?? "").replace(/[^\d-]/g, ""));
  return Number.isFinite(n) ? n : null;
}

function toDecimal(v) {
  if (v === null || v === undefined || v === "") return null;
  const s = String(v)
    .replace(/\s/g, "")
    .replace(/₺/g, "")
    .replace(/TRY/gi, "")
    .replace(/\./g, "")
    .replace(/,/g, ".")
    .replace(/[^\d.-]/g, "");
  const n = Number(s);
  return Number.isFinite(n) ? n : null;
}

function excelSerialToDate(n) {
  const d = new Date(Math.round((n - 25569) * 86400 * 1000));
  return Number.isNaN(d.getTime()) ? null : d;
}

function toDate(v) {
  if (v === null || v === undefined || v === "") return null;
  if (v instanceof Date && !Number.isNaN(v.getTime())) return v;
  if (typeof v === "number") return excelSerialToDate(v);

  const s = String(v).trim();
  if (/^\d+(\.\d+)?$/.test(s)) return excelSerialToDate(Number(s));

  const isoTry = new Date(s);
  if (!Number.isNaN(isoTry.getTime())) return isoTry;

  let m = s.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})/);
  if (m) return new Date(Number(m[3]), Number(m[2]) - 1, Number(m[1]));

  m = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})/);
  if (m) return new Date(Number(m[3]), Number(m[2]) - 1, Number(m[1]));

  return null;
}

function mapHepiyiRowToPolicy(row, agencyName) {
  const policyNo = getCell(row, ["Poliçe No"]);
  const zeylNo = getCell(row, ["Zeyl No"]);
  const policyEndorsementNo = [policyNo, zeylNo].filter(Boolean).join("-");

  const startdate = toDate(getCell(row, ["Poliçe Tarih"])) || null;
  const enddate = toDate(getCell(row, ["Poliçe Bitiş Tarih"])) || null;

  const insured = String(
    getCell(row, ["Müşteri Ad – Soyad", "Müşteri Ad - Soyad", "MUSTERI_UNVANI"]) || ""
  ).trim();

  const plate = String(getCell(row, ["Plaka"]) || "").trim();
  const product = String(getCell(row, ["URUN_ADI"]) || "").trim();

  const netPrim = toDecimal(getCell(row, ["Net Prim"]));
  const brutPrim = toDecimal(getCell(row, ["Brüt Prim"]));
  const commission = toDecimal(getCell(row, ["Komisyon"]));
  const premium = brutPrim ?? netPrim ?? null;

  const renewalNo = toInt(getCell(row, ["YENILEME_NO"])) || 0;
  const renewed = renewalNo > 0;

  return {
    agency: agencyName,
    startdate,
    enddate,
    insured,
    policyEndorsementNo,
    product,
    plate,
    premium,

    assignments:
      String(getCell(row, ["P Kaynak Adı", "PARTAJ"]) || "-").trim() || "-",
    paymentStatus: "-",

    grossPremium: brutPrim,
    netPremium: netPrim,
    commission,

    branch: String(getCell(row, ["PARTAJ"]) || "").trim() || null,
    representative: String(getCell(row, ["SYS Kullanici Adi"]) || "").trim() || null,
    policyStatus: String(getCell(row, ["ZEYIL_TIPI"]) || "").trim() || null,
    renewed,

    brand: String(getCell(row, ["Marka"]) || "").trim() || null,
    brandType: String(getCell(row, ["Model"]) || "").trim() || null,
    modelYear: toInt(getCell(row, ["Model Yılı"])),
    motorNo: String(getCell(row, ["Motor No"]) || "").trim() || null,
    chassisNo: String(getCell(row, ["Şasi No"]) || "").trim() || null,
    vehicleValue: toInt(getCell(row, ["ARAÇ BEDELİ"])),
    usageType: String(getCell(row, ["Kullanım Tarz"]) || "").trim() || null,
    licenseSerialNo:
      String(getCell(row, ["Belge Seri Kod-No", "RUHSAT_BELGE_SERI_KOD"]) || "").trim() ||
      null,
    productCode: String(getCell(row, ["Police Tür Kod"]) || "").trim() || null,
    nationalId:
      String(getCell(row, ["TC", "VERGI_KIMLIK_NUMARASI"]) || "").trim() || null,
    birthDate: toDate(getCell(row, ["Doğum Tarih"])),
  };
}