"use client";

import { useEffect, useState } from "react";
import InputItem from "@/app/Components/FormItems";
import { Tabs } from "antd";
import dayjs from "dayjs";
import ct from "countries-and-timezones";
import { errorMessage, successMessage } from "@/app/utils/alertMessages";
import { Loader } from "@/app/Components/Loader";
import { AlertMessage } from "@/app/Components/AlertMessage";
import { validateAndAlert } from "@/app/utils/form";
import { useSiteContext } from "@/app/Context/SiteContext";
import { useCheckPermission } from "@/app/utils/auth/Privilege";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import CompanyBanks from "../../CompanyBanks";
import { allCurrencies } from "@/app/utils/allCurrencies";
import EmailSettings from "./Email.";
import ThemeSelector from "../../ThemeSelector";

import { useQuery, useQueryClient } from "@tanstack/react-query";
import TaxBuilder from "../../TaxBuilder";
import GoogleIcon from "../../GoogleIcon";
import BackupRestore from "./BackupRestore";
import PhotoUpload from "@/app/Components/PhotoUpload";

const fetcher = (url) =>
  fetch(url, {}).then((res) => {
    if (!res.ok) throw new Error("Unauthorized or error fetching data");
    return res.json();
  });

export default function BrandSettings({ editPermission }) {
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();

  // const { data, error, isLoading } = useSWR(`/api/brand_settings`, fetcher);

  const queryClient = useQueryClient();

  const {
    data,
    isPending: isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ["brand_settings"],
    queryFn: () => fetcher("/api/brand_settings"),
  });

  const {
    data: emailData,
    isPending: isEmailLoading,
    error: emailError,
    refetch: refetchEmail,
  } = useQuery({
    queryKey: ["email_settings"],
    queryFn: () => fetcher("/api/email_settings"),
  });

  const [form, setForm] = useState(null);
  const [pendingUploads, setPendingUploads] = useState({});

  const { setFormValidation, currentSession } = useSiteContext();

  const [timeZones, setTimeZones] = useState([]);

  const [loadingUploads, setLoadingUploads] = useState(false);
  const [emailForm, setEmailForm] = useState({});
  const [emailSaving, setEmailSaving] = useState(false);
  const [testEmail, setTestEmail] = useState("");
  const [testEmailLoading, setTestEmailLoading] = useState(false);

  const checkPermission = useCheckPermission();

  const getThousandSeparator = [
    // STANDARD SEPARATORS
    {
      label: "Comma (1,000,000)",
      value: "comma",
    },
    {
      label: "Period (1.000.000)",
      value: "period",
    },
    {
      label: "Space (1 000 000)",
      value: "space",
    },
    {
      label: "None (1000000)",
      value: "none",
    },

    // REGIONAL EXAMPLES
    {
      label: "US Style (1,000,000.00)",
      value: "us",
    },
    {
      label: "EU Style (1.000.000,00)",
      value: "euro",
    },
    {
      label: "Indian Style (10,00,000)",
      value: "indian",
    },

    // CURRENCY-SPECIFIC
    {
      label: "AED Format (1,000,000.00)",
      value: "aed",
    },
    {
      label: "JPY Format (1,000,000)",
      value: "jpy",
    },
  ];

  const getDecimalPrecision = [
    { label: "AED 100 (No decimals)", value: "No decimals" },
    { label: "AED 100.00 (Standard 2 decimals)", value: "2 decimals" },
    { label: "AED 100.000 (3 decimals)", value: "3 decimals" },
  ];

  const getCurrencyFormats = [
    {
      label: "AED 100 (Symbol before)",
      value: "before",
    },
    {
      label: "100 AED (Symbol after)",
      value: "after",
    },
    {
      label: "AED100 (No space)",
      value: "before-nospace",
    },
    {
      label: "100AED (No space)",
      value: "after-nospace",
    },
  ];

  const getTimeZones = [
    {
      label: "(GMT+04:00) Abu Dhabi, Dubai",
      value: "Asia/Dubai",
      offset: 4,
    },
    {
      label: "(GMT+05:30) India Standard Time",
      value: "Asia/Kolkata",
      offset: 5.5,
    },
    {
      label: "(GMT+00:00) Greenwich Mean Time",
      value: "GMT",
      offset: 0,
    },
    {
      label: "(GMT+01:00) Central European Time",
      value: "Europe/Paris",
      offset: 1,
    },
    {
      label: "(GMT+02:00) Eastern European Time",
      value: "Europe/Bucharest",
      offset: 2,
    },
    {
      label: "(GMT+03:00) Moscow Standard Time",
      value: "Europe/Moscow",
      offset: 3,
    },
    {
      label: "(GMT+08:00) China Standard Time",
      value: "Asia/Shanghai",
      offset: 8,
    },
    {
      label: "(GMT+09:00) Japan Standard Time",
      value: "Asia/Tokyo",
      offset: 9,
    },
    {
      label: "(GMT-05:00) Eastern Time (US & Canada)",
      value: "America/New_York",
      offset: -5,
    },
    {
      label: "(GMT-08:00) Pacific Time (US & Canada)",
      value: "America/Los_Angeles",
      offset: -8,
    },
    {
      label: "(GMT+10:00) Australia Eastern Time",
      value: "Australia/Sydney",
      offset: 10,
    },
  ];

  const getTimeZonesFromPackage = () => {
    const allTimezones = ct?.getAllTimezones();

    return Object.entries(allTimezones)
      .map(([key, timezone]) => ({
        label: `(GMT${timezone.utcOffsetStr}) ${timezone.name}`,
        value: key,
        offset: timezone.utcOffsetStr,
        countries: timezone.countries,
      }))
      .sort((a, b) => {
        const offsetA = parseFloat(a.offset.replace(":", "."));
        const offsetB = parseFloat(b.offset.replace(":", "."));
        return offsetA - offsetB;
      });
  };

  const dateFormats = [
    { label: "YYYY MM DD", value: "YYYY MM DD" }, // 2025 09 17
    { label: "DD MM YYYY", value: "DD MM YYYY" }, // 17 09 2025
    { label: "MM DD YYYY", value: "MM DD YYYY" }, // 09 17 2025
    { label: "MMMM DD YYYY", value: "MMMM DD YYYY" }, // September 17 2025
    { label: "DD MMMM YYYY", value: "DD MMMM YYYY" }, // 17 September 2025
    { label: "dddd MMMM DD YYYY", value: "dddd MMMM DD YYYY" }, // Wednesday September 17 2025
  ];

  const dateSeparators = [
    { label: "None", value: " " },
    { label: "Forward Slash (/)", value: "/" }, // 17/09/2025
    { label: "Hyphen (-)", value: "-" }, // 17-09-2025
    { label: "Dot (.)", value: "." }, // 17.09.2025
    { label: "Space ( )", value: " " }, // 17 09 2025
    { label: "Comma (,)", value: ", " }, // September 17, 2025
    { label: "Pipe (|)", value: "|" }, // 17|09|2025
  ];

  const updatedFormats = updateDateFormatLabels(form?.date_separator);

  useEffect(() => {
    if (form?.date_separator) {
      const updatedFormats = updateDateFormatLabels(form.date_separator);

      // check if current date_format is still valid
      const stillValid = updatedFormats.some(
        (fmt) => fmt.value === form.date_format,
      );

      // if not valid, reset to first option
      if (!stillValid) {
        handleChange({
          target: {
            name: "date_format",
            value: updatedFormats[0].value,
          },
        });
      }
    }
  }, [form?.date_separator]);

  useEffect(() => {
    const sectionId = searchParams.get("id");
    if (sectionId) {
      // Use setTimeout to ensure DOM is fully rendered
      setTimeout(() => {
        const element = document.getElementById(sectionId);
        if (element) {
          element.scrollIntoView({ behavior: "smooth" });
        }
      }, 100);
    }
  }, [searchParams]);

  useEffect(() => {
    const dynamicTimeZones = getTimeZonesFromPackage();

    setTimeZones(dynamicTimeZones);
  }, []);

  useEffect(() => {
    if (!data?.settings?.[0]) return;

    const s = data.settings[0];

    setForm({
      company_name: s.company_name || "",
      address_line_1: s.address_line_1 || "",
      country: s.country || "",
      state_province: s.state_province || "",
      city: s.city || "",
      postal_zip_code: s.postal_zip_code || "",
      phone: s.phone || "",
      support_email: s.support_email || "",
      website: s.website || "",
      tax_vat_registration_number: s.tax_vat_registration_number || "",

      currencies: s.currencies || [],
      default_language: s.default_language || "",

      company_logo: s.company_logo || "",
      company_logo_color: s.company_logo_color || "",

      global_tax: JSON.stringify(s.global_tax) || [],

      date_format: s.date_format || "",
      date_separator: s.date_separator || "-",
      time_zone: s.time_zone || "",
      currency_format: s.currency_format || "",
      decimal_precision: s.decimal_precision || "",
      thousand_separator: s.thousand_separator || "",
      primary_color: s.primary_color || "",

      max_discount_percentage: s.max_discount_percentage ?? 0,
      max_discount_amount: s.max_discount_amount ?? 0,

      payment_banks: s.payment_banks || [],
      seo_title: s.seo_title || "",
      seo_description: s.seo_description || "",
      active_theme: s.active_theme || null,
      dark_theme: s.dark_theme || {},
    });
  }, [data]);

  useEffect(() => {
    if (!emailData?.settings?.length) return;

    const row = emailData.settings[0];
    setEmailForm({
      id: row.id,
      method: row.method || "",
      host: row.host || "",
      port: row.port || "",
      encryption: row.encryption || "",
      username: row.username || "",
      password: row.password || "",
      fromEmail: row.fromEmail || "",
      fromName: row.fromName || "",
      signature: row.signature || "",
      email_method: row.method || "",
      email_host: row.host || "",
      email_port: row.port || "",
      email_encryption: row.encryption || "",
      email_username: row.username || "",
      email_password: row.password || "",
      email_from: row.fromEmail || "",
      email_from_name: row.fromName || "",
      email_signature: row.signature || "",
    });
  }, [emailData]);

  if (error)
    return <AlertMessage type="error" message="Error loading settings." />;

  const mergedForm = { ...form, ...pendingUploads };

  const formData = {
    id: data?.settings?.[0]?.id,
    ...mergedForm,
    active_theme:
      mergedForm.active_theme ?? data?.settings?.[0]?.active_theme,
    dark_theme:
      mergedForm.dark_theme ?? data?.settings?.[0]?.dark_theme,
  };

  const requiredFields = [
    "company_name",
    "address_line_1",
    "state_province",
    "city",
    //"location",
    "state_province",
    "city",
    "phone",
    "support_email",
    "currencies",
    "default_language",
    "primary_color",
  ];

  const update = async () => {
    if (!validateAndAlert(formData, requiredFields, setFormValidation)) return;

    try {
      if (canModifyEmail) {
        await handleEmailSave();
      }

      const response = await fetch("/api/brand_settings", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (!response.ok) throw new Error("Failed to update settings");

      await response.json();
      setForm(mergedForm);
      setPendingUploads({});
      successMessage("Settings updated successfully!");

      await queryClient.refetchQueries({
        queryKey: ["brand_settings"],
      });
    } catch {
      //errorMessage("Error updating settings");
    }
  };

  const addNew = async () => {
    if (!validateAndAlert(formData, requiredFields)) return;

    try {
      if (canModifyEmail) {
        await handleEmailSave();
      }

      const response = await fetch(`/api/brand_settings`, {
        method: "POST",

        body: JSON.stringify(formData),
      });

      if (!response.ok) throw new Error("Failed to save settings");

      await response.json();
      setForm(mergedForm);
      setPendingUploads({});
      successMessage("Settings saved successfully!");

      queryClient.invalidateQueries({
        queryKey: ["brand_settings"],
      });
    } catch {
      //errorMessage("Error saving settings");
    }
  };

  const handleChange = (eOrValue, fieldName = null) => {
    let name, value;

    // Handle multi-select case where value is passed directly
    if (fieldName) {
      name = fieldName;
      value = eOrValue; // This will be an array for multi-select
    } else if (eOrValue?.target) {
      name = eOrValue.target.name;
      value =
        eOrValue.target.type === "checkbox"
          ? eOrValue.target.checked
          : eOrValue.target.value;
    }

    if (name) {
      setForm((prev) => ({ ...prev, [name]: value }));
    }
  };

  const handleFileUpload = async (eOrFile, key) => {
    const file =
      eOrFile?.target?.files?.[0] ||
      eOrFile?.file?.originFileObj ||
      eOrFile?.originFileObj ||
      (eOrFile instanceof File ? eOrFile : null);

    if (!file) return;

    const maxSize = 250 * 1024; // 250 KB
    if (file.size > maxSize) {
      errorMessage("File size should not exceed 250 KB");
      return;
    }

    const allowedTypes = new Set([
      "image/png",
      "image/webp",
      "image/jpeg",
      "image/svg+xml",
      "image/jpg",
    ]);
    const allowedExt = new Set([".png", ".webp", ".jpg", ".jpeg", ".svg"]);
    const ext = (file.name.match(/\.[^.]+$/)?.[0] || "").toLowerCase();

    if (!allowedTypes.has(file.type) && !allowedExt.has(ext)) {
      errorMessage("Allowed file types: png, jpg, jpeg, webp, svg");
      return;
    }

    const formDataUpload = new FormData();
    formDataUpload.append("file", file);
    formDataUpload.append("locationName", "brand");

    setLoadingUploads(true);

    try {
      const res = await fetch(`/api/upload_images`, {
        method: "POST",
        body: formDataUpload,
      });

      const data = await res.json().catch(() => ({}));

      if (!res.ok) {
        throw new Error(data?.error || "Upload failed");
      }

      const uploadedPath = data?.url || data?.message;
      if (!uploadedPath) {
        throw new Error("Upload response missing file path");
      }

      setPendingUploads((prev) => ({ ...prev, [key]: uploadedPath }));
      successMessage("File uploaded!");
    } catch (err) {
      errorMessage(err?.message || "Upload failed");
    } finally {
      setLoadingUploads(false);
    }
  };

  const handleCountryStateChange = (name, val) => {
    const country = val?.location?.country || "";
    const state = val?.location?.state_province || "";
    setForm((prev) => ({
      ...prev,
      country,
      state_province: state,
    }));
  };

  const handleEmailChange = (eOrValue, fieldName = null) => {
    let name;
    let value;

    if (typeof fieldName === "string") {
      name = fieldName;
      value = eOrValue;
    } else if (eOrValue?.target) {
      name = eOrValue.target.name;
      value =
        eOrValue.target.type === "checkbox"
          ? eOrValue.target.checked
          : eOrValue.target.value;
    }

    if (name) {
      setEmailForm((prev) => ({ ...prev, [name]: value }));
    }
  };

  const handleEmailSave = async () => {
    if (!emailForm) return;

    setEmailSaving(true);

    const payload = {
      id: emailForm.id,
      method: emailForm.email_method || emailForm.method || "",
      host: emailForm.email_host || emailForm.host || "",
      port: emailForm.email_port || emailForm.port || "",
      encryption: emailForm.email_encryption || emailForm.encryption || "",
      username: emailForm.email_username || emailForm.username || "",
      password: emailForm.email_password || emailForm.password || "",
      fromName: emailForm.email_from_name || emailForm.fromName || "",
      fromEmail: emailForm.email_from || emailForm.fromEmail || "",
      signature: emailForm.email_signature || emailForm.signature || "",
    };

    try {
      const response = await fetch("/api/email_settings", {
        method: payload.id ? "PUT" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const result = await response.json().catch(() => ({}));

      if (!response.ok) {
        throw new Error(result.error || result.message || "Unable to save email settings");
      }

      successMessage("Email settings saved");
      await refetchEmail();
    } catch (err) {
      errorMessage(err?.message || "Failed to save email settings");
    } finally {
      setEmailSaving(false);
    }
  };

  const handleTestEmail = async () => {
    if (!testEmail) {
      return errorMessage("Enter a test recipient email");
    }

    setTestEmailLoading(true);

    try {
      const formData = new FormData();
      formData.append("to", testEmail);
      formData.append("subject", "Test email from Billing");
      formData.append("message", "This is a test email.");

      const response = await fetch("/api/mail", {
        method: "POST",
        body: formData,
      });

      const result = await response.json().catch(() => ({}));

      if (!response.ok) {
        throw new Error(result.error || result.message || "Test email failed");
      }

      successMessage("Test email sent");
    } catch (err) {
      errorMessage(err?.message || "Failed to send test email");
    } finally {
      setTestEmailLoading(false);
    }
  };

  function updateDateFormatLabels(selectedSeparator) {
    const separatorRegex = /[\/\-\., ]+/g;

    return dateFormats.map((format) => {
      const label = format.label || format.value;

      const updatedLabel = label.replace(separatorRegex, selectedSeparator);

      return {
        ...format,
        label: updatedLabel,
        value: updatedLabel,
      };
    });
  }

  function getDateExample(format, separator) {
    if (!format || !separator) return "";
    const separatorRegex = /[\/\-\., ]+/g;
    const formatted = format.replace(separatorRegex, separator);
    return dayjs().format(formatted);
  }

  const languages = [{ label: "English", value: "English" }];

  const canModifyGeneral = checkPermission("general-settings.modify");
  const canModifyCompany = checkPermission("company-settings.modify");
  const canModifyBrand = checkPermission("brand-settings.modify");
  const canModifyEmail = checkPermission("email-settings.modify");
  const canEditEmail = editPermission || canModifyEmail;

  const generalTabContent = (
    <div id="general" className="grid gap-7 pt-3">

      <InputItem
        type="select"
        label="Default Language"
        name="default_language"
        value={form?.default_language}
        onChange={handleChange}
        options={languages}
        disabled={!editPermission}
      />

      <div className="grid sm:gap-5 gap-6">
        <div className="sm:flex grid gap-5">
          <InputItem
            type="select"
            label="Date Format"
            name="date_format"
            value={form?.date_format}
            onChange={handleChange}
            options={updatedFormats}
            disabled={!editPermission}
          />
          <InputItem
            type="select"
            label="Date Separator"
            name="date_separator"
            value={form?.date_separator}
            onChange={handleChange}
            options={dateSeparators}
            hint={`Example: ${getDateExample(
              form?.date_format,
              form?.date_separator
            )}`}
            disabled={!editPermission}
          />
        </div>
      </div>

      <InputItem
        type="select"
        label="Time Zone"
        name="time_zone"
        value={form?.time_zone}
        onChange={handleChange}
        options={timeZones.length ? timeZones : getTimeZones}
        disabled={!editPermission}
      />

      <InputItem
        type="select"
        label="Currency Format"
        name="currency_format"
        value={form?.currency_format}
        onChange={handleChange}
        options={getCurrencyFormats}
        disabled={!editPermission}
      />

      <InputItem
        type="select"
        label="Decimal Precision"
        name="decimal_precision"
        value={form?.decimal_precision}
        onChange={handleChange}
        options={getDecimalPrecision}
        disabled={!editPermission}
      />

      <InputItem
        type="select"
        label="Thousand Separator"
        name="thousand_separator"
        value={form?.thousand_separator}
        onChange={handleChange}
        options={getThousandSeparator}
        disabled={!editPermission}
      />

      <div>

        <TaxBuilder form={form} setForm={setForm} />
      </div>

      <InputItem
        type="tags"
        label="Currencies"
        name="currencies"
        value={form?.currencies || []}
        onChange={handleChange}
        hint="Select multiple currencies as required by your customers"
        options={allCurrencies || []}
        disabled={!editPermission}
      />

      <InputItem
        type="number"
        label="Maximum Discount (%)"
        name="max_discount_percentage"
        value={form?.max_discount_percentage || ""}
        onChange={handleChange}
        disabled={!editPermission}
      />

      <InputItem
        type="number"
        label="Maximum Discount (0.00)"
        name="max_discount_amount"
        value={form?.max_discount_amount || ""}
        onChange={handleChange}
        disabled={!editPermission}
      />
    </div>
  );

  const companyTabContent = (
    <div id="company" className="grid gap-7 pt-3">

      <InputItem
        type="text"
        label="Company Name"
        name="company_name"
        value={form?.company_name}
        onChange={handleChange}
        disabled={!editPermission}
      />

      <InputItem
        type="textarea"
        label="Address"
        name="address_line_1"
        value={form?.address_line_1}
        onChange={handleChange}
        disabled={!editPermission}
      />

      <div className="sm:flex grid sm:gap-5 gap-6">
        <InputItem
          type="country_state"
          name="location"
          label="Location"
          value={{
            location: {
              country: form?.country,
              state_province: form?.state_province,
            },
          }}
          onChange={handleCountryStateChange}
          disabled={!editPermission}
        />
      </div>

      <div className="sm:flex grid sm:gap-5 gap-6">
        <InputItem
          type="text"
          label="City"
          name="city"
          value={form?.city}
          onChange={handleChange}
          disabled={!editPermission}
        />
        <InputItem
          type="number"
          label="Postal/Zip Code"
          name="postal_zip_code"
          value={form?.postal_zip_code}
          onChange={handleChange}
          disabled={!editPermission}
        />
      </div>

      <div className="sm:flex grid sm:gap-5 gap-6">
        <InputItem
          type="email"
          label="Email"
          name="support_email"
          value={form?.support_email}
          onChange={handleChange}
          disabled={!editPermission}
        />
        <InputItem
          type="phone_with_code"
          label="Phone Number"
          name="phone"
          value={form?.phone}
          onChange={handleChange}
          disabled={!editPermission}
        />
      </div>

      <div className="sm:flex grid sm:gap-5 gap-6">
        <InputItem
          type="url"
          label="Website"
          name="website"
          value={form?.website}
          onChange={handleChange}
          disabled={!editPermission}
        />
        <InputItem
          type="text"
          label="Tax/VAT Registration Number"
          name="tax_vat_registration_number"
          value={form?.tax_vat_registration_number}
          onChange={handleChange}
          disabled={!editPermission}
        />
      </div>
    </div>
  );

  const bankTabContent = (
    <div className="grid gap-7 pt-3">

      <CompanyBanks
        form={form}
        setForm={setForm}
        editPermission={editPermission}
      />
    </div>
  );

  const emailTabContent = (
    <div className="pt-3">
      {emailError && (
        <AlertMessage
          type="error"
          message="Failed to load email settings"
          className="mb-4"
        />
      )}
      {isEmailLoading ? (
        <Loader full />
      ) : (
        <EmailSettings
          editPermission={canEditEmail}
          form={emailForm}
          handleChange={handleEmailChange}
          onSave={handleEmailSave}
          isSaving={emailSaving}
          testEmail={testEmail}
          setTestEmail={setTestEmail}
          handleTestEmail={handleTestEmail}
          testEmailLoading={testEmailLoading}
        />
      )}
    </div>
  );

  const seoTabContent = (
    <div className="grid gap-7 pt-3">

      <InputItem
        type="text"
        label="SEO Title"
        name="seo_title"
        value={form?.seo_title}
        onChange={handleChange}
        disabled={!editPermission}
      />

      <InputItem
        type="textarea"
        label="SEO Description"
        name="seo_description"
        value={form?.seo_description}
        onChange={handleChange}
        disabled={!editPermission}
      />
    </div>
  );

  const brandTabContent = (
    <div id="brand" className="grid sm:gap-5 gap-6 sm:pt-[50px] pt-[20px]">
      <PhotoUpload
        form={form}
        setForm={setForm}
        title="Company Logo"
        size={140}
        type="user"
        name="company_logo_color"
        location="brand"
      />

      <div className="flex gap-[30px]">
        <InputItem
          type="color"
          label="Primary color"
          name="primary_color"
          value={form?.primary_color}
          onChange={handleChange}
          disabled={!editPermission}
        />
      </div>
    </div>
  );

  const themeTabContent = (
    <div id="theme" className="grid gap-5 pt-6 px-2 ">
      <ThemeSelector />
    </div>
  );

  const backupTabContent = (
    <div id="backup" className="grid gap-5 pt-6">
      <BackupRestore editPermission={editPermission} />
    </div>
  );

  const tabItems = [
    ...(canModifyGeneral
      ? [
        {
          key: "general",
          label: "General",
          children: generalTabContent,
        },
      ]
      : []),
    {
      key: "company",
      label: "Company",
      children: companyTabContent,
    },
    {
      key: "bank",
      label: "Bank",
      children: bankTabContent,
    },
    {
      key: "email",
      label: "Email",
      children: emailTabContent,
    },
    {
      key: "seo",
      label: "SEO",
      children: seoTabContent,
    },
    ...(canModifyBrand
      ? [
        {
          key: "brand",
          label: "Brand",
          children: brandTabContent,
        },
      ]
      : []),
    {
      key: "theme",
      label: "Theme",
      children: themeTabContent,
    },
  ];

  const defaultTabKey = tabItems[0]?.key || "company";
  const searchItem = searchParams.get("brand_tab");
  const activeTabKey = tabItems.some((t) => t.key === searchItem)
    ? searchItem
    : defaultTabKey;

  const handleTabChange = (key) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set("brand_tab", key);
    router.push(`${pathname}?${params.toString()}`);
  };

  return (
    <div className="">
      <div className="overflow-x-auto w-full">
        <Tabs
          activeKey={activeTabKey}
          onChange={handleTabChange}
          items={tabItems}
          className="w-full overflow-hidden settings-tabs"
          tabBarStyle={{
            overflowX: "auto",
            flexWrap: "nowrap",
          }}
        />

        {(canModifyGeneral || canModifyCompany || canModifyBrand) && searchParams.get("item") !== "backup" && (
          <div className="sm:pt-0 pt-2 sm:px-0 mt-7">
            {data?.settings[0] ? (
              <InputItem
                type="button"
                name="Update"
                title="Save"
                onClick={() => update()}
                className="no-width"
                icon={<GoogleIcon name="save" size={16}

                />}

                btnvariant="solid"
              />
            ) : (
              <InputItem
                type="button"
                name="Save"
                title="Save"
                onClick={() => addNew()}
                disabled={!editPermission}
                className="no-width"
                icon={<GoogleIcon name="save" size={16} />}
                btnvariant="solid"
              />
            )}
          </div>
        )}
      </div>
      <style jsx global>{`
        .settings-tabs .ant-tabs-nav {
          width: 100%;
          background: transparent;
          overflow-x: auto;
        }
        .settings-tabs .ant-tabs-nav-list {
          display: flex;
          flex-wrap: nowrap;
          width: max-content;
          padding-bottom: 4px;
          gap: 8px;
        }
        .settings-tabs .ant-tabs-tab {
          white-space: nowrap;
        }
        .settings-tabs .ant-tabs-nav-list::-webkit-scrollbar {
          height: 4px;
        }
        .settings-tabs .ant-tabs-nav-list::-webkit-scrollbar-thumb {
          background: rgba(0, 0, 0, 0.2);
          border-radius: 2px;
        }
        @media (max-width: 640px) {
          .settings-tabs .ant-tabs-nav {
            padding-left: 8px;
            padding-right: 8px;
          }
          .settings-tabs .ant-tabs-tab-btn {
            padding: 0 12px;
          }
        }
      `}</style>
    </div>
  );
}
