import React, { useEffect, useState } from "react";
import "react-datepicker/dist/react-datepicker.css";
import "./billing.css";
import config from "../../config/config.json";
import { apiCall } from "../../_services/apiCall";
import Loader from "../loader/Loader";
import { Modal, ModalHeader } from "../../globalComponents/ui/Modal";
import { PrimaryButton, SecondaryButton, DangerButton } from "../../globalComponents/ui/Button";
import {
  SettingLayout,
  SettingsCard, SettingsSectionHeader, SettingsSectionTitle,
  SettingsModalBody, SettingsModalFooter,
  SettingsContent, SettingsTopBar, SettingsTopBarLeft,
  SettingsAccentBar, SettingsTopBarTitle, SettingsTopBarSub
} from "./SettingShell";

const Billing = ({ tab, userPermissionList }) => {
  const [authValue, setAuthValue] = useState(null);
  const [error, setError] = useState();
  const [currentPlan, setCurrentPlan] = useState("");
  const [updradePlanShow, setUpdradePlanShow] = useState(false);
  const [updradePrice, setUpdradePrice] = useState();
  const [items, setItems] = useState([]);
  const userId = JSON.parse(localStorage.getItem("user_temp_id"));
  const [showSkelton, setshowSkelton] = useState(false);
  const [deletePopup, setDeletePopup] = useState(false);

  const closeDeletePopup = () => setDeletePopup(false);

  useEffect(() => {
    const auth = JSON.parse(localStorage.getItem("currentUser"));
    setAuthValue(auth);
    getGlobalSubscriptionPlan();
  }, [tab]);

  const changeDateFormat = (dateString) => {
    const date = new Date(dateString);
    date.setDate(date.getDate() + 1);
    const day = date.getDate();
    const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    const month = months[date.getMonth()];
    const year = date.getFullYear();
    return `${day < 10 ? "0" + day : day}-${month}-${year}`;
  };

  const getGlobalSubscriptionPlan = async () => {
    setshowSkelton(true);
    const { isSuccess, data, error } = await apiCall(
      config.POSTLOGIN_API_URL_COMPANY + `getSubcriptionPlane`,
      {},
      { userId: userId },
      "GET"
    );
    setshowSkelton(false);
    if (isSuccess) {
      if (data?.data) {
        for (let i = 0; i < data.data.length; i++) {
          if (data.data[i].status === "PAYMENT_DONE") {
            setCurrentPlan(data.data[i].price);
            break;
          }
        }
      }
      setItems(data?.data || []);
    } else {
      setError(error);
    }
  };

  const paymentDone = async (id) => {
    const { isSuccess } = await apiCall(config.API_URL + `paymentDone`, {}, { orderId: id }, "POST");
    if (isSuccess) getGlobalSubscriptionPlan();
  };

  const cancelPlane = async () => {
    const { isSuccess } = await apiCall(config.POSTLOGIN_API_URL_COMPANY + `cancelPlan`, {}, {}, "POST");
    if (isSuccess) {
      closeDeletePopup();
      getGlobalSubscriptionPlan();
    }
  };

  const upgradePlanPaymentDone = async (id) => {
    const { isSuccess } = await apiCall(config.API_URL + `upgradePlanPaymentDone`, {}, { orderId: id }, "POST");
    if (isSuccess) getGlobalSubscriptionPlan();
  };

  const upgradePlan = async () => {
    const { isSuccess, data } = await apiCall(config.API_URL + `upgradePlan`, {}, "GET");
    if (isSuccess) {
      setUpdradePlanShow(false);
      const options = {
        key: "rzp_test_hCHVIASrXD6OsD",
        amount: "80",
        currency: "INR",
        name: "Acme Corp",
        description: "Test Transaction",
        order_id: data.data.orderId,
        handler: (response) => upgradePlanPaymentDone(response.razorpay_order_id),
        theme: { color: "#3399cc" },
      };
      const rzp1 = new window.Razorpay(options);
      rzp1.open();
    }
  };

  const paymentHandler = async (item) => {
    const { isSuccess, data } = await apiCall(config.API_URL + `generateOrderId`, {}, { plan_id: item.id }, "GET");
    if (isSuccess) {
      const options = {
        key: "rzp_test_hCHVIASrXD6OsD",
        amount: "80",
        currency: "INR",
        name: "Acme Corp",
        description: "Test Transaction",
        order_id: data.data.orderId,
        handler: (response) => paymentDone(response.razorpay_order_id),
        theme: { color: "#3399cc" },
      };
      const rzp1 = new window.Razorpay(options);
      rzp1.open();
    }
  };

  const upgradePlanPayment = (item) => {
    setUpdradePlanShow(true);
    setUpdradePrice(item?.price);
    setCurrentPlan(item?.id);
  };

  const specialCompanies = [338];
  const canViewPlan = userPermissionList.some(p => p.permissionCode === "VIEW_SUBSCRIPTION_PLAN" && p.checked);
  const canCancelPlan = userPermissionList.some(p => p.permissionCode === "CANCEL_PLAN" && p.checked);
  const canUpgradePlan = userPermissionList.some(p => p.permissionCode === "UPGRADE_PLAN" && p.checked);

  if (authValue && specialCompanies.includes(authValue.company_id)) {
    return (
      <SettingLayout
        title="Billing & Subscription"
        subtitle="Unlock unlimited features"
      >
        <SettingsContent>
          <SettingsCard style={{ padding: 40, textAlign: "center" }}>
            <div style={{ background: "#f0f9ff", border: "1px solid #bae6fd", borderRadius: 12, padding: "24px 32px", marginBottom: 32 }}>
              <h2 style={{ color: "#0369a1", fontSize: 20, fontWeight: 700, margin: 0 }}>
                Unlock unlimited features and take your experience to the next level!
              </h2>
            </div>
            <div style={{ maxWidth: 400, margin: "0 auto", textAlign: "left" }}>
              <h3 style={{ color: "#0f172a", fontSize: 16, fontWeight: 600, marginBottom: 20, paddingBottom: 8, borderBottom: "1px solid #f1f5f9" }}>
                Contact Information
              </h3>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12, padding: 12, background: "#f8fafc", borderRadius: 8 }}>
                  <i className="fas fa-user" style={{ color: "#3f88a5" }} />
                  <span style={{ fontSize: 14 }}><strong>Name:</strong> Sharique Zia</span>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 12, padding: 12, background: "#f8fafc", borderRadius: 8 }}>
                  <i className="fas fa-envelope" style={{ color: "#3f88a5" }} />
                  <span style={{ fontSize: 14 }}><strong>Email:</strong> sharique@riu.ai</span>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 12, padding: 12, background: "#f8fafc", borderRadius: 8 }}>
                  <i className="fas fa-phone" style={{ color: "#3f88a5" }} />
                  <span style={{ fontSize: 14 }}><strong>Contact:</strong> +91-9738757221</span>
                </div>
              </div>
            </div>
          </SettingsCard>
        </SettingsContent>
      </SettingLayout>
    );
  }

  return (
    <SettingLayout
      title="Billing & Subscription"
      subtitle="Manage your reporting plans and subscription"
      $wide
      rightContent={
        <>
          <SecondaryButton style={{ marginRight: 12 }}>Subscribe New Framework</SecondaryButton>
          <PrimaryButton>Upgrade</PrimaryButton>
        </>
      }
    >
      <SettingsContent>
        {showSkelton ? (
          <div style={{ padding: 60 }}><Loader /></div>
        ) : (
          <div style={{ display: "flex", gap: 24, flexWrap: "wrap", justifyContent: "center" }}>
            {canViewPlan && items.map((item, key) => (
              <div key={item.id} className="pricing-table turquoise" style={{ width: 360, margin: 0 }}>
                {item.price !== item.payment_amount && (
                  <div className="badge-overlay">
                    <span className="top-right badge">
                      {Math.round(((item.price - item.payment_amount) * 100) / item.price)}% OFF
                    </span>
                  </div>
                )}
                <div style={{ textAlign: "left", fontSize: "20px", fontWeight: "bold", color: "#11546f", marginBottom: 12 }}>{item.title}</div>
                <div className="d-flex align-items-baseline" style={{ gap: 8, marginBottom: 16 }}>
                  {item.price !== item.payment_amount && (
                    <div style={{ fontSize: 18, color: "#ef4444", textDecoration: "line-through", opacity: 0.7 }}>
                      ₹{Number(item.price).toLocaleString('en-IN')}
                    </div>
                  )}
                  <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
                    <span style={{ fontSize: 24, fontWeight: 700, color: "#11546f" }}>₹{Number(item.payment_amount).toLocaleString('en-IN')}</span>
                    <span style={{ fontSize: 14, color: "#64748b" }}>/ {item.renewal_type}</span>
                  </div>
                </div>

                <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 20 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, color: "#475569" }}>
                    <span>Financial Year</span><span style={{ fontWeight: 600 }}>{item.plan_data?.FINANCIAL_YEAR}</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, color: "#475569" }}>
                    <span>Users Included</span><span style={{ fontWeight: 600 }}>{item.plan_data?.NO_USERS}</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, color: "#475569" }}>
                    <span>Frameworks</span><span style={{ fontWeight: 600 }}>{item.plan_data?.NO_FRAMEWORK}</span>
                  </div>
                </div>

                <div className="pricing-features" style={{ textAlign: "left" }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: "#11546f", marginBottom: 8 }}>Included Features:</div>
                  <ul style={{ paddingLeft: 20, marginBottom: 20, fontSize: 13, color: "#64748b" }}>
                    {item.plan_data?.MAPPED_FRAMEWORK?.map((f) => <li key={f.id}>{f.title}</li>)}
                    {item.plan_data?.MAPPED_MENUS?.map((m) => <li key={m.id}>{m.title}</li>)}
                  </ul>
                </div>

                <div style={{ marginTop: "auto" }}>
                  {key === 0 && item.auto_renewal === "0" && item.status === "PAYMENT_DONE" && (
                    <div style={{ fontSize: 12, color: "#64748b", marginBottom: 12 }}>
                      Applicable from {changeDateFormat(item.valid_till)}
                    </div>
                  )}

                  {canCancelPlan && key !== 1 && item.auto_renewal === "1" && item.status === "PAYMENT_DONE" ? (
                    <DangerButton style={{ width: "100%" }} onClick={() => setDeletePopup(true)}>CANCEL PLAN</DangerButton>
                  ) : canUpgradePlan && currentPlan && item.price > currentPlan ? (
                    <PrimaryButton style={{ width: "100%" }} onClick={() => upgradePlanPayment(item)}>UPGRADE PLAN</PrimaryButton>
                  ) : currentPlan?.length === 0 && (item.is_invitable === 1 || item.is_invitable === 0) ? (
                    <PrimaryButton style={{ width: "100%" }} onClick={() => paymentHandler(item)}>GET STARTED</PrimaryButton>
                  ) : null}
                </div>
              </div>
            ))}
          </div>
        )}
      </SettingsContent>

      {/* Upgrade Modal */}
      <Modal show={updradePlanShow} onClose={() => setUpdradePlanShow(false)} maxWidth={400}>
        <ModalHeader icon="fas fa-arrow-circle-up" title="Upgrade Plan" />
        <SettingsModalBody>
          <p style={{ margin: 0, fontSize: 14 }}>You are about to upgrade your plan. Total amount payable: <strong>₹{updradePrice}</strong></p>
        </SettingsModalBody>
        <SettingsModalFooter>
          <SecondaryButton onClick={() => setUpdradePlanShow(false)}>Cancel</SecondaryButton>
          <PrimaryButton onClick={upgradePlan}>Proceed to Pay</PrimaryButton>
        </SettingsModalFooter>
      </Modal>

      {/* Delete Confirmation Modal */}
      <Modal show={deletePopup} onClose={closeDeletePopup} maxWidth={400}>
        <ModalHeader icon="fas fa-exclamation-triangle" title="Cancel Subscription" />
        <SettingsModalBody>
          <p style={{ margin: 0, fontSize: 14 }}>Are you certain you want to cancel your plan? This action will disable automated renewals.</p>
        </SettingsModalBody>
        <SettingsModalFooter>
          <SecondaryButton onClick={closeDeletePopup}>Keep Plan</SecondaryButton>
          <DangerButton onClick={cancelPlane}>Cancel Plan</DangerButton>
        </SettingsModalFooter>
      </Modal>
    </SettingLayout>
  );
};

export default Billing;