"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { useLocale, useTranslations } from "next-intl";
import { useSession } from "@/auth/session-provider";
import {
  Card,
  CardBody,
  Button,
  Input,
  Textarea,
  Select,
  SelectItem,
} from "@heroui/react";
import Image from "next/image";
import { ArrowLeft, ArrowRight, Upload, X, Loader2 } from "lucide-react";
import { uploadImage, removeImage } from "@/actions/upload-image";
import { useAppToast } from "@/app/[lang]/providers";
import AuctionUnifiedTimer from "@/components/count/AuctionUnifiedTimer";
import { API_BASE_URL } from "@/lib/axios";
import type { VaccinationStatusValue } from "@/lib/animalVaccinationStatus";
import { normalizeVaccinationStatusFromPayload } from "@/lib/animalVaccinationStatus";
import {
  applyCamelAgesReferenceParam,
  formatCamelAnimalAgeForDisplay,
} from "@/lib/camelAnimalAge";
import { normalizeNullableDateOfBirth } from "@/lib/animalDateOfBirth";

const API_URL = API_BASE_URL;

const parseAuctionDateMs = (raw: any): number | null => {
  if (!raw) return null;
  if (raw instanceof Date) {
    const ms = raw.getTime();
    return Number.isFinite(ms) ? ms : null;
  }

  let s = String(raw).trim();
  if (!s) return null;

  if (/^\d+$/.test(s)) {
    const n = Number(s);
    if (!Number.isFinite(n)) return null;
    const ms = s.length <= 10 ? n * 1000 : n;
    return Number.isFinite(ms) ? ms : null;
  }

  s = s.replace(/^([0-9]{4})[:\/-]([0-9]{2})[:\/-]([0-9]{2})/, "$1-$2-$3");
  const normalized = s.includes("T") ? s : s.replace(" ", "T");
  const ms = new Date(normalized).getTime();
  return Number.isFinite(ms) ? ms : null;
};

