"use client";
import Modal from "@/components/elements/Modal";
import RoundedInput from "@/components/elements/RoundedInput";
import RoundedButton from "@/components/elements/RoundedButton";
import { Service } from "@/types/types";
import React, { useState } from "react";
import { IMAGE_BASE_URL } from "../BaseUrl";
import Image from "next/image";
import toast from "react-hot-toast";
import { v4 as uuidv4 } from "uuid";
import { useTranslation } from "react-i18next";

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

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

  const handleSubmit = () => {
    if (!title || !originalPrice) {
      toast.error(t("serviceModal.titlePriceRequired"));
      return;
    }
    if (discountPrice && Number(discountPrice) > Number(originalPrice)) {
      toast.error(t("serviceModal.discountTooHigh"));
      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="auto"
      // هم‌سطح منوبار (z-50) تا منوبار مثل بقیه مودال‌های ثبت بیلبورد روی شیت بماند
      panelClassName="max-h-[min(78dvh,calc(100dvh-6rem))] overflow-y-auto pb-[calc(5.5rem+env(safe-area-inset-bottom))]"
    >
      <div className="mx-auto flex w-full max-w-[500px] flex-col items-center gap-3">
        <h2 className="mb-2 text-xl font-bold">{t("serviceModal.addTitle")}</h2>
        <RoundedInput
          type="text"
          placeholder={t("serviceModal.titlePlaceholder")}
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          className="max-w-full text-right"
        />
        <div className="flex w-full gap-3">
          <RoundedInput
            type="number"
            placeholder={t("serviceModal.originalPrice")}
            value={originalPrice}
            onChange={(e) => setOriginalPrice(e.target.value)}
            className="max-w-full text-right"
          />
          <RoundedInput
            type="number"
            placeholder={t("serviceModal.discountPrice")}
            value={discountPrice}
            onChange={(e) => setDiscountPrice(e.target.value)}
            className="max-w-full text-right"
          />
        </div>

        <div className="relative mt-2 flex h-[100px] w-[100px] items-center justify-center overflow-hidden rounded-full border border-neutral-950 dark:border-neutral-400">
          {serviceImage ? (
            <>
              <img
                src={
                  serviceImage.startsWith("data:")
                    ? serviceImage
                    : IMAGE_BASE_URL + serviceImage
                }
                alt=""
                className="h-full w-full object-cover"
              />
              <button
                type="button"
                onClick={removeImage}
                className="absolute right-0 top-0 p-2"
              >
                <Image
                  src="/images/icons/close-circle.svg"
                  width={25}
                  height={25}
                  alt=""
                />
              </button>
            </>
          ) : (
            <label
              htmlFor="serviceFileInput"
              className="flex h-full w-full cursor-pointer items-center justify-center"
            >
              <Image
                src="/images/icons/gallery-add.svg"
                width={40}
                height={40}
                alt=""
                className="dark:invert"
              />
            </label>
          )}
        </div>
        <input
          id="serviceFileInput"
          type="file"
          accept="image/*"
          className="hidden"
          onChange={selectImage}
        />

        <RoundedButton
          type="button"
          variant="primary"
          onClick={handleSubmit}
          className="mt-3 h-10 px-8"
        >
          {t("serviceModal.add")}
        </RoundedButton>
      </div>
    </Modal>
  );
};

export default AddServiceModal;
