"use client";
import AuthInput from "@/components/auth/AuthInput";
import AuthNextButton from "@/components/auth/AuthNextButton";
import Modal from "@/components/elements/Modal";
import { Service } from "@/types/types";
import React, { useState } from "react";
import { IMAGE_BASE_URL, buildStorageUrl } from "../BaseUrl";
import Image from "next/image";
import toast from "react-hot-toast";
import { v4 as uuidv4 } from "uuid"; // ✅ استفاده از uuid
// import { useRouter } from "next/navigation";

interface AddServiceModalProps {
  onClose: () => void;
  onAdd: (service: Service) => void;
  isModalOpen: boolean;
}

const AddServiceModal: React.FC<AddServiceModalProps> = ({
  onClose,
  onAdd,
  isModalOpen,
}) => {
  const [title, setTitle] = useState("");
  const [originalPrice, setOriginalPrice] = useState<string>("");
  const [discountPrice, setDiscountPrice] = useState<string>("");
  const [serviceImage, setServiceImage] = useState<string | null>(null);

  // const router = useRouter();

const handleSubmit = () => {
  if (!title || !originalPrice) {
    toast.error("لطفاً عنوان و قیمت اصلی را پر کنید.");
    return;
  }
  if (discountPrice && Number(discountPrice) > Number(originalPrice)) {
    toast.error("قیمت تخفیف خورده نمیتواند بزرگتر از قیمت اصلی باشد.");
    return;
  }

  const newService: Service = {
    id: uuidv4(),
    title,
    originalPrice,
    discountPrice,
    image: serviceImage,
    discountPercentage: discountPrice
      ? Math.round(
          ((Number(originalPrice) - Number(discountPrice)) / Number(originalPrice)) * 100
        )
      : 0,
    status: "UnderReview", // ✅ مقدار پیش‌فرض اضافه کن
  };
  

  onAdd(newService);
  onClose();


};

  const selectImage = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = () => setServiceImage(reader.result as string);
      reader.readAsDataURL(file);
    }
  };

  const removeImage = () => setServiceImage(null);

  return (
    <Modal isOpen={isModalOpen} onClose={onClose} height="420px">
      <div className="flex flex-col items-center w-full gap-4 max-w-[500px] mx-auto pb-16">
        <h2 className="text-xl font-bold mb-4">افزودن خدمت</h2>
        <AuthInput
          type="text"
          placeholder="عنوان"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          className="w-full py-2 max-w-[992px] text-right"
        />
        <div className="flex gap-4 w-full">
          <AuthInput
            type="number"
            placeholder="قیمت اصلی"
            value={originalPrice}
            onChange={(e) => setOriginalPrice(e.target.value)}
            className="w-full py-2 max-w-[992px] text-right"
          />
          <AuthInput
            type="number"
            placeholder="قیمت تخفیف خورده"
            value={discountPrice}
            onChange={(e) => setDiscountPrice(e.target.value)}
            className="w-full py-2 max-w-[992px] text-right"
          />
        </div>

        <div className="relative w-[100px] h-[100px] flex items-center justify-center text-white rounded-3xl border border-[#676767] overflow-hidden mt-4">
          {serviceImage ? (
            <>
              <img
                src={serviceImage.startsWith("data:") ? serviceImage : IMAGE_BASE_URL + serviceImage}
                alt="serviceImage"
                className="w-full h-full object-cover"
              />
              <button onClick={removeImage} className="p-2 absolute top-0 right-0">
                <Image src="/images/icons/close-circle.svg" width={25} height={25} alt="remove profile icon" />
              </button>
            </>
          ) : (
            <label
              htmlFor="fileInput"
              className="cursor-pointer w-[100px] h-[100px] flex items-center justify-center text-white rounded-3xl border border-[#676767]"
            >
              <Image src="/images/icons/gallery-add.svg" width={50} height={50} alt="add profile icon" />
            </label>
          )}
        </div>
        <input id="fileInput" type="file" accept="image/*" className="hidden" onChange={selectImage} />

        <AuthNextButton
          onClick={handleSubmit}
          className="mb-4 mt-4 !text-[#0066FF] !border-[#0066FF] w-32"
          type="button"
        >
          افزودن
        </AuthNextButton>
      </div>
    </Modal>
  );
};

export default AddServiceModal;
