/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useState } from "react";
import { X, CircleFadingPlus } from "lucide-react";
import Button from "../Button";
import { createInvestmentPlan } from "../../lib/api/api";

  export interface InvestmentPlan {
    title: string;
    description: string;
    amount: string;
    duration: string;
    interest: string;
    total: string;
  }
  
interface InvestmentPlanModalProps {
  isOpen: boolean;
  onClose: () => void;
  plan: InvestmentPlan | null;
}

const InvestmentPlanModal = ({ isOpen, onClose, plan }: InvestmentPlanModalProps) => {
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [success, isSuccess] = useState(false);
  const [error, setError] = useState("");

  if (!isOpen || !plan) return null;

  const isTechnicalError = (msg: string) =>
    typeof msg === "string" &&
    (
      msg.includes("Exception") ||
      msg.includes("server") ||
      msg.includes("internal") ||
      msg.includes("retrieving the wallet")
    );

  const getUserFriendlyError = (msg: string) =>
    isTechnicalError(msg)
      ? "Something went wrong. Please try again later."
      : msg || "An error occurred. Please try again.";

  const handleCreate = async () => {
    setLoading(true);
    try {
      const payload = {
        type: "fixed",
        plan: plan.title,
        amount: parseInt(plan.amount.replace(/[₦,]/g, "")),
        duration: parseInt(plan.duration),
      };

      const response = await createInvestmentPlan(payload);

      if (response?.data?.data?.isSuccess) {
        isSuccess(true);
        setModalVisible(true);
      } else {
        const errorMessage = getUserFriendlyError(response?.data?.data?.errors?.[0]?.message);
        setError(errorMessage);
        isSuccess(false);
        setModalVisible(true);
      }
    } catch (err: any) {
      let errorMessage = "An error occurred. Please try again";
      if (err.response?.data?.errors?.length > 0) {
        errorMessage = getUserFriendlyError(err.response.data.errors[0].message);
      } else if (err.response?.data?.error) {
        errorMessage = getUserFriendlyError(err.response.data.error);
      } else if (err.response?.data?.message) {
        errorMessage = getUserFriendlyError(err.response.data.message);
      }
      setError(errorMessage);
      isSuccess(false);
      setModalVisible(true);
    } finally {
      setLoading(false);
    }
  };

  const monthlyAmount = plan.amount.replace(/[₦,]/g, "");

  return (
    <div className="fixed inset-0 bg-black bg-opacity-30 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-3xl shadow-2xl max-w-lg w-full p-8 relative">
        {/* Close */}
        <button
          onClick={onClose}
          className="absolute top-6 right-6 text-gray-400 hover:text-gray-600 transition"
        >
          <X size={24} />
        </button>

        {/* Title */}
        <h2 className="text-2xl font-semibold text-gray-900 text-center mb-8">
          {plan.title} Plan
        </h2>

        {/* Details */}
        <div className="space-y-6 mb-8">
          <div className="flex justify-between py-3 border-b border-gray-100">
            <span className="text-gray-700">Interest</span>
            <span className="text-gray-900 font-medium">{plan.interest}</span>
          </div>
          <div className="flex justify-between py-3 border-b border-gray-100">
            <span className="text-gray-700">Fixed Amount</span>
            <span className="text-gray-900 font-medium">₦{monthlyAmount}/Month</span>
          </div>
          <div className="flex justify-between py-3 border-b border-gray-100">
            <span className="text-gray-700">Duration</span>
            <span className="text-gray-900 font-medium">{plan.duration}</span>
          </div>
          <div className="flex justify-between py-3 border-b border-gray-100">
            <span className="text-gray-700">Calculated Returns</span>
            <span className="text-gray-900 font-semibold">{plan.total}</span>
          </div>
        </div>

        {/* Button */}
        <div className="flex justify-center gap-6">
          <Button
            type="button"
            border="border border-white"
            width="40%"
            onClick={handleCreate}
            disabled={loading}
          >
            <div className="flex items-center justify-center gap-2">
              {loading ? (
                <span>Loading...</span>
              ) : (
                <>
                  <CircleFadingPlus size={16} strokeWidth={3} />
                  <h4 className="text-xs sm:text-sm md:text-base">Continue</h4>
                </>
              )}
            </div>
          </Button>
        </div>

        {/* Response Modal */}
        {modalVisible && (
          <div className="fixed inset-0 flex items-center justify-center bg-black/40 z-50">
            <div className="bg-white rounded-xl p-6 text-center max-w-sm">
              <h3 className={`text-lg font-bold mb-3 ${success ? "text-green-600" : "text-red-600"}`}>
                {success ? "Success" : "Error!"}
              </h3>
              <p className="text-gray-700 mb-4">
                {error || "Investment Plan created successfully!"}
              </p>
              <button
                onClick={() => {
                  setModalVisible(false);
                  onClose();
                }}
                className={`px-6 py-2 rounded-lg text-white ${
                  success ? "bg-green-600 hover:bg-green-700" : "bg-red-600 hover:bg-red-700"
                }`}
              >
                {success ? "Continue" : "Try Again"}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default InvestmentPlanModal;
