import { Button, Form } from "antd";
import { ProBottomSheet } from "components/ProBottomSheet/ProBottomSheet.tsx";
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";

import {
  selectCart,
  selectGrandTotal,
  updateSplitBillAmount,
} from "features/order/orderSlice";
import { useAppDispatch, useAppSelector } from "redux/hooks";
import ProText from "components/ProText";
import ArabicPrice from "components/ArabicPrice";
import styles from "./SplitBill.module.css";
import { ProInputNumber } from "components/Inputs/ProInputNumber";

interface SplitBillChoiceBottomSheetProps {
  isOpen: boolean;
  onClose: () => void;
  onRemoveSplitWay?: () => void;
}

export function CustomAmountChoiceBottomSheet({
  isOpen,
  onClose,
  onRemoveSplitWay,
}: SplitBillChoiceBottomSheetProps) {
  const { t } = useTranslation();
  const dispatch = useAppDispatch();
  const { splitBillAmount, fee } = useAppSelector(selectCart);
  const grandTotal = useAppSelector(selectGrandTotal);
  const [amount, setAmount] = useState<string>(
    splitBillAmount > 0 ? splitBillAmount.toString() : "",
  );
  useEffect(() => {
    if (isOpen && splitBillAmount > 0) {
      setAmount(splitBillAmount.toString());
    }
  }, [isOpen, splitBillAmount]);

  const handleSave = () => {
    const numAmount = parseFloat(amount) || 0;
    dispatch(updateSplitBillAmount(numAmount));
    onClose();
  };

  const handleRemoveSplitWay = () => {
    setAmount("");
    dispatch(updateSplitBillAmount(0));
    onRemoveSplitWay?.();
    onClose();
  };

  // Calculate preview values using local amount state for real-time updates
  const currentAmount = parseFloat(amount) || 0;
  // Original total bill (before split) = grandTotal + splitBillAmount (from Redux)
  const originalTotalBill = grandTotal + splitBillAmount;
  // Preview: total bill stays the same, remaining = original - current amount being typed
  const previewTotalBill = originalTotalBill;
  const previewRemaining = originalTotalBill - currentAmount;
  const taxesChargesStyle = {
    fontWeight: 400,
    fontStyle: "Regular",
    fontSize: 12,
    lineHeight: "140%",
    letterSpacing: "0%",
    color: "#777580",
  };

  return (
    <ProBottomSheet
      isOpen={isOpen}
      onClose={onClose}
      title={t("splitBill.customAmount")}
      showCloseButton={true}
      initialSnap={1}
      height={425}
      snapPoints={[425]}
      contentStyle={{
        padding: 0,
      }}
    >
      <div
        style={{
          padding: "20px",
          display: "flex",
          flexDirection: "column",
          gap: 20,
        }}
      >
        <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
          <ProText
            style={{
              fontWeight: 400,
              fontStyle: "Regular",
              fontSize: 16,
              lineHeight: "140%",
              letterSpacing: "0%",
            }}
          >
            {t("splitBill.howMuchWouldYouLikeToPay")}
          </ProText>
          <Form.Item name="amount">
            <ProInputNumber
              value={amount}
              onChange={(value) => {
                setAmount(value?.toString() || "");
                dispatch(updateSplitBillAmount(Number(value) || 0));
              }}
              placeholder={t("splitBill.amount")}
              max={(grandTotal + splitBillAmount).toString()}
            />
          </Form.Item>
        </div>
      </div>

      <div
        style={{
          display: "flex",
          flexDirection: "column",
          backgroundColor: "var(--background)",
          padding: "20px",
          opacity: 1,
          gap: 8,
          borderTopLeftRadius: 24,
          borderTopRightRadius: 24,
          paddingTop: 12,
          paddingRight: 24,
          paddingBottom: 24,
          paddingLeft: 24,
        }}
      >
        <div className={styles.summaryRow}>
          <ProText style={taxesChargesStyle}>
            {t("splitBill.totalBill")}
          </ProText>
          <ArabicPrice price={previewTotalBill} textStyle={taxesChargesStyle} />
        </div>
        <div className={styles.summaryRow}>
          <ProText style={taxesChargesStyle}>
            {t("splitBill.serviceFee")}
          </ProText>
          <ArabicPrice price={fee} textStyle={taxesChargesStyle} />
        </div>
        <div className={styles.summaryRow}>
          <ProText
            style={{
              fontWeight: 400,
              fontStyle: "Regular",
              fontSize: 14,
              lineHeight: "140%",
              letterSpacing: "0%",
            }}
          >
            {t("splitBill.remainingToPay")}
          </ProText>
          <ArabicPrice
            price={Math.max(0, previewRemaining)}
            textStyle={taxesChargesStyle}
          />
        </div>
        <ProText style={taxesChargesStyle}>
          {t("splitBill.includesAllOfTaxesCharges")}
        </ProText>
      </div>

      <div
        style={{
          display: "flex",
          gap: 12,
          margin: 20,
        }}
      >
        <Button
          style={{
            flex: 1,
            backgroundColor: "#FEEDED",
            color: "#DD4143",
            boxShadow: "none",
            border: "none",
            height: 48,
          }}
          onClick={handleRemoveSplitWay}
        >
          {t("splitBill.cancelSplit")}
        </Button>
        <Button
          type="primary"
          style={{
            flex: 1,
            boxShadow: "none",
            height: 48,
          }}
          onClick={handleSave}
          disabled={!amount || parseFloat(amount) <= 0}
        >
          {t("splitBill.confirm")}
        </Button>
      </div>
    </ProBottomSheet>
  );
}
