"use client";

import React, { useCallback, useMemo, useState } from "react";
import { v7 as uuid } from "uuid";

import styles from "@/components/administrator/SettingGeneral/settinggeneral.module.css";

import { useSettingManagement } from "@/hooks/useSettingManagement";

import Input from "@/components/administrator/form/Input/input";
import TextArea from "@/components/administrator/form/TextArea/text.area";
import Button from "@/components/ui/Button/button";
import Switch from "@/components/ui/Switch/switch";

import { RiHomeLine } from "react-icons/ri";
import { LuSettings2 } from "react-icons/lu";
import { PiBowlSteam, PiWarningCircleThin } from "react-icons/pi";
import { FiFileText } from "react-icons/fi";
import { IoImageOutline } from "react-icons/io5";
import { SiGoogleanalytics, SiGoogletagmanager } from "react-icons/si";

/**
 *
 * @type {React.FC<{
 *    generalSetting: any
 * }>}
 *
 * @returns {JSX.Element}
 */
const SettingGeneral = (props) => {
  const [data, setData] = useState(props.generalSetting);
  const { saveGeneralSetting, setDefaultGeneralSetting } =
    useSettingManagement();

  const formatedData = useMemo(() => {
    return {
      ...data,
      googleAnalyticsId: (() => {
        let value = data?.googleAnalyticsId;
        if (value) {
          if (!value.startsWith("G-")) value = "G-" + value;
        } else {
          value = null;
        }

        return value;
      })(),
      googleTagId: (() => {
        let value = data?.googleTagId;
        if (value) {
          if (!value.startsWith("GTM-")) value = "GTM-" + value;
        } else {
          value = null;
        }

        return value;
      })(),
      logo: (() => {
        let value = data?.logo;
        if (value) {
          if (!value.startsWith("/")) value = "/" + value;
        } else {
          value = null;
        }

        return value;
      })(),
    };
  }, [data]);

  const isChanges = useMemo(
    () => JSON.stringify(props.generalSetting) !== JSON.stringify(formatedData),
    [formatedData, props]
  );

  // action
  const handleSave = useCallback(() => {
    saveGeneralSetting(formatedData, (data) => {
      setData(data);
    });
  }, [formatedData, saveGeneralSetting]);

  const handleSetDefault = useCallback(() => {
    setDefaultGeneralSetting((data) => {
      setData(data);
    });
  }, [setDefaultGeneralSetting]);

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.header_title}>
          <h3>
            <LuSettings2 /> General Setting
          </h3>
          <p>Manage basic website information and default preferences.</p>
        </div>
        <div className={styles.header_action}>
          <Button
            className={styles.button}
            onClick={handleSave}
            disabled={!isChanges}>
            Save
          </Button>
          <Button
            className={`${styles.button} ${styles.reverse}`}
            onClick={handleSetDefault}>
            Set Default
          </Button>
        </div>
      </div>
      <div className={styles.content}>
        <div className={styles.input_container}>
          <div className={styles.input_label}>
            <p>
              Website Name <PiWarningCircleThin title="Required" />
            </p>
            <span>
              The display name of your website. This name appears in the header,
              browser title, and other public areas.
            </span>
          </div>
          <div className={styles.input_content}>
            <Input
              className={styles.input}
              icon={<RiHomeLine />}
              value={data?.title}
              onChange={(e) => setData({ ...data, title: e.target.value })}
            />
          </div>
        </div>
        <div className={styles.input_container}>
          <div className={styles.input_label}>
            <p>
              Website Description{" "}
              <PiWarningCircleThin title="Required For SEO" />
            </p>
            <span>A short summary of your website’s purpose or content.</span>
          </div>
          <div className={styles.input_content}>
            <TextArea
              className={styles.input}
              value={data?.description}
              icon={<FiFileText />}
              onChange={(e) =>
                setData({ ...data, description: e.target.value })
              }
            />
          </div>
        </div>
        <div className={styles.input_container}>
          <div className={styles.input_label}>
            <p>
              Website Hero Image <PiWarningCircleThin title="Required" />
            </p>
            <span>This only for SEO.</span>
          </div>
          <div className={styles.input_content}>
            <Input
              className={styles.input}
              icon={<IoImageOutline size={22} />}
              value={data?.logo}
              continouslyFrom={`${process.env.NEXT_PUBLIC_ORIGIN}/`}
              onChange={(e) => setData({ ...data, logo: e.target.value })}
              format={{
                label: "Open Image in New Tab",
                action: (element) => {
                  // open in new tab
                  window.open(
                    `${process.env.NEXT_PUBLIC_ORIGIN}/${element.value}`,
                    "_blank"
                  );
                },
                changeInput: false,
              }}
              tip="Input your image name, example: 'company.png'. Place your image to /public folder."
            />
          </div>
        </div>
        <div className={styles.input_container}>
          <div className={styles.input_label}>
            <p>CMS ID</p>
            <span>CMS ID for your website.</span>
          </div>
          <div className={styles.input_content}>
            <Input
              className={styles.input}
              icon={<PiBowlSteam size={17} />}
              value={data?.CMS_ID || ""}
              disabled={true}
              format={
                !data?.CMS_ID && {
                  action: (_) => {
                    const id = uuid();
                    setData({ ...data, CMS_ID: `ICETEA-${id}` });

                    return id;
                  },
                  changeInput: true,
                  label: "Generate CMS ID",
                }
              }
            />
          </div>
        </div>
        <span className={styles.separator}></span>
        <div className={styles.input_container}>
          <div className={styles.input_label}>
            <p>Google Analytics IDs</p>
            <span>
              Add your Google Analytics ID to monitor website visitors and
              performance.
            </span>
          </div>
          <div className={styles.input_content}>
            <Input
              className={styles.input}
              icon={<SiGoogleanalytics size={13} />}
              value={data?.googleAnalyticsId || ""}
              onChange={(e) =>
                setData({ ...data, googleAnalyticsId: e.target.value })
              }
              tip="Measurement ID (e.g., G-XXXXXXX)"
            />
          </div>
        </div>
        <div className={styles.input_container}>
          <div className={styles.input_label}>
            <p>Google Tag Manager ID</p>
            <span>
              Used to connect your website with Google Tag Manager for managing
              tracking codes.
            </span>
          </div>
          <div className={styles.input_content}>
            <Input
              className={styles.input}
              icon={<SiGoogletagmanager size={13} />}
              value={data?.googleTagId || ""}
              onChange={(e) =>
                setData({ ...data, googleTagId: e.target.value })
              }
              tip="Container ID (e.g., GTM-XXXXXXX)"
            />
          </div>
        </div>
        <span className={styles.separator}></span>
        <div className={styles.input_container}>
          <div className={styles.input_label}>
            <p>Open Bridge</p>
            <span>
              If enable this feature, this cms possible to manage content across
              the company.
            </span>
          </div>
          <div className={styles.input_content}>
            <Switch
              value={data?.bridge}
              onChange={(e) => setData({ ...data, bridge: e })}
            />
          </div>
        </div>
        <div className={styles.input_container}>
          <div className={styles.input_label}>
            <p>Use Socket IO</p>
            <span>
              Important: Enable this, you must use custom runtime server.
            </span>
          </div>
          <div className={styles.input_content}>
            <Switch
              value={data?.useSocketIO}
              onChange={(e) => setData({ ...data, useSocketIO: e })}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default SettingGeneral;
