import { type FC, useState } from "react";
import DefaulModal from "@/components/DefaulModal";
import Input from "@/components/Input";
import Textarea from "@/components/Textarea";
import Button from "@/components/Button";
import { useTranslation } from "react-i18next";
import { toast } from "react-toastify";
import { extractErrorMessage } from "@/config/func";
import { useOpenCashShift } from "../hooks/useCashShiftData";

type Props = {
  open: boolean;
  onClose: () => void;
};

const OpenCashShiftModal: FC<Props> = ({ open, onClose }) => {
  const { t } = useTranslation("global");
  const [openingAmount, setOpeningAmount] = useState("");
  const [notes, setNotes] = useState("");
  const [error, setError] = useState("");
  const openShift = useOpenCashShift();

  const handleClose = () => {
    setOpeningAmount("");
    setNotes("");
    setError("");
    onClose();
  };

  const handleSubmit = () => {
    const numericAmount = Number(openingAmount);

    if (Number.isNaN(numericAmount) || numericAmount < 0) {
      setError(t("cash_shift.opening_amount_required"));
      return;
    }

    openShift.mutate(
      {
        openingAmount: numericAmount,
        notes: notes.trim() || undefined,
      },
      {
        onSuccess: () => {
          toast.success(t("cash_shift.opened_success"));
          handleClose();
        },
        onError: (err) => {
          toast.error(extractErrorMessage(err));
        },
      }
    );
  };

  return (
    <DefaulModal
      open={open}
      close={handleClose}
      isHeader
      title_header={t("cash_shift.open_title")}
      width={480}
    >
      <div className="mt-6">
        <Input
          name="openingAmount"
          label={t("cash_shift.opening_amount")}
          placeholder={t("cash_shift.opening_amount_placeholder")}
          type="number"
          seprator
          value={openingAmount}
          onChange={(e) => {
            setOpeningAmount(e.target.value);
            setError("");
          }}
          error_text={error}
        />

        <div className="mt-4">
          <Textarea
            name="notes"
            label={t("cash_shift.notes")}
            placeholder={t("cash_shift.notes_placeholder")}
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            isNotRequired
          />
        </div>

        <div className="flex gap-3 mt-6">
          <Button
            label={t("cash_shift.cancel")}
            type="button"
            onClick={handleClose}
            className="bg-gray-100 text-gray-700"
          />
          <Button
            label={t("cash_shift.open_shift")}
            type="button"
            onClick={handleSubmit}
            isloading={openShift.isPending}
          />
        </div>
      </div>
    </DefaulModal>
  );
};

export default OpenCashShiftModal;
