"use client";

import { useEffect, useRef, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { useLocale, useTranslations } from "next-intl";
import { useSession } from "@/auth/session-provider";
import axios from "axios";
import {
  Card,
  CardBody,
  Button,
  Input,
  Textarea,
  Select,
  SelectItem,
  Switch,
} from "@heroui/react";
import Image from "next/image";
import { uploadImage, removeImage } from "@/actions/upload-image";
import type { AuctionConfigData } from "@/models/auctionConfig";
import {
  applyCamelAgesReferenceParam,
  formatCamelAnimalAgeForDisplay,
} from "@/lib/camelAnimalAge";
import { BaseModal } from "@/components/modal";
import PdfViewer from "@/components/viewers/PdfViewer";
import LocationMapPicker from "@/components/maps/LocationMapPicker";
import { DEFAULT_MAP_LAT, DEFAULT_MAP_LNG } from "@/lib/mapDefaults";
import { isValidLatLng } from "@/lib/coordinates";
import { normalizeNullableDateOfBirth } from "@/lib/animalDateOfBirth";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { API_BASE_URL } from "@/lib/axios";

const API_URL = API_BASE_URL;

export default function OfferEditPage() {
  const t = useTranslations("DASHBOARD.LISTINGS");
  const tLoc = useTranslations("ADD_LISTING.STEP6");
  const tMedia = useTranslations("ADD_LISTING.STEP7");
  const tStep4 = useTranslations("ADD_LISTING.STEP4");
  const params = useParams();
  const id = params?.id as string;
  const lang = useLocale();
  const isRTL = lang === "ar";
  const session = useSession();
  const router = useRouter();

  const [pdfModalOpen, setPdfModalOpen] = useState(false);
  const [selectedPdf, setSelectedPdf] = useState<{
    url: string;
    title: string;
  } | null>(null);

  const [mainImageModalOpen, setMainImageModalOpen] = useState(false);
  const [galleryModalOpen, setGalleryModalOpen] = useState(false);
  const [videoModalOpen, setVideoModalOpen] = useState(false);
  const [certsModalOpen, setCertsModalOpen] = useState(false);
  const [detailsModalOpen, setDetailsModalOpen] = useState(false);
  const [animalModalOpen, setAnimalModalOpen] = useState(false);

  const getFileKind = (f: any): "video" | "pdf" | "image" | "other" => {
    const url = String(f?.url || "").toLowerCase();
    const type = String(f?.type || "").toLowerCase();
    const name = String(f?.name || "").toLowerCase();

    if (String(f?.collection_name || "") === "video") return "video";
    if (type.includes("pdf") || url.endsWith(".pdf") || name.endsWith(".pdf"))
      return "pdf";
    if (
      type.startsWith("image/") ||
      url.match(/\.(jpg|jpeg|png|gif|webp)$/i) ||
      name.match(/\.(jpg|jpeg|png|gif|webp)$/i)
    )
      return "image";
    return "other";
  };

  const openPdf = (url: string, title: string) => {
    setSelectedPdf({ url, title });
    setPdfModalOpen(true);
  };

  const scrollToSection = (sectionId: string) => {
    const el = document.getElementById(sectionId);
    el?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [full, setFull] = useState<any | null>(null);
  const [files, setFiles] = useState<any[]>([]);

  const [general, setGeneral] = useState({
    title: "",
    description: "",
    price: "",
    status: "",
    lat: DEFAULT_MAP_LAT,
    lng: DEFAULT_MAP_LNG,
  });

  const [horse, setHorse] = useState<any | null>(null);
  const [camel, setCamel] = useState<any | null>(null);

  // Refs to store initial state for diff-based save
  const initialGeneral = useRef({
    title: "",
    description: "",
    price: "",
    status: "",
    lat: DEFAULT_MAP_LAT,
    lng: DEFAULT_MAP_LNG,
  });
  const initialFiles = useRef<any[]>([]);
  const initialHorse = useRef<any | null>(null);
  const initialCamel = useRef<any | null>(null);
  const initialVideoLinks = useRef<string[]>([]);

  const animalTypeOptions = (() => {
    const isCamel = !!camel;
    const isHorse = !!horse;
    const gender = (camel || horse)?.gender as "male" | "female" | undefined;

    if (!gender) return [] as Array<{ value: string; label: string }>;

    if (gender === "male") {
      const base = [
        { value: "male", label: tStep4("type_options.male") },
        { value: "castrated", label: tStep4("type_options.castrated") },
      ];

      if (isHorse) {
        base.push({
          value: "foal_male",
          label: tStep4("type_options.foal_male"),
        });
      }

      return base;
    }

    if (gender === "female") {
      const base = [
        {
          value: "breeding_female",
          label: isCamel
            ? tStep4("type_options.camel_breeding_female")
            : tStep4("type_options.horse_breeding_female"),
        },
        {
          value: "non_breeding_female",
          label: isCamel
            ? tStep4("type_options.camel_non_breeding_female")
            : tStep4("type_options.horse_non_breeding_female"),
        },
      ];

      if (isHorse) {
        base.push({
          value: "foal_female",
          label: tStep4("type_options.foal_female"),
        });
      }

      return base;
    }

    return [] as Array<{ value: string; label: string }>;
  })();

  const currentAnimalType = (camel || horse)?.type as string | undefined;
  const animalTypeSelectItems = (() => {
    if (!currentAnimalType) return animalTypeOptions;
    if (animalTypeOptions.some((o) => o.value === currentAnimalType))
      return animalTypeOptions;
    return [
      ...animalTypeOptions,
      { value: currentAnimalType, label: currentAnimalType },
    ];
  })();

  const [config, setConfig] = useState<AuctionConfigData | null>(null);
  const [configLoading, setConfigLoading] = useState(false);

  const [videoLinks, setVideoLinks] = useState<string[]>([]);
  const [videoDirty, setVideoDirty] = useState(false);

  const handleFilesUpload = async (
    fieldName: string,
    collectionName: string,
    fileList: FileList | null,
  ) => {
    if (!fileList || fileList.length === 0) return;

    if (collectionName === "main_image") {
      const alreadyHasMain = files.some(
        (f) => f.collection_name === "main_image",
      );
      if (alreadyHasMain) {
        alert(tMedia("toast.main_image_exists"));
        return;
      }
      if (fileList.length > 1) {
        alert(tMedia("toast.only_one_main_image"));
        return;
      }
    }

    const formData = new FormData();
    formData.append("model_name", "Offer");

    const filesArray = Array.from(fileList);

    const singleFileCollections = [
      "main_image",
      "medical_exam_certificate",
      "info_certificate",
      "owner_document",
    ];

    if (singleFileCollections.includes(collectionName)) {
      formData.append(fieldName, filesArray[0]);
    } else {
      filesArray.forEach((file, index) => {
        formData.append(`${fieldName}[${index}]`, file);
      });
    }

    try {
      const res = await uploadImage(formData);
      if (res?.success && Array.isArray(res.data)) {
        const uploadedFiles = res.data.map((f: any) => ({
          id: f.id,
          collection_name: f.collection_name,
          url: f.url,
        }));

        setFiles((prev) => [...prev, ...uploadedFiles]);
      } else {
        alert(tMedia("toast.upload_failed"));
      }
    } catch (error) {
      console.error("upload error", error);
      alert(tMedia("toast.upload_failed"));
    }
  };

  const handleRemoveExistingFile = async (index: number, file: any) => {
    if (!file?.id) {
      setFiles((prev) => prev.filter((_, idx) => idx !== index));
      return;
    }

    const token = session?.access_token;
    if (!token) {
      alert(tMedia("toast.remove_failed"));
      return;
    }

    try {
      const res = await removeImage({ mediaIds: [file.id], token });
      if (res?.success) {
        setFiles((prev) => prev.filter((_, idx) => idx !== index));
      } else {
        alert(tMedia("toast.remove_failed"));
      }
    } catch (err) {
      console.error("remove media error", err);
      alert(tMedia("toast.remove_failed"));
    }
  };

  useEffect(() => {
    const fetchOffer = async () => {
      try {
        setLoading(true);
        const token = session?.access_token;
        const res = await axios.get(`${API_URL}/user/dashboard/offers/${id}`, {
          headers: {
            Authorization: token ? `Bearer ${token}` : "",
            Accept: "application/json",
            lang,
          },
        });

        const data = res.data?.data || {};
        setFull(data);
        const latRaw =
          data.lat != null && data.lat !== "" ? Number(data.lat) : NaN;
        const lngRaw =
          data.lng != null && data.lng !== "" ? Number(data.lng) : NaN;
        const nextLat = Number.isFinite(latRaw) ? latRaw : DEFAULT_MAP_LAT;
        const nextLng = Number.isFinite(lngRaw) ? lngRaw : DEFAULT_MAP_LNG;
        setGeneral({
          title: data.title || "",
          description: data.description || "",
          price: data.price || "",
          status: data.status || "",
          lat: nextLat,
          lng: nextLng,
        });
        setHorse(data.horse || null);
        setCamel(data.camel || null);

        const videos: string[] = Array.isArray(data.videos) ? data.videos : [];
        setVideoLinks(videos);

        const combinedFiles: any[] = [];
        if (Array.isArray(data.files) && data.files.length) {
          combinedFiles.push(...data.files);
        } else {
          const media = data.media_files;

          if (media?.main_image?.url) {
            combinedFiles.push({
              collection_name: "main_image",
              url: media.main_image.url,
            });
          }

          if (Array.isArray(media?.additional_images)) {
            media.additional_images.forEach((img: any) => {
              if (img?.url) {
                combinedFiles.push({
                  collection_name: "additional_images",
                  url: img.url,
                });
              }
            });
          }

          const getUrl = (value: any) => {
            if (!value) return null;
            if (typeof value === "string") return value;
            return value.url || null;
          };

          const medicalUrl = getUrl(media?.medical_exam_certificate);
          if (medicalUrl) {
            combinedFiles.push({
              collection_name: "medical_exam_certificate",
              url: medicalUrl,
            });
          }

          const infoCertUrl = getUrl(media?.info_certificate);
          if (infoCertUrl) {
            combinedFiles.push({
              collection_name: "info_certificate",
              url: infoCertUrl,
            });
          }

          const ownerDocUrl = getUrl(media?.owner_document);
          if (ownerDocUrl) {
            combinedFiles.push({
              collection_name: "owner_document",
              url: ownerDocUrl,
            });
          }
        }

        setFiles(combinedFiles);

        // Store initial snapshots for diff-based save
        initialGeneral.current = {
          title: data.title || "",
          description: data.description || "",
          price: data.price || "",
          status: data.status || "",
          lat: nextLat,
          lng: nextLng,
        };
        initialFiles.current = JSON.parse(JSON.stringify(combinedFiles));
        initialHorse.current = data.horse
          ? JSON.parse(JSON.stringify(data.horse))
          : null;
        initialCamel.current = data.camel
          ? JSON.parse(JSON.stringify(data.camel))
          : null;
        initialVideoLinks.current = Array.isArray(data.videos)
          ? [...data.videos]
          : [];

        // جلب الكونفغ حسب نوع الحيوان (horse أو camel)
        const animalTypeForConfig: "camel" | "horse" | null = data.horse
          ? "horse"
          : data.camel
            ? "camel"
            : null;

        if (animalTypeForConfig) {
          setConfigLoading(true);
          const params = new URLSearchParams({
            countries: "1",
            additional_services: "1",
            usages: "1",
            animal_type: animalTypeForConfig,
            colors: "1",
          });
          applyCamelAgesReferenceParam(params, animalTypeForConfig);

          const cfgRes = await axios.get(
            `${API_URL}/user/config/reference-data?${params.toString()}`,
            {
              headers: {
                Authorization: token ? `Bearer ${token}` : "",
                Accept: "application/json",
                lang,
              },
            },
          );

          setConfig(cfgRes.data?.data || null);
          setConfigLoading(false);
        }
        setError(null);
      } catch (e: any) {
        console.error(e);
        setError(
          e?.response?.data?.message || e?.message || t("edit_load_failed"),
        );
      } finally {
        setLoading(false);
      }
    };

    if (id) fetchOffer();
  }, [id, lang, session?.access_token]);

  // عند توفر الكونفغ، اربط الأسماء القادمة من العرض (usage/color) بالـ IDs من الكونفغ
  useEffect(() => {
    if (!config) return;

    // Horse
    setHorse((prev: any) => {
      if (!prev) return prev;
      const next = { ...prev };

      if (!next.animal_usage_id && next.animal_usage && config.usages) {
        const u = config.usages.find((x) => x.name === next.animal_usage);
        if (u) next.animal_usage_id = String(u.id);
      }

      if (!next.animal_color_id && next.animal_color && config.colors) {
        const c = config.colors.find((x) => x.name === next.animal_color);
        if (c) next.animal_color_id = String(c.id);
      }

      return next;
    });

    // Camel
    setCamel((prev: any) => {
      if (!prev) return prev;
      const next = { ...prev };

      if (!next.animal_usage_id && next.animal_usage && config.usages) {
        const u = config.usages.find((x) => x.name === next.animal_usage);
        if (u) next.animal_usage_id = String(u.id);
      }

      if (!next.animal_color_id && next.animal_color && config.colors) {
        const c = config.colors.find((x) => x.name === next.animal_color);
        if (c) next.animal_color_id = String(c.id);
      }

      if (!next.animal_age_id && next.animal_age && config.ages?.length) {
        const label = formatCamelAnimalAgeForDisplay(next.animal_age);
        if (label) {
          const a = config.ages.find((x) => x.name === label);
          if (a) next.animal_age_id = String(a.id);
        }
      }

      return next;
    });
  }, [config]);

  const saveOffer = async ({ navigateBack }: { navigateBack: boolean }) => {
    if (!full) return;
    try {
      setSaving(true);
      const token = session?.access_token;

      const payload: any = {
        _method: "put",
      };

      // Only include changed general fields
      if (general.title !== initialGeneral.current.title) {
        payload.title = general.title;
      }
      if (general.description !== initialGeneral.current.description) {
        payload.description = general.description;
      }
      if (general.price !== initialGeneral.current.price) {
        payload.price = general.price;
      }

      const la = Number(general.lat);
      const ln = Number(general.lng);
      if (!isValidLatLng(la, ln)) {
        alert(tLoc("invalid_coordinates"));
        setSaving(false);
        return false;
      }
      payload.lat = la;
      payload.lng = ln;

      // Status change
      const editableStatus =
        full.status === "rejected" || full.status === "active";
      if (editableStatus && general.status && general.status !== full.status) {
        payload.status = "sold";
      }

      // Only include files if changed
      if (JSON.stringify(files) !== JSON.stringify(initialFiles.current)) {
        payload.files = files;
      }

      // Only include videos if dirty
      if (videoDirty) {
        payload.videos = videoLinks.filter((v) => v && v.trim().length);
      }

      // Only include animal data if changed
      if (camel) {
        const { id: _camelId, ...camelWithoutId } = camel as any;
        const { id: _initId, ...initCamelWithoutId } = (initialCamel.current ||
          {}) as any;
        const camelForApi = {
          ...camelWithoutId,
          date_of_birth: normalizeNullableDateOfBirth(
            camelWithoutId.date_of_birth,
          ),
        };
        const initForCompare = {
          ...initCamelWithoutId,
          date_of_birth: normalizeNullableDateOfBirth(
            initCamelWithoutId.date_of_birth,
          ),
        };
        if (JSON.stringify(camelForApi) !== JSON.stringify(initForCompare)) {
          payload.camel = camelForApi;
        }
      }
      if (horse) {
        const { id: _horseId, ...horseWithoutId } = horse as any;
        const { id: _initId, ...initHorseWithoutId } = (initialHorse.current ||
          {}) as any;
        if (
          JSON.stringify(horseWithoutId) !== JSON.stringify(initHorseWithoutId)
        ) {
          payload.horse = horseWithoutId;
        }
      }

      await axios.post(`${API_URL}/user/dashboard/offers/${id}`, payload, {
        headers: {
          Authorization: token ? `Bearer ${token}` : "",
          Accept: "application/json",
          lang,
        },
      });

      // Update initial refs to reflect saved state
      initialGeneral.current = { ...general };
      initialFiles.current = JSON.parse(JSON.stringify(files));
      if (camel) initialCamel.current = JSON.parse(JSON.stringify(camel));
      if (horse) initialHorse.current = JSON.parse(JSON.stringify(horse));
      if (videoDirty) {
        initialVideoLinks.current = [...videoLinks];
        setVideoDirty(false);
      }

      if (navigateBack) {
        router.back();
      }

      return true;
    } catch (e: any) {
      console.error(e);
      alert(
        e?.response?.data?.message || e?.message || t("edit_update_failed"),
      );
      return false;
    } finally {
      setSaving(false);
    }
  };

  const handleSave = async () => {
    await saveOffer({ navigateBack: true });
  };

  if (loading) {
    return (
      <div className={`max-w-7xl mx-auto px-4 py-4 mt-16 text-start`}>
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
          <main className="lg:col-span-8 space-y-6">
            <div className="h-10 bg-slate-200 rounded-xl animate-pulse" />
            <Card className="border rounded-2xl shadow-soft">
              <CardBody className="space-y-4">
                <div className="h-5 w-28 bg-slate-200 rounded animate-pulse" />
                <div className="aspect-16/7 w-full bg-slate-200 rounded-2xl animate-pulse" />
              </CardBody>
            </Card>
            <Card className="border rounded-2xl shadow-soft">
              <CardBody className="space-y-4">
                <div className="h-5 w-36 bg-slate-200 rounded animate-pulse" />
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="h-10 bg-slate-200 rounded animate-pulse" />
                  <div className="h-10 bg-slate-200 rounded animate-pulse" />
                </div>
                <div className="h-28 bg-slate-200 rounded animate-pulse" />
              </CardBody>
            </Card>
            <Card className="border rounded-2xl shadow-soft">
              <CardBody className="space-y-4">
                <div className="h-5 w-40 bg-slate-200 rounded animate-pulse" />
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                  {Array.from({ length: 8 }).map((_, idx) => (
                    <div
                      key={idx}
                      className="aspect-square bg-slate-200 rounded-xl animate-pulse"
                    />
                  ))}
                </div>
              </CardBody>
            </Card>
            <div className="flex justify-end">
              <div className="h-10 w-32 bg-slate-200 rounded-xl animate-pulse" />
            </div>
          </main>
          <aside className="lg:col-span-4 space-y-6">
            <Card className="border rounded-2xl shadow-soft">
              <CardBody className="space-y-4">
                <div className="h-5 w-32 bg-slate-200 rounded animate-pulse" />
                <div className="space-y-3">
                  <div className="h-10 bg-slate-200 rounded animate-pulse" />
                  <div className="h-10 bg-slate-200 rounded animate-pulse" />
                  <div className="h-10 bg-slate-200 rounded animate-pulse" />
                </div>
              </CardBody>
            </Card>
            <Card className="border rounded-2xl shadow-soft">
              <CardBody className="space-y-4">
                <div className="h-5 w-28 bg-slate-200 rounded animate-pulse" />
                <div className="h-10 bg-slate-200 rounded animate-pulse" />
                <div className="h-10 bg-slate-200 rounded animate-pulse" />
                <div className="h-10 bg-slate-200 rounded animate-pulse" />
              </CardBody>
            </Card>
          </aside>
        </div>
      </div>
    );
  }

  if (error || !full) {
    return (
      <Card className="border rounded-2xl shadow-soft">
        <CardBody>
          <div className="text-center p-8 text-red-500">
            {error || t("edit_load_failed")}
          </div>
        </CardBody>
      </Card>
    );
  }

  const mainImageUrl =
    files.find((f) => f.collection_name === "main_image")?.url ||
    full?.media_files?.main_image?.url ||
    full?.main_image?.url ||
    "";

  const ownerName =
    full?.created_by?.name || full?.owner?.name || full?.user?.name || "-";
  const stableName =
    full?.created_by?.stable_name ||
    full?.owner?.stable_name ||
    full?.stable_name ||
    "-";
  const ownerPhone =
    full?.created_by?.phone ||
    full?.owner?.phone ||
    full?.phone ||
    full?.owner_phone ||
    "-";

  const medicalCert = files.find(
    (f) => f.collection_name === "medical_exam_certificate",
  );
  const infoCert = files.find((f) => f.collection_name === "info_certificate");
  const ownerDoc = files.find((f) => f.collection_name === "owner_document");

  return (
    <div className={`max-w-7xl mx-auto px-4 py-4 mt-[4rem] text-start`}>
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
        <main className="lg:col-span-8 space-y-6">
          <Card id="section-image" className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <div className="flex items-center justify-between flex-row-reverse">
                <div className="font-bold text-lg">
                  {t("edit.sections.images")}
                </div>
                <div className="flex items-center gap-3">
                  <button
                    type="button"
                    className="text-primary underline text-sm cursor-pointer"
                    onClick={() => setMainImageModalOpen(true)}
                  >
                    {t("edit.fields.main_image")}
                  </button>
                  <button
                    type="button"
                    className="text-primary underline text-sm cursor-pointer"
                    onClick={() => setGalleryModalOpen(true)}
                  >
                    {t("edit.fields.gallery")}
                  </button>
                  <button
                    type="button"
                    className="text-primary underline text-sm cursor-pointer"
                    onClick={() => setVideoModalOpen(true)}
                  >
                    {tMedia("video")}
                  </button>
                </div>
              </div>
              <div className="relative w-full overflow-hidden rounded-2xl aspect-16/7 bg-slate-100">
                {mainImageUrl ? (
                  <Image
                    src={mainImageUrl}
                    alt={general.title || t("edit.fields.main_image")}
                    fill
                    className="object-cover"
                    unoptimized
                  />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-slate-500">
                    {t("edit.empty.no_image")}
                  </div>
                )}
              </div>
              {files.filter((f) => f.collection_name === "additional_images")
                .length > 0 && (
                <div className="flex gap-2 overflow-x-auto pb-2">
                  {files
                    .filter((f) => f.collection_name === "additional_images")
                    .map((f, i) => (
                      <div
                        key={i}
                        className="relative w-20 h-20 rounded-lg overflow-hidden shrink-0 border"
                      >
                        <Image
                          src={f.url}
                          alt={`${t("edit.fields.gallery")} ${i + 1}`}
                          fill
                          className="object-cover"
                          unoptimized
                        />
                      </div>
                    ))}
                </div>
              )}
            </CardBody>
          </Card>

          <Card id="section-offer" className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="font-bold text-lg">
                  {t("edit.sections.offer_details")}
                </div>
                <button
                  type="button"
                  className="text-primary underline text-sm cursor-pointer"
                  onClick={() => setDetailsModalOpen(true)}
                >
                  {t("edit.actions.edit")}
                </button>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm items-start text-start">
                <div>
                  <div className="font-semibold text-slate-500">
                    {t("title")}
                  </div>
                  <div>{general.title || "-"}</div>
                </div>
                <div>
                  <div className="font-semibold text-slate-500">
                    {t("price")}
                  </div>
                  <div>{general.price || "-"}</div>
                </div>
                <div>
                  <div className="font-semibold text-slate-500">
                    {t("status")}
                  </div>
                  <div>{full?.status || "-"}</div>
                </div>
                <div className="md:col-span-3">
                  <div className="font-semibold text-slate-500">
                    {t("description")}
                  </div>
                  <div className="line-clamp-2">
                    {general.description || "-"}
                  </div>
                </div>
              </div>
            </CardBody>
          </Card>

          {(camel || horse) && (
            <Card
              id="section-animal"
              className="border rounded-2xl shadow-soft"
            >
              <CardBody className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="font-bold text-lg">
                    {camel
                      ? t("edit.sections.camel_info")
                      : t("edit.sections.horse_info")}
                  </div>
                  <button
                    type="button"
                    className="text-primary underline text-sm cursor-pointer"
                    onClick={() => setAnimalModalOpen(true)}
                  >
                    {t("edit.actions.edit")}
                  </button>
                </div>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-4 text-sm items-start text-start ">
                  <div>
                    <div className="font-semibold text-slate-500">
                      {t("edit.fields.animal_name")}
                    </div>
                    <div>{(camel || horse)?.name || "-"}</div>
                  </div>
                  <div>
                    <div className="font-semibold text-slate-500">
                      {t("edit.fields.father_name")}
                    </div>
                    <div>{(camel || horse)?.father_name || "-"}</div>
                  </div>
                  <div>
                    <div className="font-semibold text-slate-500">
                      {t("edit.fields.mother_name")}
                    </div>
                    <div>{(camel || horse)?.mother_name || "-"}</div>
                  </div>
                  <div>
                    <div className="font-semibold text-slate-500">
                      {t("edit.fields.date_of_birth")}
                    </div>
                    <div>{(camel || horse)?.date_of_birth || "-"}</div>
                  </div>
                  <div>
                    <div className="font-semibold text-slate-500">
                      {t("edit.fields.breed")}
                    </div>
                    <div>{(camel || horse)?.breed || "-"}</div>
                  </div>
                  {camel &&
                  formatCamelAnimalAgeForDisplay(camel.animal_age) ? (
                    <div>
                      <div className="font-semibold text-slate-500">
                        {t("edit.fields.age_category")}
                      </div>
                      <div>
                        {formatCamelAnimalAgeForDisplay(camel.animal_age)}
                      </div>
                    </div>
                  ) : null}
                  {horse && (
                    <div>
                      <div className="font-semibold text-slate-500">
                        {t("edit.fields.height")}
                      </div>
                      <div>{horse?.height || "-"}</div>
                    </div>
                  )}
                </div>
              </CardBody>
            </Card>
          )}

          <div className="flex justify-end mb-2">
            <Button color="primary" onPress={handleSave} isLoading={saving}>
              {t("save")}
            </Button>
          </div>
        </main>
        <aside className="lg:col-span-4 space-y-6">
          <Card id="section-owner" className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="font-bold text-lg">{t("edit.owner_info")}</div>
                <Button
                  isIconOnly
                  size="sm"
                  variant="flat"
                  className="bg-slate-100"
                  onPress={() => scrollToSection("section-owner")}
                >
                  ⚑
                </Button>
              </div>
              <div className="space-y-3 text-start">
                <div className="border-b pb-2">
                  <div className="text-sm font-semibold">
                    {t("edit.fields.name")}
                  </div>
                  <div className="text-sm text-slate-600">{ownerName}</div>
                </div>
                <div className="border-b pb-2">
                  <div className="text-sm font-semibold">
                    {t("edit.fields.stable_name")}
                  </div>
                  <div className="text-sm text-slate-600">{stableName}</div>
                </div>
                <div className="border-b pb-2">
                  <div className="text-sm font-semibold">
                    {t("edit.fields.phone")}
                  </div>
                  <div className="text-sm text-slate-600">{ownerPhone}</div>
                </div>
              </div>
            </CardBody>
          </Card>

          <Card id="section-certs" className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <div className="flex w-full items-center justify-between">
                <div className="font-bold ">{t("edit.certificates")}</div>
                <button
                  type="button"
                  className="text-primary underline text-sm cursor-pointer "
                  onClick={() => setCertsModalOpen(true)}
                >
                  {t("edit.actions.edit")}
                </button>
              </div>
              <div className="space-y-3 text-sm">
                <div className="flex items-center justify-between gap-3">
                  <div className="font-semibold">
                    {t("edit.fields.medical_exam_certificate")}
                  </div>
                  {medicalCert?.url ? (
                    <a
                      className="text-primary underline"
                      href={medicalCert.url}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      {t("edit.actions.view")}
                    </a>
                  ) : (
                    <span className="text-slate-500">
                      {t("edit.empty.no_certificates")}
                    </span>
                  )}
                </div>
                <div className="flex items-center justify-between gap-3">
                  <div className="font-semibold">
                    {t("edit.fields.info_certificate")}
                  </div>
                  {infoCert?.url ? (
                    <a
                      className="text-primary underline"
                      href={infoCert.url}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      {t("edit.actions.view")}
                    </a>
                  ) : (
                    <span className="text-slate-500">
                      {t("edit.empty.no_certificates")}
                    </span>
                  )}
                </div>
                <div className="flex items-center justify-between gap-3">
                  <div className="font-semibold">
                    {t("edit.fields.owner_document")}
                  </div>
                  {ownerDoc?.url ? (
                    <a
                      className="text-primary underline"
                      href={ownerDoc.url}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      {t("edit.actions.view")}
                    </a>
                  ) : (
                    <span className="text-slate-500">
                      {t("edit.empty.no_certificates")}
                    </span>
                  )}
                </div>
              </div>
            </CardBody>
          </Card>
        </aside>
      </div>

      {/* Main Image Modal */}
      <BaseModal
        isOpen={mainImageModalOpen}
        onOpenChange={setMainImageModalOpen}
        placement="center"
        contentClassName="w-full max-w-2xl max-h-[85vh] overflow-y-auto rounded-2xl p-4"
        title={t("edit.fields.main_image")}
      >
        <div className="space-y-4">
          <div className="relative w-full aspect-video bg-slate-100 rounded-xl overflow-hidden">
            {mainImageUrl ? (
              <Image
                src={mainImageUrl}
                alt={t("edit.fields.main_image")}
                fill
                className="object-cover"
                unoptimized
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center text-slate-500">
                {t("edit.empty.no_image")}
              </div>
            )}
          </div>
          <input
            type="file"
            accept="image/*"
            onChange={(e) =>
              handleFilesUpload(
                "media[main_image]",
                "main_image",
                e.target.files,
              )
            }
            className="block w-full text-sm"
          />
          <div className="flex justify-end pt-4 border-t">
            <div className="flex items-center gap-2">
              <Button
                variant="flat"
                onPress={() => setMainImageModalOpen(false)}
              >
                {t("close")}
              </Button>
              <Button
                color="primary"
                onPress={async () => {
                  const ok = await saveOffer({ navigateBack: false });
                  if (ok) setMainImageModalOpen(false);
                }}
                isLoading={saving}
              >
                {t("save")}
              </Button>
            </div>
          </div>
        </div>
      </BaseModal>

      {/* Gallery Modal */}
      <BaseModal
        isOpen={galleryModalOpen}
        onOpenChange={setGalleryModalOpen}
        placement="center"
        contentClassName="w-full max-w-2xl max-h-[85vh] overflow-y-auto rounded-2xl p-4"
        title={t("edit.fields.gallery")}
      >
        <div className="space-y-4">
          <div className="grid grid-cols-3 gap-3">
            {files
              .filter((f) => f.collection_name === "additional_images")
              .map((f, i) => (
                <div
                  key={i}
                  className="relative aspect-square rounded-xl overflow-hidden border group"
                >
                  <Image
                    src={f.url}
                    alt={`img-${i}`}
                    fill
                    className="object-cover"
                    unoptimized
                  />
                  <button
                    type="button"
                    onClick={() =>
                      handleRemoveExistingFile(files.indexOf(f), f)
                    }
                    className="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs"
                  >
                    ×
                  </button>
                </div>
              ))}
          </div>
          <input
            type="file"
            multiple
            accept="image/*"
            onChange={(e) =>
              handleFilesUpload(
                "media[additional_images]",
                "additional_images",
                e.target.files,
              )
            }
            className="block w-full text-sm"
          />
          <div className="flex justify-end pt-4 border-t">
            <div className="flex items-center gap-2">
              <Button variant="flat" onPress={() => setGalleryModalOpen(false)}>
                {t("close")}
              </Button>
              <Button
                color="primary"
                onPress={async () => {
                  const ok = await saveOffer({ navigateBack: false });
                  if (ok) setGalleryModalOpen(false);
                }}
                isLoading={saving}
              >
                {t("save")}
              </Button>
            </div>
          </div>
        </div>
      </BaseModal>

      {/* Video Links Modal */}
      <BaseModal
        isOpen={videoModalOpen}
        onOpenChange={setVideoModalOpen}
        placement="center"
        contentClassName="w-full max-w-2xl max-h-[85vh] overflow-y-auto rounded-2xl p-4"
        title={t("edit.sections.video_links")}
      >
        <div className="space-y-4">
          {videoLinks.map((link, index) => (
            <div key={index} className="flex items-center gap-2">
              <Input
                className="flex-1"
                label={t("edit.video_link_label", { index: index + 1 })}
                value={link}
                onChange={(e) => {
                  const value = e.target.value;
                  setVideoLinks((prev) => {
                    const next = [...prev];
                    next[index] = value;
                    return next;
                  });
                  setVideoDirty(true);
                }}
              />
              <Button
                color="danger"
                variant="flat"
                onPress={() => {
                  setVideoLinks((prev) => prev.filter((_, i) => i !== index));
                  setVideoDirty(true);
                }}
              >
                {t("edit.actions.delete")}
              </Button>
            </div>
          ))}
          <Button
            variant="flat"
            onPress={() => {
              setVideoLinks((prev) => [...prev, ""]);
              setVideoDirty(true);
            }}
          >
            {t("edit.actions.add_video_link")}
          </Button>
          <div className="flex justify-end pt-4 border-t">
            <div className="flex items-center gap-2">
              <Button variant="flat" onPress={() => setVideoModalOpen(false)}>
                {t("close")}
              </Button>
              <Button
                color="primary"
                onPress={async () => {
                  const ok = await saveOffer({ navigateBack: false });
                  if (ok) setVideoModalOpen(false);
                }}
                isLoading={saving}
              >
                {t("save")}
              </Button>
            </div>
          </div>
        </div>
      </BaseModal>

      {/* Certificates Modal */}
      <BaseModal
        isOpen={certsModalOpen}
        onOpenChange={setCertsModalOpen}
        placement="center"
        contentClassName="w-full max-w-lg max-h-[85vh] overflow-y-auto rounded-2xl p-4"
        title={t("edit.certificates")}
      >
        <div className="space-y-4">
          {[
            { key: "medical_exam_certificate", file: medicalCert },
            { key: "info_certificate", file: infoCert },
            { key: "owner_document", file: ownerDoc },
          ].map(({ key, file }) => (
            <div
              key={key}
              className="flex items-center justify-between p-3 border rounded-xl"
            >
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center">
                  📄
                </div>
                <div>
                  <div className="font-medium text-sm">
                    {t(`edit.fields.${key}` as any)}
                  </div>
                  <div className="text-xs text-slate-500">
                    {file
                      ? t("edit.status.uploaded")
                      : t("edit.status.not_uploaded")}
                  </div>
                </div>
              </div>
              <div className="flex gap-2">
                {file?.url && (
                  <button
                    type="button"
                    className="p-2 bg-blue-50 text-blue-600 rounded-lg"
                    onClick={() => {
                      if (String(file.url).toLowerCase().endsWith(".pdf")) {
                        openPdf(String(file.url), String(key));
                      } else {
                        window.open(
                          String(file.url),
                          "_blank",
                          "noopener,noreferrer",
                        );
                      }
                    }}
                  >
                    👁
                  </button>
                )}
                <label className="p-2 bg-slate-100 rounded-lg cursor-pointer">
                  📤
                  <input
                    type="file"
                    accept="image/*,application/pdf"
                    className="hidden"
                    onChange={(e) =>
                      handleFilesUpload(`media[${key}]`, key, e.target.files)
                    }
                  />
                </label>
                {file && (
                  <button
                    type="button"
                    className="p-2 bg-red-50 text-red-600 rounded-lg"
                    onClick={() =>
                      handleRemoveExistingFile(files.indexOf(file), file)
                    }
                  >
                    🗑
                  </button>
                )}
              </div>
            </div>
          ))}
          <div className="flex justify-end pt-4 border-t">
            <div className="flex items-center gap-2">
              <Button variant="flat" onPress={() => setCertsModalOpen(false)}>
                {t("close")}
              </Button>
              <Button
                color="primary"
                onPress={async () => {
                  const ok = await saveOffer({ navigateBack: false });
                  if (ok) setCertsModalOpen(false);
                }}
                isLoading={saving}
              >
                {t("save")}
              </Button>
            </div>
          </div>
        </div>
      </BaseModal>

      {/* Details Modal */}
      <BaseModal
        isOpen={detailsModalOpen}
        onOpenChange={setDetailsModalOpen}
        placement="center"
        contentClassName="w-full max-w-2xl max-h-[85vh] overflow-y-auto rounded-2xl p-4"
        title={t("edit.sections.offer_details")}
      >
        <div
          dir={isRTL ? "rtl" : "ltr"}
          className={`space-y-4 ${isRTL ? "text-right" : ""}`}
        >
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Input
              label={t("title")}
              value={general.title}
              onChange={(e) =>
                setGeneral((p) => ({ ...p, title: e.target.value }))
              }
            />
            <Input
              label={t("price")}
              type="number"
              value={general.price}
              onChange={(e) =>
                setGeneral((p) => ({ ...p, price: e.target.value }))
              }
            />
          </div>
          <Textarea
            label={t("description")}
            value={general.description}
            onChange={(e) =>
              setGeneral((p) => ({ ...p, description: e.target.value }))
            }
          />
          {(full.status === "active" || full.status === "rejected") && (
            <div className="flex items-center gap-3">
              <Switch
                isSelected={general.status === "sold"}
                onChange={(value) =>
                  setGeneral((p) => ({
                    ...p,
                    status: value ? "sold" : full.status,
                  }))
                }
              >
                {t("edit.actions.mark_sold")}
              </Switch>
            </div>
          )}
          <div className="space-y-2">
            <div className="text-sm font-semibold text-slate-700">
              {tLoc("map_title")}
            </div>
            <p className="text-sm text-slate-500">{tLoc("map_hint")}</p>
            <LocationMapPicker
              lat={general.lat}
              lng={general.lng}
              height={240}
              onChange={({ lat, lng }) =>
                setGeneral((p) => ({ ...p, lat, lng }))
              }
            />
            <div className="text-xs text-slate-600 font-mono" dir="ltr">
              {`${general.lat.toFixed(6)}, ${general.lng.toFixed(6)}`}
            </div>
          </div>
          <div className="flex justify-end pt-4 border-t">
            <div className="flex items-center gap-2">
              <Button variant="flat" onPress={() => setDetailsModalOpen(false)}>
                {t("close")}
              </Button>
              <Button
                color="primary"
                onPress={async () => {
                  const ok = await saveOffer({ navigateBack: false });
                  if (ok) setDetailsModalOpen(false);
                }}
                isLoading={saving}
              >
                {t("save")}
              </Button>
            </div>
          </div>
        </div>
      </BaseModal>

      {/* Animal Modal */}
      <BaseModal
        isOpen={animalModalOpen}
        onOpenChange={setAnimalModalOpen}
        placement="center"
        contentClassName="w-full max-w-2xl max-h-[85vh] overflow-y-auto rounded-2xl p-4"
        title={
          camel ? t("edit.sections.camel_info") : t("edit.sections.horse_info")
        }
      >
        <div
          dir={isRTL ? "rtl" : "ltr"}
          className={`space-y-4 ${isRTL ? "text-right" : ""}`}
        >
          <div className="grid grid-cols-2 gap-4">
            <Input
              label={t("edit.fields.animal_name")}
              value={(camel || horse)?.name ?? ""}
              onChange={(e) => {
                const setter = camel ? setCamel : setHorse;
                setter((prev: any) => ({ ...prev, name: e.target.value }));
              }}
            />
            <Input
              label={t("edit.fields.father_name")}
              value={(camel || horse)?.father_name ?? ""}
              onChange={(e) => {
                const setter = camel ? setCamel : setHorse;
                setter((prev: any) => ({
                  ...prev,
                  father_name: e.target.value,
                }));
              }}
            />
            <Input
              label={t("edit.fields.mother_name")}
              value={(camel || horse)?.mother_name ?? ""}
              onChange={(e) => {
                const setter = camel ? setCamel : setHorse;
                setter((prev: any) => ({
                  ...prev,
                  mother_name: e.target.value,
                }));
              }}
            />
            <Input
              label={t("edit.fields.mother_father_name")}
              value={(camel || horse)?.mother_father_name ?? ""}
              onChange={(e) => {
                const setter = camel ? setCamel : setHorse;
                setter((prev: any) => ({
                  ...prev,
                  mother_father_name: e.target.value,
                }));
              }}
            />
            <Input
              label={t("edit.fields.date_of_birth")}
              type="date"
              value={(camel || horse)?.date_of_birth ?? ""}
              onChange={(e) => {
                const setter = camel ? setCamel : setHorse;
                setter((prev: any) => ({
                  ...prev,
                  date_of_birth: e.target.value,
                }));
              }}
            />
            {horse && (
              <Input
                label={t("edit.fields.height")}
                type="number"
                value={horse?.height == null ? "" : String(horse.height)}
                onChange={(e) =>
                  setHorse((prev: any) => ({
                    ...prev,
                    height: Number(e.target.value),
                  }))
                }
              />
            )}
            <Input
              label={t("edit.fields.breed")}
              value={(camel || horse)?.breed ?? ""}
              onChange={(e) => {
                const setter = camel ? setCamel : setHorse;
                setter((prev: any) => ({ ...prev, breed: e.target.value }));
              }}
            />
            <Select
              label={t("edit.fields.type")}
              placeholder={tStep4("type_placeholder")}
              selectedKeys={currentAnimalType ? [currentAnimalType] : []}
              onSelectionChange={(keys) => {
                const type = Array.from(keys)[0] as string;
                const setter = camel ? setCamel : setHorse;
                setter((prev: any) => ({ ...prev, type }));
              }}
              items={animalTypeSelectItems}
            >
              {(item) => <SelectItem key={item.value}>{item.label}</SelectItem>}
            </Select>
            {camel && config?.ages && config.ages.length > 0 ? (
              <Select
                label={t("edit.fields.age_category")}
                placeholder={tStep4("age_category_placeholder")}
                selectedKeys={
                  camel?.animal_age_id ? [String(camel.animal_age_id)] : []
                }
                onSelectionChange={(keys) => {
                  const id = Array.from(keys)[0] as string;
                  setCamel((prev: any) => ({
                    ...prev,
                    animal_age_id: id,
                  }));
                }}
              >
                {config.ages.map((a) => (
                  <SelectItem key={String(a.id)}>{a.name}</SelectItem>
                ))}
              </Select>
            ) : null}
          </div>
          <div className="flex justify-end pt-4 border-t">
            <div className="flex items-center gap-2">
              <Button variant="flat" onPress={() => setAnimalModalOpen(false)}>
                {t("close")}
              </Button>
              <Button
                color="primary"
                onPress={async () => {
                  const ok = await saveOffer({ navigateBack: false });
                  if (ok) setAnimalModalOpen(false);
                }}
                isLoading={saving}
              >
                {t("save")}
              </Button>
            </div>
          </div>
        </div>
      </BaseModal>

      {/* PDF Modal */}
      <BaseModal
        isOpen={pdfModalOpen}
        onOpenChange={setPdfModalOpen}
        placement="center"
        contentClassName="w-full max-w-4xl max-h-[85vh] overflow-y-auto rounded-2xl p-3"
        title={selectedPdf?.title || t("edit.fallback.file")}
      >
        {selectedPdf ? (
          <PdfViewer fileUrl={selectedPdf.url} fileName={selectedPdf.title} />
        ) : null}
      </BaseModal>
    </div>
  );
}
