"use client";

import { useAtom } from "jotai";
import { Section } from "../section";
import { formAtom } from "@/components/state/autionAtoms";
import { useTranslations } from "next-intl";
import { useMemo } from "react";
import RiyalIcon from "@/components/ui/RiyalIcon";
import type { VaccinationStatusValue } from "@/lib/animalVaccinationStatus";

function buildAnimalPayload(formData: any) {
  const {
    state_id,
    animal_type,
    is_group,
    name, // كان title
    fixedPrice, // كان price
    deposit,
    shortDesc,
    videoLinks,
    files,
    additional_services,
    custom_services,
    camelMode,
    gender,
    breed,
    age,
    height,
    vaccination_status,
    animal_usage_id,
    animal_color_id,
    father_name,
    mother_name,
    mother_father_name,
    nm,
    type,
    auction_start_time,
    auction_end_time,
    auction_type,
    offer,
  } = formData;

  const vaccinationForSubmit = (
    breedingType: string | undefined,
  ): VaccinationStatusValue | undefined => {
    if (breedingType !== "breeding_female") return undefined;
    return vaccination_status as VaccinationStatusValue | undefined;
  };

  const base: any = {
    state_id: Number(state_id),
    animal_type,
    is_group,
    title: nm || name || "tesst",
    description: shortDesc || "",
  };

  // فرّق صراحةً حسب نوع العرض
  if (offer === "fixed") {
    base.price = Number(fixedPrice) || 0; // <-- تغيّر من price إلى fixedPrice
    if (deposit !== undefined) base.deposit = Number(deposit) || 0;
    // تأكد من عدم تمرير حقول المزاد في حالة العرض الثابت
    delete base.auction_start_time;
    delete base.auction_end_time;
    delete base.auction_type;
  } else if (offer === "auction") {
    if (auction_start_time) base.auction_start_time = auction_start_time;
    if (auction_end_time) base.auction_end_time = auction_end_time;
    if (auction_type) base.auction_type = auction_type; // electronic | live
    // لا ترسل price/deposit للمزاد
    delete base.price;
    delete base.deposit;
  }

  if (Array.isArray(files) && files.length > 0) {
    base.files = files.map((f: any) => ({
      collection_name: f.collection_name,
      url: f.url,
    }));
  }

  // أرسل الفيديوهات فقط في حالة العرض الثابت (حسب الأمثلة المرسلة)
  if (offer === "fixed" && Array.isArray(videoLinks) && videoLinks.length > 0) {
    base.videos = videoLinks
      .filter((v: string) => v)
      .map((url: string) => ({ url }));
  }

  if (animal_type === "camel") {
    if (camelMode === "group" || is_group) {
      base.is_group = true;
      base.camel_group = {
        animal_usage_id,
        animal_color_id,
        breed,
        count: formData.camelsCount || formData.count || 1,
        additional_services: additional_services || [],
        custom_services: custom_services || [],
      };
    } else {
      base.is_group = false;
      const camelVax = vaccinationForSubmit(type);
      base.camel = {
        animal_usage_id,
        animal_color_id,
        name: nm,
        father_name,
        mother_name,
        mother_father_name,
        gender,
        breed,
        age: Number(age),
        age_unit: "year",
        type: type || undefined,
        ...(camelVax ? { vaccination_status: camelVax } : {}),
      };
    }
  }

  if (animal_type === "horse") {
    base.is_group = false;
    const horseVax = vaccinationForSubmit(type);
    base.horse = {
      animal_usage_id,
      animal_color_id,
      name: nm,
      father_name,
      mother_name,
      mother_father_name,
      gender,
      breed,
      age: Number(age),
      age_unit: "year",
      height: Number(height),
      type: type || undefined,
      ...(horseVax ? { vaccination_status: horseVax } : {}),
    };
  }

  return base;
}

