import { ChangeEvent, useEffect, useState } from 'react';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType } from '@/entities/common/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useExtensionListMutation } from '@/entities/additional-service/api/use-extension-list-mutation';
import { ExtensionListParams, ExtensionListResponse, SERVICE_MAP } from '@/entities/additional-service/model/types';
import { useStore } from '@/shared/model/store';
import { Dialog } from '@/shared/ui/dialogs/dialog';

export const ListPage = () => {
  const { navigate } = useNavigate();
  const midOptions = useStore.getState().UserStore.selectOptionsMids;
  const userMid = useStore.getState().UserStore.mid;

  const [mid, setMid] = useState<string>(userMid);
  const [activeServices, setActiveServices] = useState<string[]>([]);
  const [availableServices, setAvailableServices] = useState<string[]>([]);
  const [dialogOpen, setDialogOpen] = useState<boolean>(false);

  const { mutateAsync: extensionList } = useExtensionListMutation();

  useSetHeaderTitle('부가서비스 소개');
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.home);
  });

  const callExtensionList = () => {
    let params: ExtensionListParams = {
      mid: mid
    }
    extensionList(params).then((rs: ExtensionListResponse) => {
      setActiveServices(rs.activeExtensionList || []);
      setAvailableServices(rs.availableExtensionList || []);
    });
  };

  const getActiveExtensionList = () => {
    const filteredServices = SERVICE_MAP.filter(service =>
      activeServices.includes(service.code)
    );

    return filteredServices.map((service) => (
      <div
        key={'key-active-' + service.code}
        className="list-wrap01"
        onClick={() => service.path && navigate(service.path)}
      >
        <div>
          <div className="service-name">{service.serviceName}</div>
          <p className="service-desc">{service.serviceDesc}</p>
        </div>
        <img
          src={service.icon}
          alt={service.serviceName}
        />
      </div>
    ));
  };

  const getAvailableExtensionList = () => {
    const filteredServices = SERVICE_MAP.filter(service =>
      availableServices.includes(service.code)
    );

    return filteredServices.map((service) => (
      <div
        key={'key-available-' + service.code}
        className="list-wrap02"
        onClick={() => setDialogOpen(true)}
      >
        <div>
          <div className="service-name">{service.serviceName}</div>
          <p className="service-desc">{service.serviceDesc}</p>
        </div>
        <img
          src={service.icon}
          alt={service.serviceName}
        />
      </div>
    ));
  };

  useEffect(() => {
    if (!!mid) {
      callExtensionList();
    }
  }, [mid]);

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="ing-list">
              <div className="input-wrapper top-select">
                <select
                  value={mid}
                  onChange={(e: ChangeEvent<HTMLSelectElement>) => setMid(e.target.value)}
                >
                  {
                    midOptions.map((value) => (
                      <option
                        key={value.value}
                        value={value.value}
                      >{value.name}</option>
                    ))
                  }
                </select>
              </div>
              <h3 className="ing-title">사용중인 서비스</h3>
              {getActiveExtensionList()}
              <h3 className="ing-title">신청 가능한 서비스</h3>
              {getAvailableExtensionList()}
            </div>
          </div>
        </div>
      </main>
      <Dialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        message={
          <>
            이용 중이지 않은 서비스입니다.<br />
            가입 문의는 영업 담당자 또는 고객센터로 문의해 주세요.
          </>
        }
        buttonLabel={['확인']}
        onConfirmClick={() => setDialogOpen(false)}
        afterLeave={() => { }}
      />
    </>
  )
};