"use client";

import type { ReactNode } from "react";
import { useTranslations } from "next-intl";
import {
  getVaccinationStatusForDisplay,
  vaccinationStatusValueLabel,
} from "@/lib/animalVaccinationStatus";
import { formatCamelAnimalAgeForDisplay } from "@/lib/camelAnimalAge";

export default function CamelDetailsSection({ item }: { item: any }) {
  const t = useTranslations("SINGLE_AUCTION.CAMEL_DETAILS");
  const tFilters = useTranslations("AUCTIONS_FILTERS");
  const tVax = useTranslations("ANIMAL_VACCINATION_STATUS");
  const camel = item?.camel || {};
  const camelGroup = item?.camel_group || {};
  let genderKey: string;
  if (camel.gender) {
    genderKey =
      camel.gender === "male"
        ? "gender_male"
        : camel.gender === "female"
          ? "gender_female"
          : "gender_unknown";
  } else {
    genderKey = "gender_unknown";
  }

  const genderLabel = t(genderKey as any);

  const getCamelTypeLabel = (raw: any): string => {
    const key = String(raw || "").trim();
    if (!key) return "—";
    if (key === "male") return tFilters("type.male");
    if (key === "castrated") return tFilters("type.castrated");
    if (key === "breeding_female")
      return tFilters("type.camel_breeding_female");
    if (key === "non_breeding_female")
      return tFilters("type.camel_non_breeding_female");
    return key;
  };

  const ageYears = (() => {
    if (!camel.date_of_birth) return "—";
    const dob = new Date(camel.date_of_birth);
    if (Number.isNaN(dob.getTime())) return camel.date_of_birth;
    const diff = Date.now() - dob.getTime();
    const years = Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
    return t("age_years", { years });
  })();

  const ageCategoryDisplay = formatCamelAnimalAgeForDisplay(
    camel.animal_age,
  );

  type DetailRow = { key: string; label: string; value: ReactNode };

  const animalAgeRow: DetailRow[] = ageCategoryDisplay
    ? [
        {
          key: "animal_age",
          label: t("age_category"),
          value: ageCategoryDisplay,
        },
      ]
    : [];
  const primaryDetails: DetailRow[] = [
    {
      key: "name",
      label: t("name"),
      value: camel.name || item?.title || "—",
    },
    {
      key: "breed",
      label: t("breed"),
      value: camel.breed || camelGroup.breed || "—",
    },
    {
      key: "gender",
      label: t("gender"),
      value: genderLabel,
    },
    {
      key: "birth",
      label: t("birth_and_age"),
      value: camel.date_of_birth
        ? `${camel.date_of_birth} • ${ageYears}`
        : "—",
    },
    {
      key: "type",
      label: t("type"),
      value: getCamelTypeLabel(camel.type),
    },
    {
      key: "usage",
      label: t("usage"),
      value: camel.animal_usage || camelGroup.animal_usage || "—",
    },
    {
      key: "group_count",
      label: t("group_count"),
      value: camelGroup.count ?? "—",
    },
  ];

  const secondaryDetails: DetailRow[] = [
    {
      key: "height",
      label: t("height"),
      value: camel.height ? t("height_with_unit", { value: camel.height }) : "—",
    },
    {
      key: "color",
      label: t("color"),
      value: camel.animal_color || "—",
    },
    ...animalAgeRow,
    {
      key: "father_name",
      label: t("father_name"),
      value: camel.father_name || "—",
    },
    {
      key: "mother_name",
      label: t("mother_name"),
      value: camel.mother_name || "—",
    },
    {
      key: "mother_father_name",
      label: t("mother_father_name"),
      value: camel.mother_father_name || "—",
    },
  ];

  const camelVax = getVaccinationStatusForDisplay(camel);
  if (camelVax) {
    secondaryDetails.push({
      key: "vaccination_status",
      label: tVax("label"),
      value: vaccinationStatusValueLabel(camelVax, tVax),
    });
  }

  const rowsPerColumn = Math.max(primaryDetails.length, secondaryDetails.length);
  const paddedPrimaryDetails = [
    ...primaryDetails,
    ...Array.from(
      { length: Math.max(0, rowsPerColumn - primaryDetails.length) },
      (_, index) => ({
        key: `primary-empty-${index}`,
        label: "",
        value: "",
      }),
    ),
  ];

  const paddedSecondaryDetails = [
    ...secondaryDetails,
    ...Array.from(
      { length: Math.max(0, rowsPerColumn - secondaryDetails.length) },
      (_, index) => ({
        key: `secondary-empty-${index}`,
        label: "",
        value: "",
      }),
    ),
  ];

  return (
    <section className="bg-white rounded-2xl p-5 border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)]">
      <h3 className="text-lg font-bold text-[#0F5132] mb-3">{t("title")}</h3>
      <div className="grid md:grid-cols-2 gap-4">
        <div className="w-full text-sm overflow-hidden bg-slate-50/30  divide-y">
          {paddedPrimaryDetails.map((detail) => {
            const isEmpty = !detail.label && !detail.value;
            return (
              <div
                key={detail.key}
                className="grid grid-cols-[minmax(120px,42%)_1fr] min-h-[52px]"
                aria-hidden={isEmpty}
              >
                <div className="p-3 text-slate-500">{detail.label || "\u00A0"}</div>
                <div className="p-3 font-bold text-slate-900">
                  {detail.value || "\u00A0"}
                </div>
              </div>
            );
          })}
        </div>

        <div className="w-full text-sm overflow-hidden bg-slate-50/30  divide-y">
          {paddedSecondaryDetails.map((detail) => {
            const isEmpty = !detail.label && !detail.value;
            return (
              <div
                key={detail.key}
                className="grid grid-cols-[minmax(120px,42%)_1fr] min-h-[52px]"
                aria-hidden={isEmpty}
              >
                <div className="p-3 text-slate-500">{detail.label || "\u00A0"}</div>
                <div className="p-3 font-bold text-slate-900">
                  {detail.value || "\u00A0"}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}
