import { zodResolver } from "@hookform/resolvers/zod";
import Button from "../../components/Button/Button";
import { Grid } from "../../components/Grid/Grid";
import Textfield from "../../components/Textfeild/Textfeild";
import { useForm, Controller } from "react-hook-form";
import {
  zValidateBigNumber,
  zValidateNumber,
  zValidateNumberOptional,
  zValidateStringOptional,
} from "../../data/getFormTypeErrors";
import { z } from "zod";
import { useApiMutation } from "../../utils/useApiRequest";
import { useToast } from "../../hooks/useToast";
import { useModalStore } from "../../context/zustand-store/appStore";
import { getToastResponse } from "../../data/getToastResponse";
import Typography from "../../components/Typography/Typography";
import { useEffect } from "react";
import ansar from "../../assets/images/banks/ansar.png";
import ayandeh from "../../assets/images/banks/ayandeh.png";
import eghtesadNovin from "../../assets/images/banks/eghtesad-novin.png";
import keshavarzi from "../../assets/images/banks/keshavarzi.png";
import maskan from "../../assets/images/banks/maskan.png";
import mehriran from "../../assets/images/banks/mehriran.png";
import meli from "../../assets/images/banks/meli.png";
import mellat from "../../assets/images/banks/mellat.png";
import pasargad from "../../assets/images/banks/pasargad.png";
import saderat from "../../assets/images/banks/saderat.png";
import saman from "../../assets/images/banks/saman.png";
import sina from "../../assets/images/banks/sina.png";
import tejarat from "../../assets/images/banks/tejarat.png";
import toseeTavon from "../../assets/images/banks/tosee-tavon.png";

const schema = z.object({
  name: zValidateStringOptional("بانک"),
  card: zValidateNumberOptional("شماره کارت"),
  account: zValidateNumber("شماره حساب"),
  sheba: zValidateBigNumber("شماره شبا"),
});

type AddPageProps = {
  getData: () => void;
  item?: any;
  target?: string;
};

type FormValues = z.infer<typeof schema>;

const cardToBank: Record<string, string> = {
  "6037": "ملی",
  "5892": "رفاه",
  "6273": "انصار",
  "5022": "پاسارگاد",
  "6104": "ملت",
  "6219": "سامان",
  "6221": "پارسیان",
  "6274": "اقتصاد نوین",
  "6280": "مسکن",
  "6393": "سینا",
  "5029": "توسعه تعاون",
  "5859": "تجارت",
  "6392": "کشاورزی",
  "6278": "توسعه صادرات",
  "6063": "مهر ایران",
  "6362": "آینده",
  "": "نامشخص",
};

const bankToImage: Record<string, string> = {
  ملی: meli,
  انصار: ansar,
  پاسارگاد: pasargad,
  ملت: mellat,
  سامان: saman,
  "اقتصاد نوین": eghtesadNovin,
  مسکن: maskan,
  سینا: sina,
  "توسعه تعاون": toseeTavon,
  تجارت: tejarat,
  کشاورزی: keshavarzi,
  "توسعه صادرات": saderat,
  "مهر ایران": mehriran,
  آینده: ayandeh,
};

export const AddCard = ({ getData, item, target }: AddPageProps) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();
  const cardInfo = item?.bank_account?.[0] || {};

  const {
    control,
    handleSubmit,
    setValue,
    watch,
    getValues,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      name: cardInfo?.name || "",
      card: cardInfo?.card || "",
      account: cardInfo?.account || "",
      sheba: cardInfo?.sheba || "",
    },
  });

  const cardNumber = watch("card");

  useEffect(() => {
    if (!cardNumber) return;
    const foundBank =
      cardToBank[
        Object.keys(cardToBank).find((prefix) =>
          cardNumber.toString().startsWith(prefix)
        ) || ""
      ];
    if (foundBank) setValue("name", foundBank);
    else setValue("name", "");
  }, [cardNumber, setValue]);

  const mutation = useApiMutation({
    api: `/auth/api/v1/bank_account/${
      cardInfo?.name ? cardInfo?.id + "/" : ""
    }`,
    method: cardInfo?.name ? "put" : "post",
  });

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        name: data?.name || "نامشخص",
        card: data?.card ? data?.card : "",
        account: data?.account,
        sheba: data?.sheba,
        organization: item?.id,
        account_type: "ORG",
      });
      showToast(getToastResponse(item, "کارت"), "success");
      getData();
      closeModal();
    } catch (error: any) {
      if (error?.status === 403) {
        showToast("این کارت تکراری است!", "error");
      } else {
        showToast(
          error?.response?.data?.message || "خطا در ثبت اطلاعات!",
          "error"
        );
      }
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container column className="gap-2">
        <Typography sign="info" variant="caption">
          تعریف مشخصات بانکی برای {"‌"}
          {target}
        </Typography>

        <Controller
          name="card"
          control={control}
          render={({ field }) => {
            const bankName = getValues("name");
            const bankImage = bankName && bankToImage[bankName];
            return (
              <Textfield
                fullWidth
                placeholder="شماره کارت"
                value={field.value}
                onChange={field.onChange}
                error={!!errors.card}
                helperText={errors.card?.message}
                end={
                  bankImage ? (
                    <img
                      src={bankImage}
                      alt={bankName}
                      className="h-8 w-auto object-contain"
                    />
                  ) : (
                    bankName || "نامشخص"
                  )
                }
              />
            );
          }}
        />

        <Controller
          name="account"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="شماره حساب"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.account}
              helperText={errors.account?.message}
            />
          )}
        />

        <Controller
          name="sheba"
          control={control}
          render={({ field }) => (
            <Textfield
              fullWidth
              placeholder="شماره شبا"
              value={field.value}
              onChange={field.onChange}
              error={!!errors.sheba}
              helperText={errors.sheba?.message}
              end="IR"
            />
          )}
        />

        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