export default function EditSingleAuctionPage() {
  const params = useParams();
  const groupAuctionId = params?.id as string;
  const singleAuctionId = params?.singleAuctionId as string;
  const lang = useLocale();
  const isRTL = lang === "ar";
  const tToast = useTranslations("TOAST");
  const tVax = useTranslations("ANIMAL_VACCINATION_STATUS");
  const session = useSession();
  const router = useRouter();
  const toast = useAppToast();

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<any>(null);
  const [config, setConfig] = useState<any>(null);

  // Form state
  const [description, setDescription] = useState("");
  const [startingPrice, setStartingPrice] = useState("");
  const [marketEntryPrice, setMarketEntryPrice] = useState("");
  const [stateId, setStateId] = useState("");

  // Horse/Camel state
  const [animal, setAnimal] = useState<any>({
    name: "",
    father_name: "",
    mother_name: "",
    mother_father_name: "",
    gender: "male",
    date_of_birth: "",
    breed: "",
    height: "",
    type: "",
    vaccination_status: "" as VaccinationStatusValue | "",
    animal_color_id: "",
    animal_usage_id: "",
    animal_age_id: "",
  });

  // Owner state
  const [owner, setOwner] = useState<any>({
    name: "",
    phone: "",
    state_id: "",
  });

  // Files state
  const [files, setFiles] = useState<any[]>([]);
  const [uploading, setUploading] = useState<string | null>(null);

  const label = (key: string) => {
    const map: Record<string, { ar: string; en: string }> = {
      name: { ar: "الاسم", en: "Name" },
      father_name: { ar: "اسم الأب", en: "Father Name" },
      mother_name: { ar: "اسم الأم", en: "Mother Name" },
      mother_father_name: { ar: "اسم جد الأم", en: "Mother's Father Name" },
      gender: { ar: "الجنس", en: "Gender" },
      date_of_birth: { ar: "تاريخ الميلاد", en: "Date of Birth" },
      breed: { ar: "السلالة", en: "Breed" },
      height: { ar: "الارتفاع (سم)", en: "Height (cm)" },
      type: { ar: "النوع", en: "Type" },
      vaccination_status: { ar: "حالة التطعيم", en: "Vaccination status" },
      animal_color_id: { ar: "اللون", en: "Color" },
      animal_usage_id: { ar: "الاستخدام", en: "Usage" },
      animal_age_id: { ar: "فئة العمر", en: "Age category" },
      description: { ar: "الوصف", en: "Description" },
      starting_price: { ar: "السعر الابتدائي", en: "Starting Price" },
      market_entry_price: { ar: "سعر دخول السوق", en: "Market Entry Price" },
      state_id: { ar: "المدينة", en: "City" },
      owner_name: { ar: "اسم المالك", en: "Owner Name" },
      owner_phone: { ar: "هاتف المالك", en: "Owner Phone" },
      owner_state: { ar: "مدينة المالك", en: "Owner City" },
      main_image: { ar: "الصورة الرئيسية", en: "Main Image" },
      additional_images: { ar: "صور إضافية", en: "Additional Images" },
      medical_exam_certificate: {
        ar: "شهادة الفحص الطبي",
        en: "Medical Certificate",
      },
      info_certificate: { ar: "شهادة المعلومات", en: "Info Certificate" },
      owner_document: { ar: "وثيقة المالك", en: "Owner Document" },
      male: { ar: "ذكر", en: "Male" },
      female: { ar: "أنثى", en: "Female" },
    };
    const entry = map[key];
    return entry ? (isRTL ? entry.ar : entry.en) : key;
  };

  // Fetch data
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const token = session?.access_token;

        // Fetch single auction details
        const res = await fetch(
          `${API_URL}/user/dashboard/single-auctions/${singleAuctionId}`,
          {
            headers: {
              Authorization: `Bearer ${token}`,
              Accept: "application/json",
            },
          },
        );

        if (!res.ok) throw new Error("Failed to fetch auction details");

        const json = await res.json();
        const auctionData = json.data;
        setData(auctionData);

        // Set form values
        setDescription(auctionData.description || "");
        setStartingPrice(auctionData.starting_price || "");
        setMarketEntryPrice(auctionData.market_entry_price || "");

        // Set animal data (horse or camel)
        const animalData = auctionData.horse || auctionData.camel || {};
        setAnimal({
          name: animalData.name || "",
          father_name: animalData.father_name || "",
          mother_name: animalData.mother_name || "",
          mother_father_name: animalData.mother_father_name || "",
          gender: animalData.gender || "male",
          date_of_birth: animalData.date_of_birth || "",
          breed: animalData.breed || "",
          height: animalData.height || "",
          type: animalData.type || "",
          vaccination_status:
            animalData.type === "breeding_female"
              ? normalizeVaccinationStatusFromPayload(animalData) ?? "unsure"
              : "",
          animal_color_id: animalData.animal_color_id || "",
          animal_usage_id: animalData.animal_usage_id || "",
          animal_age_id:
            animalData.animal_age_id != null &&
            String(animalData.animal_age_id).trim() !== ""
              ? String(animalData.animal_age_id)
              : "",
        });

        // Set owner data
        if (auctionData.owner) {
          setOwner({
            name: auctionData.owner.name || "",
            phone: auctionData.owner.phone || "",
            state_id: auctionData.owner.state_id || "",
          });
        }

        // Set files
        const combinedFiles: any[] = [];
        const media = auctionData.media_files || {};

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

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

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

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

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

        setFiles(combinedFiles);

        // Fetch config for dropdowns
        const animalType = auctionData.horse ? "horse" : "camel";
        const refParams = new URLSearchParams({
          countries: "1",
          usages: "1",
          animal_type: animalType,
          colors: "1",
        });
        applyCamelAgesReferenceParam(
          refParams,
          animalType as "horse" | "camel",
        );
        const configRes = await fetch(
          `${API_URL}/user/config/reference-data?${refParams.toString()}`,
          {
            headers: {
              Authorization: `Bearer ${token}`,
              Accept: "application/json",
            },
          },
        );

        if (configRes.ok) {
          const configJson = await configRes.json();
          setConfig(configJson.data);

          // Try to find state_id from country name
          if (auctionData.state && configJson.data?.countries) {
            const allStates = configJson.data.countries.flatMap(
              (c: any) => c.states || [],
            );
            const foundState = allStates.find(
              (s: any) => s.name === auctionData.state,
            );
            if (foundState) setStateId(String(foundState.id));
          }

          // Try to find color/usage IDs
          if (animalData.animal_color && configJson.data?.colors) {
            const foundColor = configJson.data.colors.find(
              (c: any) => c.name === animalData.animal_color,
            );
            if (foundColor) {
              setAnimal((prev: any) => ({
                ...prev,
                animal_color_id: String(foundColor.id),
              }));
            }
          }

          if (animalData.animal_usage && configJson.data?.usages) {
            const foundUsage = configJson.data.usages.find(
              (u: any) => u.name === animalData.animal_usage,
            );
            if (foundUsage) {
              setAnimal((prev: any) => ({
                ...prev,
                animal_usage_id: String(foundUsage.id),
              }));
            }
          }

          if (
            auctionData.camel &&
            !(animalData as any).animal_age_id &&
            animalData.animal_age &&
            Array.isArray(configJson.data?.ages)
          ) {
            const display = formatCamelAnimalAgeForDisplay(
              animalData.animal_age,
            );
            if (display) {
              const foundAge = configJson.data.ages.find(
                (a: any) => a.name === display,
              );
              if (foundAge) {
                setAnimal((prev: any) => ({
                  ...prev,
                  animal_age_id: String(foundAge.id),
                }));
              }
            }
          }

          // Owner state
          if (auctionData.owner?.state && configJson.data?.countries) {
            const allStates = configJson.data.countries.flatMap(
              (c: any) => c.states || [],
            );
            const foundState = allStates.find(
              (s: any) => s.name === auctionData.owner.state,
            );
            if (foundState) {
              setOwner((prev: any) => ({
                ...prev,
                state_id: String(foundState.id),
              }));
            }
          }
        }

        setError(null);
      } catch (e: any) {
        console.error(e);
        setError(e?.message || tToast("edit_page_load_failed"));
      } finally {
        setLoading(false);
      }
    };

    if (singleAuctionId && session?.access_token) {
      fetchData();
    }
  }, [singleAuctionId, session?.access_token, tToast]);

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

    const singleCollections = new Set([
      "main_image",
      "medical_exam_certificate",
      "info_certificate",
      "owner_document",
    ]);

    if (singleCollections.has(collectionName)) {
      const alreadyHasOne = files.some(
        (f) => f.collection_name === collectionName,
      );
      if (alreadyHasOne) {
        toast.error(tToast("file_exists_remove_first"));
        return;
      }
    }

    setUploading(collectionName);

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

    const filesArray = Array.from(fileList);

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

    try {
      const res = await uploadImage(formData);
      if (res?.success && Array.isArray(res.data)) {
        const uploadedFiles = res.data.map((f: any) => ({
          collection_name: f.collection_name,
          url: f.url,
        }));
        setFiles((prev) => [...prev, ...uploadedFiles]);
        toast.success(tToast("file_upload_success"));
      } else {
        toast.error(tToast("upload_failed"));
      }
    } catch (error) {
      console.error("upload error", error);
      toast.error(tToast("upload_failed"));
    } finally {
      setUploading(null);
    }
  };

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

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

  const handleSave = async () => {
    if (!data) return;

    setSaving(true);
    try {
      const token = session?.access_token;
      const animalType = data.horse ? "horse" : "camel";

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

      // Top-level simple fields: أرسل فقط إذا تغيّرت عن الداتا الأصلية
      if (description !== (data.description || "")) {
        payload.description = description;
      }
      if (startingPrice !== (data.starting_price || "")) {
        payload.starting_price = startingPrice;
      }
      if (marketEntryPrice !== (data.market_entry_price || "")) {
        payload.market_entry_price = marketEntryPrice;
      }

      // state_id: الأصل عندنا من الـ config؛ إذا المستخدم اختار مدينة نرسلها
      if (stateId) {
        payload.state_id = stateId;
      }

      // الملفات: إذا تغيّرت (إضافة/حذف) لازم نرسلها دائماً
      if (files.length > 0) {
        payload.files = files.map((f) => ({
          collection_name: f.collection_name,
          url: f.url,
        }));
      }

      // Animal payload (horse / camel): إبنِ فقط إذا تغيّر شيء عن الداتا الأصلية
      const originalAnimal: any = data.horse || data.camel || {};
      const animalPayload: any = {};

      if (animal.name !== (originalAnimal.name || "")) {
        animalPayload.name = animal.name;
      }
      if (animal.father_name !== (originalAnimal.father_name || "")) {
        animalPayload.father_name = animal.father_name;
      }
      if (animal.mother_name !== (originalAnimal.mother_name || "")) {
        animalPayload.mother_name = animal.mother_name;
      }
      if (
        animal.mother_father_name !== (originalAnimal.mother_father_name || "")
      ) {
        animalPayload.mother_father_name = animal.mother_father_name;
      }
      if (animal.gender !== (originalAnimal.gender || "")) {
        animalPayload.gender = animal.gender;
      }
      if (animalType === "camel") {
        const nextDob = normalizeNullableDateOfBirth(animal.date_of_birth);
        const origDob = normalizeNullableDateOfBirth(
          originalAnimal.date_of_birth,
        );
        if (nextDob !== origDob) {
          animalPayload.date_of_birth = nextDob;
        }
      } else {
        if (animal.date_of_birth !== (originalAnimal.date_of_birth || "")) {
          animalPayload.date_of_birth = animal.date_of_birth;
        }
      }
      if (animal.breed !== (originalAnimal.breed || "")) {
        animalPayload.breed = animal.breed;
      }
      if (String(animal.height || "") !== String(originalAnimal.height || "")) {
        animalPayload.height = animal.height;
      }
      if (animal.type !== (originalAnimal.type || "")) {
        animalPayload.type = animal.type;
      }
      const originalVaxNorm: VaccinationStatusValue | "" =
        originalAnimal.type === "breeding_female"
          ? normalizeVaccinationStatusFromPayload(originalAnimal) ?? "unsure"
          : "";
      const currentVaxNorm: VaccinationStatusValue | "" =
        animal.type === "breeding_female"
          ? (animal.vaccination_status as VaccinationStatusValue) || "unsure"
          : "";
      if (
        animal.type === "breeding_female" &&
        currentVaxNorm !== originalVaxNorm
      ) {
        animalPayload.vaccination_status = currentVaxNorm;
      }
      if (
        animal.animal_color_id &&
        animal.animal_color_id !== (originalAnimal.animal_color_id || "")
      ) {
        animalPayload.animal_color_id = animal.animal_color_id;
      }
      if (
        animal.animal_usage_id &&
        animal.animal_usage_id !== (originalAnimal.animal_usage_id || "")
      ) {
        animalPayload.animal_usage_id = animal.animal_usage_id;
      }
      if (animalType === "camel") {
        const curAge = String(animal.animal_age_id || "");
        const origAge = String(originalAnimal.animal_age_id || "");
        if (curAge && curAge !== origAge) {
          animalPayload.animal_age_id = curAge;
        }
      }

      if (Object.keys(animalPayload).length > 0) {
        payload[animalType] = animalPayload;
      }

      // Owner payload: أرسل فقط إذا تغيّر شيء
      const originalOwner: any = data.owner || {};
      const ownerPayload: any = {};

      if (owner.name !== (originalOwner.name || "")) {
        ownerPayload.name = owner.name;
      }
      if (owner.phone !== (originalOwner.phone || "")) {
        ownerPayload.phone = owner.phone;
      }
      if (owner.state_id && owner.state_id !== (originalOwner.state_id || "")) {
        ownerPayload.state_id = owner.state_id;
      }

      if (Object.keys(ownerPayload).length > 0) {
        payload.owner = ownerPayload;
      }

      const res = await fetch(
        `${API_URL}/user/dashboard/single-auctions/${singleAuctionId}`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        },
      );

      if (res.ok) {
        toast.success(tToast("form_save_success"));
        router.back();
      } else {
        const errData = await res.json();
        toast.error(errData.message || tToast("form_save_failed"));
      }
    } catch (e: any) {
      console.error(e);
      toast.error(e?.message || tToast("dashboard_generic_error"));
    } finally {
      setSaving(false);
    }
  };

  const allStates =
    config?.countries?.flatMap((c: any) => c.states || []) || [];

  const countdownMeta = (() => {
    if (!data) return { target: null as number | null, label: null as string | null };

    const now = Date.now();
    const auctionState = String(data?.auction_state || "").toLowerCase();
    const startMs = parseAuctionDateMs(
      data?.auction_start_time || data?.auction_start_datetime,
    );
    const endMs = parseAuctionDateMs(
      data?.auction_end_time || data?.auction_end_datetime,
    );

    if (auctionState === "upcoming") {
      return {
        target: startMs ?? endMs,
        label: isRTL ? "العد التنازلي لبدء المزاد" : "Auction starts in",
      };
    }

    if (auctionState === "active" || auctionState === "live") {
      return {
        target: endMs,
        label: isRTL ? "العد التنازلي لانتهاء المزاد" : "Auction ends in",
      };
    }

    // Fallback based on dates when state is not explicit
    if (startMs && startMs > now) {
      return {
        target: startMs,
        label: isRTL ? "العد التنازلي لبدء المزاد" : "Auction starts in",
      };
    }

    if (endMs && endMs > now) {
      return {
        target: endMs,
        label: isRTL ? "العد التنازلي لانتهاء المزاد" : "Auction ends in",
      };
    }

    return { target: null as number | null, label: null as string | null };
  })();

  if (loading) {
    return (
      <div className="max-w-4xl mx-auto px-4 py-8">
        <div className="flex items-center justify-center py-16">
          <Loader2 className="w-8 h-8 animate-spin text-primary" />
        </div>
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="max-w-4xl mx-auto px-4 py-8">
        <Card className="border rounded-2xl">
          <CardBody>
            <div className="text-center p-8 text-red-500">
              {error ||
                (isRTL ? "لم يتم العثور على البيانات" : "Data not found")}
            </div>
            <div className="flex justify-center">
              <Button onPress={() => router.back()}>
                {isRTL ? "رجوع" : "Go Back"}
              </Button>
            </div>
          </CardBody>
        </Card>
      </div>
    );
  }

  const mainImage = files.find((f) => f.collection_name === "main_image");
  const additionalImages = files.filter(
    (f) => f.collection_name === "additional_images",
  );
  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="min-h-screen bg-[#F7F8F5]">
      <div className="max-w-7xl mx-auto px-4 py-8 mt-16">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
        <main className="lg:col-span-8 space-y-6">
          {/* Header */}
          <div className="rounded-2xl border border-[#0f5132]/15 bg-gradient-to-br from-[#0f5132] to-[#1b7a50] text-white p-5 md:p-6 shadow-[0_12px_30px_rgba(15,81,50,0.22)]">
            <div className="flex items-center justify-between gap-3">
              <button
                type="button"
                onClick={() => router.back()}
                className="group inline-flex items-center gap-2 px-3.5 py-2 rounded-full bg-white/10 border border-white/30 hover:bg-white/15 transition"
              >
                <span className="inline-flex h-7 w-7 items-center justify-center rounded-full bg-white/20">
                  {isRTL ? <ArrowRight size={16} /> : <ArrowLeft size={16} />}
                </span>
                <span className="text-sm font-semibold">
                  {isRTL ? "رجوع" : "Back"}
                </span>
              </button>
              <span className="inline-flex items-center rounded-full bg-white/15 border border-white/25 px-3 py-1 text-xs font-semibold">
                {data?.horse
                  ? isRTL
                    ? "مزاد خيل"
                    : "Horse Auction"
                  : isRTL
                    ? "مزاد إبل"
                    : "Camel Auction"}
              </span>
            </div>

            <h1 className="mt-4 text-2xl md:text-3xl font-extrabold">
              {isRTL ? "تعديل المزاد" : "Edit Auction"}{" "}
              <span className="text-emerald-200">#{data.unique_id}</span>
            </h1>
            <p className="mt-2 text-sm md:text-base text-white/85 line-clamp-2">
              {data.title}
            </p>

            <div className="mt-4 flex flex-wrap items-center gap-2">
              {data?.auction_state ? (
                <span className="rounded-full bg-white/15 border border-white/25 px-3 py-1 text-xs font-semibold">
                  {isRTL ? "حالة المزاد:" : "Auction state:"}{" "}
                  {String(data.auction_state)}
                </span>
              ) : null}
              {data?.status ? (
                <span className="rounded-full bg-white/15 border border-white/25 px-3 py-1 text-xs font-semibold">
                  {isRTL ? "حالة الطلب:" : "Request status:"} {String(data.status)}
                </span>
              ) : null}
            </div>
          </div>

          {/* Main Image */}
          <Card className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <h2 className="font-bold text-lg">{label("main_image")}</h2>
              <div className="flex items-start gap-4">
                {mainImage ? (
                  <div className="relative w-48 h-32 rounded-lg overflow-hidden border">
                    <Image
                      src={mainImage.url}
                      alt="Main"
                      fill
                      className="object-cover"
                      unoptimized
                    />
                    <button
                      type="button"
                      onClick={() =>
                        handleRemoveFile(files.indexOf(mainImage), mainImage)
                      }
                      className="absolute top-1 right-1 bg-red-500 text-white p-1 rounded-full"
                    >
                      <X size={14} />
                    </button>
                  </div>
                ) : (
                  <label className="flex flex-col items-center justify-center w-48 h-32 border-2 border-dashed rounded-lg cursor-pointer hover:bg-slate-50">
                    {uploading === "main_image" ? (
                      <Loader2 className="w-6 h-6 animate-spin text-primary" />
                    ) : (
                      <>
                        <Upload className="w-6 h-6 text-slate-400" />
                        <span className="text-xs text-slate-500 mt-1">
                          {isRTL ? "رفع صورة" : "Upload"}
                        </span>
                      </>
                    )}
                    <input
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={(e) =>
                        handleFileUpload("main_image", e.target.files)
                      }
                      disabled={uploading === "main_image"}
                    />
                  </label>
                )}
              </div>
            </CardBody>
          </Card>

          {/* Additional Images */}
          <Card className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <h2 className="font-bold text-lg">
                {label("additional_images")}
              </h2>
              <div className="flex flex-wrap gap-3">
                {additionalImages.map((img, idx) => (
                  <div
                    key={idx}
                    className="relative w-24 h-24 rounded-lg overflow-hidden border"
                  >
                    <Image
                      src={img.url}
                      alt={`Additional ${idx}`}
                      fill
                      className="object-cover"
                      unoptimized
                    />
                    <button
                      type="button"
                      onClick={() => handleRemoveFile(files.indexOf(img), img)}
                      className="absolute top-1 right-1 bg-red-500 text-white p-1 rounded-full"
                    >
                      <X size={12} />
                    </button>
                  </div>
                ))}
                <label className="flex flex-col items-center justify-center w-24 h-24 border-2 border-dashed rounded-lg cursor-pointer hover:bg-slate-50">
                  {uploading === "additional_images" ? (
                    <Loader2 className="w-5 h-5 animate-spin text-primary" />
                  ) : (
                    <Upload className="w-5 h-5 text-slate-400" />
                  )}
                  <input
                    type="file"
                    accept="image/*"
                    multiple
                    className="hidden"
                    onChange={(e) =>
                      handleFileUpload("additional_images", e.target.files)
                    }
                    disabled={uploading === "additional_images"}
                  />
                </label>
              </div>
            </CardBody>
          </Card>

          {/* Basic Info */}
          <Card className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <h2 className="font-bold text-lg">
                {isRTL ? "معلومات أساسية" : "Basic Info"}
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <Textarea
                  label={label("description")}
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  className="col-span-full"
                />
                <Input
                  label={label("starting_price")}
                  type="number"
                  value={startingPrice}
                  onChange={(e) => setStartingPrice(e.target.value)}
                />
                <Input
                  label={label("market_entry_price")}
                  type="number"
                  value={marketEntryPrice}
                  onChange={(e) => setMarketEntryPrice(e.target.value)}
                />
                <Select
                  label={label("state_id")}
                  selectedKeys={stateId ? [stateId] : []}
                  onSelectionChange={(keys) =>
                    setStateId(Array.from(keys)[0] as string)
                  }
                >
                  {allStates.map((s: any) => (
                    <SelectItem key={String(s.id)}>{s.name}</SelectItem>
                  ))}
                </Select>
              </div>
            </CardBody>
          </Card>

          {/* Animal Info */}
          <Card className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <h2 className="font-bold text-lg">
                {data.horse
                  ? isRTL
                    ? "معلومات الخيل"
                    : "Horse Info"
                  : isRTL
                    ? "معلومات الإبل"
                    : "Camel Info"}
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <Input
                  label={label("name")}
                  value={animal.name}
                  onChange={(e) =>
                    setAnimal({ ...animal, name: e.target.value })
                  }
                />
                <Input
                  label={label("father_name")}
                  value={animal.father_name}
                  onChange={(e) =>
                    setAnimal({ ...animal, father_name: e.target.value })
                  }
                />
                <Input
                  label={label("mother_name")}
                  value={animal.mother_name}
                  onChange={(e) =>
                    setAnimal({ ...animal, mother_name: e.target.value })
                  }
                />
                <Input
                  label={label("mother_father_name")}
                  value={animal.mother_father_name}
                  onChange={(e) =>
                    setAnimal({ ...animal, mother_father_name: e.target.value })
                  }
                />
                <Select
                  label={label("gender")}
                  selectedKeys={animal.gender ? [animal.gender] : []}
                  onSelectionChange={(keys) =>
                    setAnimal({
                      ...animal,
                      gender: Array.from(keys)[0] as string,
                    })
                  }
                >
                  <SelectItem key="male">{label("male")}</SelectItem>
                  <SelectItem key="female">{label("female")}</SelectItem>
                </Select>
                <Input
                  label={label("date_of_birth")}
                  type="date"
                  value={animal.date_of_birth}
                  onChange={(e) =>
                    setAnimal({ ...animal, date_of_birth: e.target.value })
                  }
                />
                <Input
                  label={label("breed")}
                  value={animal.breed}
                  onChange={(e) =>
                    setAnimal({ ...animal, breed: e.target.value })
                  }
                />
                <Input
                  label={label("height")}
                  type="number"
                  value={animal.height}
                  onChange={(e) =>
                    setAnimal({ ...animal, height: e.target.value })
                  }
                />
                <Input
                  label={label("type")}
                  value={animal.type}
                  onChange={(e) => {
                    const nextType = e.target.value;
                    setAnimal((prev: any) => ({
                      ...prev,
                      type: nextType,
                      vaccination_status:
                        nextType === "breeding_female"
                          ? prev.vaccination_status || "unsure"
                          : "",
                    }));
                  }}
                />
                {animal.type === "breeding_female" && (
                  <Select
                    label={label("vaccination_status")}
                    selectedKeys={
                      animal.vaccination_status
                        ? [String(animal.vaccination_status)]
                        : []
                    }
                    onSelectionChange={(keys) =>
                      setAnimal({
                        ...animal,
                        vaccination_status: Array.from(keys)[0] as string,
                      })
                    }
                  >
                    <SelectItem key="vaccinated">{tVax("vaccinated")}</SelectItem>
                    <SelectItem key="unvaccinated">
                      {tVax("unvaccinated")}
                    </SelectItem>
                    <SelectItem key="unsure">{tVax("unsure")}</SelectItem>
                  </Select>
                )}
                {config?.colors && (
                  <Select
                    label={label("animal_color_id")}
                    selectedKeys={
                      animal.animal_color_id ? [animal.animal_color_id] : []
                    }
                    onSelectionChange={(keys) =>
                      setAnimal({
                        ...animal,
                        animal_color_id: Array.from(keys)[0] as string,
                      })
                    }
                  >
                    {config.colors.map((c: any) => (
                      <SelectItem key={String(c.id)}>{c.name}</SelectItem>
                    ))}
                  </Select>
                )}
                {config?.usages && (
                  <Select
                    label={label("animal_usage_id")}
                    selectedKeys={
                      animal.animal_usage_id ? [animal.animal_usage_id] : []
                    }
                    onSelectionChange={(keys) =>
                      setAnimal({
                        ...animal,
                        animal_usage_id: Array.from(keys)[0] as string,
                      })
                    }
                  >
                    {config.usages.map((u: any) => (
                      <SelectItem key={String(u.id)}>{u.name}</SelectItem>
                    ))}
                  </Select>
                )}
                {data?.camel && config?.ages && config.ages.length > 0 ? (
                  <Select
                    label={label("animal_age_id")}
                    selectedKeys={
                      animal.animal_age_id ? [String(animal.animal_age_id)] : []
                    }
                    onSelectionChange={(keys) =>
                      setAnimal({
                        ...animal,
                        animal_age_id: Array.from(keys)[0] as string,
                      })
                    }
                  >
                    {config.ages.map((a: any) => (
                      <SelectItem key={String(a.id)}>{a.name}</SelectItem>
                    ))}
                  </Select>
                ) : null}
              </div>
            </CardBody>
          </Card>

          {/* Owner Info */}
          <Card className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <h2 className="font-bold text-lg">
                {isRTL ? "معلومات المالك" : "Owner Info"}
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <Input
                  label={label("owner_name")}
                  value={owner.name}
                  onChange={(e) => setOwner({ ...owner, name: e.target.value })}
                />
                <Input
                  label={label("owner_phone")}
                  value={owner.phone}
                  onChange={(e) =>
                    setOwner({ ...owner, phone: e.target.value })
                  }
                />
                <Select
                  label={label("owner_state")}
                  selectedKeys={owner.state_id ? [owner.state_id] : []}
                  onSelectionChange={(keys) =>
                    setOwner({
                      ...owner,
                      state_id: Array.from(keys)[0] as string,
                    })
                  }
                >
                  {allStates.map((s: any) => (
                    <SelectItem key={String(s.id)}>{s.name}</SelectItem>
                  ))}
                </Select>
              </div>
            </CardBody>
          </Card>

          {/* Certificates */}
          <Card className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <h2 className="font-bold text-lg">
                {isRTL ? "الشهادات والوثائق" : "Certificates"}
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {/* Medical Certificate */}
                <div>
                  <p className="text-sm font-medium mb-2">
                    {label("medical_exam_certificate")}
                  </p>
                  {medicalCert ? (
                    <div className="flex items-center gap-2 p-2 bg-slate-50 rounded-lg">
                      <a
                        href={medicalCert.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-sm text-primary truncate flex-1"
                      >
                        {isRTL ? "عرض الملف" : "View File"}
                      </a>
                      <button
                        onClick={() =>
                          handleRemoveFile(
                            files.indexOf(medicalCert),
                            medicalCert,
                          )
                        }
                        className="text-red-500"
                      >
                        <X size={16} />
                      </button>
                    </div>
                  ) : (
                    <label className="flex items-center justify-center p-3 border-2 border-dashed rounded-lg cursor-pointer hover:bg-slate-50">
                      {uploading === "medical_exam_certificate" ? (
                        <Loader2 className="w-5 h-5 animate-spin" />
                      ) : (
                        <Upload className="w-5 h-5 text-slate-400" />
                      )}
                      <input
                        type="file"
                        accept="image/*,.pdf"
                        className="hidden"
                        onChange={(e) =>
                          handleFileUpload(
                            "medical_exam_certificate",
                            e.target.files,
                          )
                        }
                      />
                    </label>
                  )}
                </div>

                {/* Info Certificate */}
                <div>
                  <p className="text-sm font-medium mb-2">
                    {label("info_certificate")}
                  </p>
                  {infoCert ? (
                    <div className="flex items-center gap-2 p-2 bg-slate-50 rounded-lg">
                      <a
                        href={infoCert.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-sm text-primary truncate flex-1"
                      >
                        {isRTL ? "عرض الملف" : "View File"}
                      </a>
                      <button
                        onClick={() =>
                          handleRemoveFile(files.indexOf(infoCert), infoCert)
                        }
                        className="text-red-500"
                      >
                        <X size={16} />
                      </button>
                    </div>
                  ) : (
                    <label className="flex items-center justify-center p-3 border-2 border-dashed rounded-lg cursor-pointer hover:bg-slate-50">
                      {uploading === "info_certificate" ? (
                        <Loader2 className="w-5 h-5 animate-spin" />
                      ) : (
                        <Upload className="w-5 h-5 text-slate-400" />
                      )}
                      <input
                        type="file"
                        accept="image/*,.pdf"
                        className="hidden"
                        onChange={(e) =>
                          handleFileUpload("info_certificate", e.target.files)
                        }
                      />
                    </label>
                  )}
                </div>

                {/* Owner Document */}
                <div>
                  <p className="text-sm font-medium mb-2">
                    {label("owner_document")}
                  </p>
                  {ownerDoc ? (
                    <div className="flex items-center gap-2 p-2 bg-slate-50 rounded-lg">
                      <a
                        href={ownerDoc.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-sm text-primary truncate flex-1"
                      >
                        {isRTL ? "عرض الملف" : "View File"}
                      </a>
                      <button
                        onClick={() =>
                          handleRemoveFile(files.indexOf(ownerDoc), ownerDoc)
                        }
                        className="text-red-500"
                      >
                        <X size={16} />
                      </button>
                    </div>
                  ) : (
                    <label className="flex items-center justify-center p-3 border-2 border-dashed rounded-lg cursor-pointer hover:bg-slate-50">
                      {uploading === "owner_document" ? (
                        <Loader2 className="w-5 h-5 animate-spin" />
                      ) : (
                        <Upload className="w-5 h-5 text-slate-400" />
                      )}
                      <input
                        type="file"
                        accept="image/*,.pdf"
                        className="hidden"
                        onChange={(e) =>
                          handleFileUpload("owner_document", e.target.files)
                        }
                      />
                    </label>
                  )}
                </div>
              </div>
            </CardBody>
          </Card>

          {/* Actions */}
          <div className="flex justify-end gap-3">
            <Button variant="flat" onPress={() => router.back()}>
              {isRTL ? "إلغاء" : "Cancel"}
            </Button>
            <Button color="primary" onPress={handleSave} isLoading={saving}>
              {isRTL ? "حفظ التغييرات" : "Save Changes"}
            </Button>
          </div>
        </main>

        {/* Sidebar summary */}
        <aside className="lg:col-span-4 space-y-6">
          <Card className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-xs uppercase tracking-wide text-slate-400">
                    {isRTL ? "رقم العينة" : "Single Auction"}
                  </div>
                  <div className="text-lg font-extrabold text-slate-900">
                    {data.unique_id || "—"}
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                <div className="p-3 rounded-xl bg-slate-50">
                  <div className="text-slate-500">
                    {isRTL ? "الدولة / المدينة" : "Country / City"}
                  </div>
                  <div className="font-semibold text-slate-900">
                    {(data.country || "") +
                      (data.state ? ` - ${data.state}` : "") || "—"}
                  </div>
                </div>

                {data.starting_price && (
                  <div className="p-3 rounded-xl bg-slate-50">
                    <div className="text-slate-500">
                      {label("starting_price")}
                    </div>
                    <div className="font-extrabold text-slate-900">
                      {data.starting_price}
                    </div>
                  </div>
                )}

                {data.market_entry_price && (
                  <div className="p-3 rounded-xl bg-slate-50">
                    <div className="text-slate-500">
                      {label("market_entry_price")}
                    </div>
                    <div className="font-extrabold text-slate-900">
                      {data.market_entry_price}
                    </div>
                  </div>
                )}

                {data.status && (
                  <div className="p-3 rounded-xl bg-slate-50">
                    <div className="text-slate-500">
                      {isRTL ? "حالة الطلب" : "Status"}
                    </div>
                    <div className="inline-flex px-3 py-1 rounded-full text-xs font-bold bg-slate-100 text-slate-700 mt-1">
                      {String(data.status)}
                    </div>
                  </div>
                )}
              </div>
            </CardBody>
          </Card>

          {countdownMeta.target && countdownMeta.label ? (
            <Card className="border rounded-2xl shadow-soft">
              <CardBody className="space-y-3">
                <h3 className="text-base font-bold text-slate-900">
                  {isRTL ? "مؤقت المزاد" : "Auction Timer"}
                </h3>
                <AuctionUnifiedTimer
                  targetDate={countdownMeta.target}
                  label={countdownMeta.label}
                  variant="surface"
                />
              </CardBody>
            </Card>
          ) : null}

          <Card className="border rounded-2xl shadow-soft">
            <CardBody className="space-y-3">
              <h3 className="text-base font-bold text-[#0f5132]">
                {isRTL
                  ? "الالتزام بلوائح المزاد وسياسة المنصة"
                  : "Auction Regulations & Platform Policy"}
              </h3>
              <p className="text-sm leading-7 text-slate-600">
                {isRTL ? (
                  <>
                    يرجى قراءة{" "}
                    <Link
                      href={`/${lang}/privacy`}
                      className="text-[#0f5132] font-semibold underline underline-offset-2"
                    >
                      سياسة الخصوصية
                    </Link>{" "}
                    و{" "}
                    <Link
                      href={`/${lang}/term-conditions`}
                      className="text-[#0f5132] font-semibold underline underline-offset-2"
                    >
                      الشروط والأحكام
                    </Link>{" "}
                    قبل حفظ التعديلات.
                  </>
                ) : (
                  <>
                    Please review{" "}
                    <Link
                      href={`/${lang}/privacy`}
                      className="text-[#0f5132] font-semibold underline underline-offset-2"
                    >
                      Privacy Policy
                    </Link>{" "}
                    and{" "}
                    <Link
                      href={`/${lang}/term-conditions`}
                      className="text-[#0f5132] font-semibold underline underline-offset-2"
                    >
                      Terms & Conditions
                    </Link>{" "}
                    before saving changes.
                  </>
                )}
              </p>
            </CardBody>
          </Card>
        </aside>
      </div>
    </div>
    </div>
  );
}
