import React, { useState, useEffect, useContext } from "react";
import { GlobalContext } from "../context/Provider";
import henceforthApi from "../utils/henceforthApi";
import Swal from "sweetalert2";
import { toast } from "react-toastify";

interface CountrySetting {
  country_code: string;
  referral_amount: number | "";
  minimum_withdraw_amount: number | "";
}

interface SettingsData {
  admin_commission_percentage?: number | "";
  customer_without_referral_discount?: number | "";
  referral_person_first_ride_discount?: number | "";
  country_settings?: CountrySetting[];
  is_referral_coupon_credit_disable?: boolean;
}

const COUNTRY_LABELS: Record<string, string> = {
  US: "🇺🇸 United States (USD)",
  CA: "🇨🇦 Canada (CAD)",
  NG: "🇳🇬 Nigeria (NGN)",
};

const DEFAULT_COUNTRY_SETTINGS: CountrySetting[] = [
  { country_code: "US", referral_amount: 10, minimum_withdraw_amount: 50 },
  { country_code: "CA", referral_amount: 10, minimum_withdraw_amount: 50 },
  { country_code: "NG", referral_amount: 10, minimum_withdraw_amount: 50 },
];

const Settings = () => {
  const { authState, setLoading } = useContext(GlobalContext);
  if (authState.access_token) {
    henceforthApi.setToken(authState.access_token);
  }

  const [settings, setSettings] = useState<SettingsData>({});
  const [formData, setFormData] = useState<SettingsData>({
    admin_commission_percentage: "",
    customer_without_referral_discount: "",
    referral_person_first_ride_discount: "",
    country_settings: DEFAULT_COUNTRY_SETTINGS,
    is_referral_coupon_credit_disable: false,
  });
  const [referralLoading, setReferralLoading] = useState(false);

  useEffect(() => {
    fetchSettings();
  }, []);

  const fetchSettings = async () => {
    try {
      setLoading(true);
      const res = await henceforthApi.Settings.getSettings();
      const settingsData: SettingsData = res.data?.settings || {};
      setSettings(settingsData);

      // Merge fetched country_settings with defaults (ensure all 3 countries present)
      const fetchedCountrySettings: CountrySetting[] = settingsData.country_settings || [];
      const mergedCountrySettings = DEFAULT_COUNTRY_SETTINGS.map((def) => {
        const found = fetchedCountrySettings.find((c) => c.country_code === def.country_code);
        return found ? { ...def, ...found } : def;
      });

      setFormData({
        admin_commission_percentage: settingsData.admin_commission_percentage ?? "",
        customer_without_referral_discount: settingsData.customer_without_referral_discount ?? "",
        referral_person_first_ride_discount: settingsData.referral_person_first_ride_discount ?? "",
        country_settings: mergedCountrySettings,
        is_referral_coupon_credit_disable: settingsData.is_referral_coupon_credit_disable ?? false,
      });
      setLoading(false);
    } catch (error: any) {
      setLoading(false);
      Swal.fire({
        title: "Error!",
        text: error.response?.body?.error_description || "Failed to fetch settings",
        icon: "error",
        confirmButtonText: "OK",
      });
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    // Keep empty string when input is cleared, otherwise parse as number
    const numValue = value === "" ? "" : parseFloat(value);
    setFormData((prev) => ({ ...prev, [name]: numValue }));
  };

  const handleCountryChange = (
    country_code: string,
    field: "referral_amount" | "minimum_withdraw_amount",
    value: string
  ) => {
    // Keep empty string when input is cleared, otherwise parse as number
    const numValue = value === "" ? "" : parseFloat(value);
    setFormData((prev) => ({
      ...prev,
      country_settings: (prev.country_settings || DEFAULT_COUNTRY_SETTINGS).map((cs) =>
        cs.country_code === country_code ? { ...cs, [field]: numValue } : cs
      ),
    }));
  };

  const validateForm = (): string | null => {
    const { admin_commission_percentage, customer_without_referral_discount, referral_person_first_ride_discount, country_settings } = formData;

    const currentAdminCommission = Number(admin_commission_percentage === "" ? settings.admin_commission_percentage : admin_commission_percentage) || 15;
    const currentCustomerDiscount = Number(customer_without_referral_discount === "" ? settings.customer_without_referral_discount : customer_without_referral_discount) || 10;
    const currentReferralDiscount = Number(referral_person_first_ride_discount === "" ? settings.referral_person_first_ride_discount : referral_person_first_ride_discount) || 15;

    if (admin_commission_percentage !== undefined && admin_commission_percentage !== "") {
      const value = Number(admin_commission_percentage);
      if (isNaN(value) || value < 0 || value > 100)
        return "Admin commission percentage must be between 0 and 100";
      if (value < currentCustomerDiscount)
        return `Admin commission (${value}%) cannot be less than customer discount (${currentCustomerDiscount}%)`;
      if (value < currentReferralDiscount)
        return `Admin commission (${value}%) cannot be less than referral discount (${currentReferralDiscount}%)`;
    }

    if (customer_without_referral_discount !== undefined && customer_without_referral_discount !== "") {
      const value = Number(customer_without_referral_discount);
      if (isNaN(value) || value < 0 || value > 100)
        return "Customer without referral discount must be between 0 and 100";
      if (value > currentAdminCommission)
        return `Customer discount (${value}%) cannot exceed admin commission (${currentAdminCommission}%)`;
    }

    if (referral_person_first_ride_discount !== undefined && referral_person_first_ride_discount !== "") {
      const value = Number(referral_person_first_ride_discount);
      if (isNaN(value) || value < 0 || value > 100)
        return "Referral person first ride discount must be between 0 and 100";
      if (value > currentAdminCommission)
        return `Referral discount (${value}%) cannot exceed admin commission (${currentAdminCommission}%)`;
    }

    for (const cs of country_settings || []) {
      const referralValue = cs.referral_amount === "" ? 0 : Number(cs.referral_amount);
      const withdrawValue = cs.minimum_withdraw_amount === "" ? 0 : Number(cs.minimum_withdraw_amount);
      
      if (isNaN(referralValue) || referralValue < 0 || referralValue > 100)
        return `Referral percentage for ${cs.country_code} must be between 0 and 100`;
      if (isNaN(withdrawValue) || withdrawValue < 0)
        return `Minimum withdraw amount for ${cs.country_code} must be a positive number`;
      
      // New validation: referral percentage + customer discount cannot exceed admin commission
      const totalWithCustomerDiscount = referralValue + currentCustomerDiscount;
      if (totalWithCustomerDiscount > currentAdminCommission) {
        
        return `Referral percentage (${referralValue}%) + Customer discount (${currentCustomerDiscount}%) = ${totalWithCustomerDiscount}% cannot exceed Admin commission (${currentAdminCommission}%) for ${cs.country_code}`;
      }
      
      // New validation: referral percentage + referral discount cannot exceed admin commission
      const totalWithReferralDiscount = referralValue + currentReferralDiscount;
      if (totalWithReferralDiscount > currentAdminCommission) {
        return `Referral percentage (${referralValue}%) + Referral discount (${currentReferralDiscount}%) = ${totalWithReferralDiscount}% cannot exceed Admin commission (${currentAdminCommission}%) for ${cs.country_code}`;
      }
    }

    return null;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const validationError = validateForm();
    if (validationError) return toast.error(validationError, { autoClose: 7000 });

    try {
      setLoading(true);
      const updateData: SettingsData = {};

      if (formData.admin_commission_percentage !== undefined && formData.admin_commission_percentage !== settings.admin_commission_percentage)
        updateData.admin_commission_percentage = formData.admin_commission_percentage;
      if (formData.customer_without_referral_discount !== undefined && formData.customer_without_referral_discount !== settings.customer_without_referral_discount)
        updateData.customer_without_referral_discount = formData.customer_without_referral_discount;
      if (formData.referral_person_first_ride_discount !== undefined && formData.referral_person_first_ride_discount !== settings.referral_person_first_ride_discount)
        updateData.referral_person_first_ride_discount = formData.referral_person_first_ride_discount;

      // Always send country_settings (they are always editable)
      updateData.country_settings = formData.country_settings;

      if (Object.keys(updateData).length === 0) {
        setLoading(false);
        return toast.info("No changes to update", { autoClose: 3000 });
      }

      await henceforthApi.Settings.updateSettings(updateData);
      setLoading(false);

      Swal.fire({
        title: "Success!",
        text: "Settings updated successfully",
        icon: "success",
        confirmButtonText: "OK",
      });

      fetchSettings();
    } catch (error: any) {
      setLoading(false);
      Swal.fire({
        title: "Error!",
        text: error.response?.body?.error_description || "Failed to update settings",
        icon: "error",
        confirmButtonText: "OK",
      });
    }
  };

  const handleReferralToggle = async () => {
    try {
      setReferralLoading(true);
      const newStatus = !formData.is_referral_coupon_credit_disable;
      
      await henceforthApi.Settings.update_all_users_referral_coupon_settings({
        is_referral_coupon_credit_disable: newStatus
      });
      
      setFormData(prev => ({
        ...prev,
        is_referral_coupon_credit_disable: newStatus
      }));
      
      setReferralLoading(false);
      
      Swal.fire({
        title: "Success!",
        text: `Referral feature ${newStatus ? "disabled" : "enabled"} successfully`,
        icon: "success",
        confirmButtonText: "OK",
      });
      
      fetchSettings();
    } catch (error: any) {
      setReferralLoading(false);
      Swal.fire({
        title: "Error!",
        text: error.response?.body?.error_description || "Failed to update referral settings",
        icon: "error",
        confirmButtonText: "OK",
      });
    }
  };

  return (
    <div className="row animated fadeInRight">
      <div className="col-md-12">
        <div className="ibox">
          <div className="ibox-title">Settings</div>
          <div className="ibox-content">
            <form onSubmit={handleSubmit}>

              {/* ── Commission & Discount Settings ── */}
              <h6 className="fw-bold text-uppercase text-muted mb-3" style={{ letterSpacing: '0.05em' }}>
                Commission &amp; Discount
              </h6>

              <div className="form-group mb-3">
                <label className="mb-2">
                  Admin Commission Percentage (%)
                  <span className="text-danger">*</span>
                </label>
                <input
                  type="number"
                  name="admin_commission_percentage"
                  className="form-control text-dark no-spinner"
                  value={formData.admin_commission_percentage === "" ? "" : formData.admin_commission_percentage}
                  onChange={handleChange}
                  min="0"
                  max="100"
                  step="0.01"
                  required
                />
                <small className="form-text text-muted">
                  Must be between 0 and 100, and cannot be less than customer or referral discounts
                </small>
              </div>

              <div className="form-group mb-3">
                <label className="mb-2">
                  Discount given to passengers' first ride without promo code (%)
                  <span className="text-danger">*</span>
                </label>
                <input
                  type="number"
                  name="customer_without_referral_discount"
                  className="form-control text-dark no-spinner"
                  value={formData.customer_without_referral_discount === "" ? "" : formData.customer_without_referral_discount}
                  onChange={handleChange}
                  min="0"
                  max="100"
                  step="0.01"
                  required
                />
                <small className="form-text text-muted">
                  Must be between 0 and 100, and cannot exceed admin commission percentage
                </small>
              </div>

              <div className="form-group mb-4">
                <label className="mb-2">
                  Discount given to passengers' first ride with promo code (%)
                  <span className="text-danger">*</span>
                </label>
                <input
                  type="number"
                  name="referral_person_first_ride_discount"
                  className="form-control text-dark no-spinner"
                  value={formData.referral_person_first_ride_discount === "" ? "" : formData.referral_person_first_ride_discount}
                  onChange={handleChange}
                  min="0"
                  max="100"
                  step="0.01"
                  required
                />
                <small className="form-text text-muted">
                  Must be between 0 and 100, and cannot exceed admin commission percentage
                </small>
              </div>

              <hr className="my-4" />

              {/* ── Referral Feature Toggle ── */}
              <h6 className="fw-bold text-uppercase text-muted mb-3" style={{ letterSpacing: '0.05em' }}>
                Referral Feature Control
              </h6>

              <div className="form-group mb-4">
                <div className="d-flex align-items-center justify-content-between p-3 border rounded" style={{ background: '#f8f9fa' }}>
                  <div>
                    <h6 className="mb-1">Referral Coupon Feature</h6>
                    <small className="text-muted">
                      {formData.is_referral_coupon_credit_disable 
                        ? "Referral coupons are currently DISABLED for all users" 
                        : "Referral coupons are currently ENABLED for all users"}
                    </small>
                  </div>
                  <button
                    type="button"
                    className={`btn ${formData.is_referral_coupon_credit_disable ? 'btn-success' : 'btn-danger'} btn-sm`}
                    onClick={handleReferralToggle}
                    disabled={referralLoading}
                  >
                    {referralLoading ? (
                      <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                    ) : null}
                    {formData.is_referral_coupon_credit_disable ? "Enable Referral" : "Disable Referral"}
                  </button>
                </div>
              </div>

              <hr className="my-4" />

              {/* ── Per-Country Settings ── */}
              <h6 className="fw-bold text-uppercase text-muted mb-3" style={{ letterSpacing: '0.05em' }}>
                Country-Based Referral &amp; Withdrawal Settings
              </h6>

              <div className="row g-3 mb-4">
                {(formData.country_settings || DEFAULT_COUNTRY_SETTINGS).map((cs) => (
                  <div className="col-12 col-md-4" key={cs.country_code}>
                    <div className="border rounded p-3 h-100" style={{ background: '#f8f9fa' }}>
                      <h6 className="fw-bold mb-3">{COUNTRY_LABELS[cs.country_code] || cs.country_code}</h6>

                      <div className="mb-3">
                        <label className="form-label mb-1">
                          Referral Percentage (%)
                          <span className="text-danger">*</span>
                        </label>
                        <input
                          type="number"
                          className="form-control text-dark no-spinner"
                          value={cs.referral_amount === "" ? "" : cs.referral_amount}
                          onChange={(e) => handleCountryChange(cs.country_code, "referral_amount", e.target.value)}
                          min="0"
                          max="100"
                          step="0.01"
                          required
                        />
                        <small className="form-text text-muted">Percentage credited as referral reward</small>
                      </div>

                      <div>
                        <label className="form-label mb-1">
                          Minimum Withdraw Amount
                          <span className="text-danger">*</span>
                        </label>
                        <input
                          type="number"
                          className="form-control text-dark no-spinner"
                          value={cs.minimum_withdraw_amount === "" ? "" : cs.minimum_withdraw_amount}
                          onChange={(e) => handleCountryChange(cs.country_code, "minimum_withdraw_amount", e.target.value)}
                          min="0"
                          step="0.01"
                          required
                        />
                        <small className="form-text text-muted">Minimum balance required to withdraw</small>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              <div className="form-group">
                <button type="submit" className="btn dashboard-button btn-color">
                  Update Settings
                </button>
              </div>

            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Settings;