export function Step9() {
  const t = useTranslations("ADD_LISTING.STEP9");
  const tCard = useTranslations("HORSE_CARD");
  const [form] = useAtom(formAtom);

  const mainImage = useMemo(
    () => form.files?.find((f) => f.collection_name === "main_image")?.url,
    [form.files],
  );

  // قيم مساعدة غير معرّفة في نوع AuctionForm الرسمي لكنها موجودة في الفورم
  const countryName = (form as any).country_name ?? form.country ?? "";
  const stateName = (form as any).state_name ?? "";

  const price = useMemo(() => {
    if (form.offer === "fixed") return form.fixedPrice ?? 0;
    if (form.offer === "auction")
      return form.starting_price ?? form.market_entry_price ?? 0;
    return 0;
  }, [
    form.offer,
    form.fixedPrice,
    form.starting_price,
    form.market_entry_price,
  ]);

  const saleTypeLabel =
    form.offer === "fixed" ? t("offer_fixed") : t("offer_auction");

  const typeBadge = form.hcat || form.type || "";

  return (
    <Section title={t("title")}>
      <div className="space-y-4">
        <div className="font-bold text-sm text-slate-700">
          {t("review_header")}
        </div>

        <article className="md:max-w-[50%]  bg-white rounded-xl overflow-hidden shadow-lg border border-gray-100 text-start items-start">
          <div className="relative overflow-hidden">
            <img
              src={
                mainImage ||
                "https://endpoint.diriw.com/storage/images/default/default.webp"
              }
              alt={form.nm || "preview"}
              className="w-full h-56 object-cover"
            />

            <div className="absolute top-3 right-3 flex items-center gap-2">
              {typeBadge && (
                <div className="bg-white/90 backdrop-blur-sm text-[#0F5132] border border-[#0F5132]/20 px-3 py-1 rounded-full text-xs font-bold">
                  {typeBadge}
                </div>
              )}
              <div className="bg-black/70 text-white px-2 py-1 rounded-full text-xs font-bold">
                {saleTypeLabel}
              </div>
            </div>

            <div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-black/70 to-transparent text-white flex items-end justify-between">
              <div className="text-sm font-bold truncate">
                {form.breed || ""} {form.hcat ? `• ${form.hcat}` : ""}
              </div>
              <div className="flex items-center gap-2 font-extrabold text-lg">
                {price ? (
                  <>
                    <span>{price.toLocaleString("en-US")}</span>
                    <RiyalIcon className="w-4 h-4" />
                  </>
                ) : (
                  <span className="text-xs opacity-80">—</span>
                )}
              </div>
            </div>
          </div>

          <div className="p-4">
            <div className="flex items-center gap-2 mb-2 text-xs text-slate-500">
              <span className="bg-slate-100 px-2 py-1 rounded font-medium">
                #—
              </span>
              <span className="ml-auto">
                {countryName}
                {stateName ? `، ${stateName}` : ""}
              </span>
            </div>

            <h3 className="font-extrabold text-[15px] text-[#1d2b27] truncate mb-3">
              {form.nm || "—"}
            </h3>

            <div className="text-[12px] text-slate-700 space-y-1 mb-1">
              <span>
                {tCard("age_years", {
                  value: "-",
                  defaultValue: "العمر: {value} سنة",
                })}
              </span>
              <span>
                {" • "}
                {tCard("gender", {
                  value: form.gender || "-",
                  defaultValue: "الجنس: {value}",
                })}
              </span>
              <span>
                {" • "}
                {tCard("coat", {
                  value: form.color || "-",
                  defaultValue: "اللون: {value}",
                })}
              </span>
              {form.animal_type !== "camel" ? (
                <span>
                  {" • "}
                  {tCard("height_cm", {
                    value: form.height ?? "-",
                    defaultValue: "الارتفاع: {value} سم",
                  })}
                </span>
              ) : null}
            </div>

            {form.shortDesc && (
              <p className="text-[12px] text-slate-600 mt-1 line-clamp-2">
                {form.shortDesc}
              </p>
            )}
          </div>
        </article>
      </div>
    </Section>
  );
}
