import React, { useState, useEffect } from "react";
import styles from "./Checkout.module.scss";
import { useTranslation } from "react-i18next";
import {
  usePlaceOrderMutation,
  useGetOrderTimesQuery,
  useGetOrderPaymentsQuery,
} from "../../app/api/orderApi";
import { useGetLocationsQuery } from "../../app/api/locationApi";

const isPriceZero = (price) => !price || parseFloat(price) === 0;

const useDeviceType = () => {
  const [deviceType, setDeviceType] = useState("desktop");
  useEffect(() => {
    setDeviceType(
      /Mobi|Android/i.test(navigator.userAgent) ? "mobile" : "desktop",
    );
  }, []);
  return deviceType;
};

const Checkout = ({
  cartItems,
  shippingPrice,
  productIds,
  onBackToCart,
  onPlaceOrder,
}) => {
  const { t } = useTranslation();
  const [formData, setFormData] = useState({
    customer_name: "",
    customer_phone: "+993 ",
    customer_address: "",
    payment_type_id: "",
    notes: "",
    region: "",
  });

  const [selectedAddress, setSelectedAddress] = useState(null);
  const [placeOrder] = usePlaceOrderMutation();
  const { data: orderPayments = [] } = useGetOrderPaymentsQuery();
  const { data: locationsData } = useGetLocationsQuery();
  const deviceType = useDeviceType();

  // Sepetteki tüm ürünlerin fiyatı 0 mı?
  const allItemsZeroPrice = cartItems?.every((item) =>
    isPriceZero(item.product?.price_amount),
  );

  const handleInputChange = (e) => {
    const { name, value } = e.target;

    if (name === "customer_phone") {
      const prefix = "+993 ";
      if (value.length < prefix.length) return;

      const digits = value
        .substring(prefix.length)
        .replace(/\D/g, "")
        .substring(0, 8);
      let formatted = prefix + digits.substring(0, 2);
      if (digits.length > 2) formatted += " " + digits.substring(2);

      setFormData((prev) => ({ ...prev, [name]: formatted }));
    } else {
      setFormData((prev) => ({ ...prev, [name]: value }));
    }
  };

  const handleAddressSelect = (value) => {
    setSelectedAddress(value);
    const selectedLocation = locationsData?.data?.find((l) => l.name === value);
    setFormData((prev) => ({
      ...prev,
      address: value,
      region: selectedLocation?.region || "",
    }));
  };

  const handleClearAddress = () => {
    setSelectedAddress(null);
    setFormData((prev) => ({ ...prev, address: "" }));
  };

  const handleFocus = (e) =>
    e.target.scrollIntoView({ behavior: "smooth", block: "center" });

  const formatPhoneNumber = (phone) =>
    phone.replace(/^\+993\s*/, "").replace(/\s+/g, "");

  const getOrderData = () => {
    if (
      !formData.customer_name ||
      !formData.customer_phone ||
      !formData.customer_address ||
      !formData.payment_type_id
    ) {
      alert("Please fill in all required fields");
      return null;
    }

    const currentDate = new Date().toISOString().split("T")[0];

    return {
      customer_name: formData.customer_name,
      customer_phone: formatPhoneNumber(formData.customer_phone),
      customer_address: formData.customer_address,
      shipping_method: "standard",
      payment_type_id: formData.payment_type_id,
      delivery_time: "12:00-14:00",
      delivery_at: currentDate,
      region: formData.region || "",
      notes: formData.notes || "",
      shipping_price: shippingPrice,
      product_ids: productIds,
    };
  };

  const handlePlaceOrder = async () => {
    const orderDetails = getOrderData();
    if (!orderDetails) return false;

    try {
      await placeOrder(orderDetails).unwrap();
      window.location.href = "/orders";
      return true;
    } catch (error) {
      const isHtmlResponse =
        error.data &&
        typeof error.data === "string" &&
        error.data.includes("<!doctype html>");

      alert(
        isHtmlResponse
          ? "There was a problem with the server. Please try again later."
          : "Failed to place order. Please check your information and try again.",
      );
      return false;
    }
  };

  useEffect(() => {
    if (onPlaceOrder) onPlaceOrder(handlePlaceOrder);
  }, [formData, shippingPrice, productIds]);

  return (
    <div className={styles.checkoutContainer}>
      {/* <h2>{t("cart.basket")} ({cartItems?.length || 0})</h2> */}
      <div className={styles.formSection}>
        <div className={styles.paymentOptions}>
          <h3>{t("checkout.paymentMethod")}:</h3>
          {orderPayments.map((payment) => (
            <div className={styles.option} key={payment.id}>
              <input
                type="radio"
                id={`payment${payment.id}`}
                name="payment_type_id"
                value={payment.id}
                checked={formData.payment_type_id === String(payment.id)}
                onChange={handleInputChange}
              />
              <label
                htmlFor={`payment${payment.id}`}
                className={styles.customRadio}
              />
              <div
                className={styles.text}
                onClick={() =>
                  setFormData((prev) => ({
                    ...prev,
                    payment_type_id: String(payment.id),
                  }))
                }
              >
                <span className={styles.optionTitle}>{payment.name}</span>
                <span className={styles.optionDesc}>
                  {payment.name === "Nagt"
                    ? t("checkout.payment_in_cash_upon_delivery_of_the_order")
                    : t("checkout.payment_by_card")}
                </span>
              </div>
            </div>
          ))}
        </div>

        <div className={styles.deliveryForm}>
          <h3>{t("checkout.address")}:</h3>
          <div className={styles.formRow}>
            <div className={styles.formGroup}>
              <label>{t("checkout.fullName")}*</label>
              <input
                type="text"
                name="customer_name"
                value={formData.customer_name}
                onChange={handleInputChange}
                required
                onFocus={handleFocus}
              />
            </div>
            <div className={styles.formGroup}>
              <label>{t("checkout.telephone")}*</label>
              <input
                type="tel"
                name="customer_phone"
                value={formData.customer_phone}
                onChange={handleInputChange}
                placeholder="+993 61 097651"
                required
                onFocus={handleFocus}
              />
            </div>
          </div>
          <div className={styles.formRow}>
            <div className={styles.formGroup}>
              <label>{t("checkout.moreAboutYourAddress")}*</label>
              <input
                type="text"
                name="customer_address"
                value={formData.customer_address}
                onChange={handleInputChange}
                required
                onFocus={handleFocus}
              />
            </div>
            <div className={styles.formGroup}>
              <label>{t("checkout.note")}</label>
              <input
                type="text"
                name="notes"
                value={formData.notes}
                onChange={handleInputChange}
                onFocus={handleFocus}
              />
            </div>
          </div>
        </div>

        <div className={styles.deliveryInfo}>
          <ul>
            <li>
              {t(
                "checkout.Delivery_is_carried_out_in_the_cities_of_Ashgabat_Buzmein_and_Anau",
              )}
            </li>
            <li>
              {t(
                "checkout.After_you_place_an_order_on_the_website_the_operator_will_call_you_to_confirm_the_order_for_regular_customers_confirmation_is_carried_out_automatically_at_their_request",
              )}
            </li>
            <li>
              {t(
                "checkout.Payment_is_made_after_you_check_and_accept_the_order_The_amount_of_your_payment_is_indicated_on_the_delivery_persons_payment_document_Payment_is_made_in_cash_and_by_card_in_national_currency_Accepted_and_paid_goods_are_not_subject_to_return",
              )}
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
};

export default Checkout;
