"use client";
import React, { useEffect, useState } from "react";
import Label from '@/components/form/Label2';
import Input from '@/components/form/input/InputField2';
import Select from '@/components/form/Select2';
import CtModal from "@/components/CtModal";
import { useMultiState } from "@/hooks/useMultiState";
import api from '@/lib/_AG';
import Button from "@/components/ui/button/Button2";
import { PlusIcon, TrashBinIcon } from "@/icons";

interface TemplateElement {
  slot: string;
  goods_id: number;
  inventory?: number;
}

interface Template {
  goods_template_id: number;
  template_name: string;
  elements: TemplateElement[];
}

export interface TemplateModalProps {
  biz_group_id: number;
  optGoodsList: { label: string; value: string; }[];
}

interface ManageTemplateModalProps {
  multiState: ReturnType<typeof useMultiState<TemplateModalProps>>;
  onOk: () => void;
  isOpen: boolean;
  closeModal: () => void;
}

type Mode = 'list' | 'create' | 'edit';

export default function ManageTemplateModal({ multiState, onOk, isOpen, closeModal }: ManageTemplateModalProps) {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [mode, setMode] = useState<Mode>('list');
  const [selectedTemplateId, setSelectedTemplateId] = useState<number | null>(null);
  const [templateName, setTemplateName] = useState<string>("");
  const [currentElements, setCurrentElements] = useState<TemplateElement[]>([]);

  // function part
  function groupTemplatesByTemplateId(data: any[]): Template[] {
    const templateMap = new Map<number, Template>();

    data.forEach((item) => {
      const templateId = item.goods_template_id;
      
      if (!templateMap.has(templateId)) {
        templateMap.set(templateId, {
          goods_template_id: templateId,
          template_name: item.template_name,
          elements: []
        });
      }

      const template = templateMap.get(templateId)!;
      template.elements.push({
        slot: item.slot,
        goods_id: item.goods_id,
        inventory: item.inventory
      });
    });

    return Array.from(templateMap.values());
  }

  function reqTemplateList() {
    if (!multiState.values.biz_group_id) {
      return;
    }

    const params = {
      biz_group_id: multiState.values.biz_group_id
    };

    api.post('/api/get-goods-template.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
        if (resp.data.result && resp.data.result.length > 0) {
          const groupedTemplates = groupTemplatesByTemplateId(resp.data.result);
          setTemplates(groupedTemplates);
        } else {
          setTemplates([]);
        }
      } else {
        alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => {
      console.error(err);
      alert("템플릿 조회 중 오류가 발생했습니다.");
    });
  }

  function reqRemoveTemplate(templateId: number) {
    if (!confirm("템플릿을 삭제하시겠습니까?")) {
      return;
    }

    const params = {
      goods_template_id: templateId
    };

    api.post('/api/remove-goods-template.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
        alert("삭제되었습니다.");
        reqTemplateList();
      } else {
        alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => {
      console.error(err);
      alert("템플릿 삭제 중 오류가 발생했습니다.");
    });
  }

  function reqAddTemplate() {
    if (currentElements.length === 0) {
      alert("최소 하나 이상의 상품을 등록해야 합니다.");
      return;
    }

    // slot이 빈 문자열인 항목 필터링
    const validElements = currentElements.filter(item => item.slot !== "");

    if (validElements.length === 0) {
      alert("컬럼번호를 입력한 상품이 없습니다.");
      return;
    }

    const params = {
      biz_group_id: multiState.values.biz_group_id,
      goods_template_elements: validElements.map(item => ({
        slot: item.slot,
        goods_id: item.goods_id,
        inventory: item.inventory || null
      }))
    };

    api.post('/api/add-goods-template.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
        alert("생성되었습니다.");
        resetToInitialState();
        reqTemplateList();
        onOk();
      } else {
        alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => {
      console.error(err);
      alert("템플릿 생성 중 오류가 발생했습니다.");
    });
  }

  function reqModifyTemplate() {
    if (!selectedTemplateId) {
      return;
    }

    if (currentElements.length === 0) {
      alert("최소 하나 이상의 상품을 등록해야 합니다.");
      return;
    }

    // slot이 빈 문자열인 항목 필터링
    const validElements = currentElements.filter(item => item.slot !== "");

    if (validElements.length === 0) {
      alert("컬럼번호를 입력한 상품이 없습니다.");
      return;
    }

    const params = {
      goods_template_id: selectedTemplateId,
      goods_template_name: templateName || undefined,
      goods_template_elements: validElements.map(item => ({
        slot: item.slot,
        goods_id: item.goods_id,
        inventory: item.inventory || null
      }))
    };

    api.post('/api/modify-goods-template.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
        alert("수정되었습니다.");
        resetToInitialState();
        reqTemplateList();
        onOk();
      } else {
        alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => {
      console.error(err);
      alert("템플릿 수정 중 오류가 발생했습니다.");
    });
  }

  function resetToInitialState() {
    setMode('list');
    setSelectedTemplateId(null);
    setTemplateName("");
    setCurrentElements([]);
  }

  // event handler function part
  const handleClickCreate = () => {
    setMode('create');
    setCurrentElements([]);
    setTemplateName("");
  };

  const handleClickEdit = (template: Template) => {
    setMode('edit');
    setSelectedTemplateId(template.goods_template_id);
    setTemplateName(template.template_name);
    setCurrentElements([...template.elements]);
  };

  const handleClickCancel = () => {
    resetToInitialState();
  };

  const handleClickAdd = () => {
    if (multiState.values.optGoodsList.length == 0) {
      alert("등록된 상품이 없습니다. 좌측 '상품관리' 메뉴에서 상품목록을 등록하세요.");
      return;
    }

    const newItem: TemplateElement = {
      slot: "",
      goods_id: parseInt(multiState.values.optGoodsList[0].value)
    };
    setCurrentElements([...currentElements, newItem]);
  };

  const handleClickDel = (index: number) => {
    const newArray = currentElements.filter((_, i) => i !== index);
    setCurrentElements(newArray);
  };

  const handleChangeSlot = (index: number, newValue: string) => {
    const newArray = [...currentElements];
    newArray[index].slot = newValue;
    setCurrentElements(newArray);
  };

  const handleChangeInventory = (index: number, newValue: string) => {
    const newArray = [...currentElements];
    newArray[index].inventory = Number(newValue);
    setCurrentElements(newArray);
  };

  const handleChangeGoods = (index: number, newValue: string) => {
    const newArray = [...currentElements];
    newArray[index].goods_id = Number(newValue);
    setCurrentElements(newArray);
  };

  // useEffect part
  useEffect(() => {
    if (isOpen && multiState.values.biz_group_id) {
      reqTemplateList();
      resetToInitialState();
    }
  }, [isOpen, multiState.values.biz_group_id]);

  // UI part
  return (
    // <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
      <CtModal
        title={"템플릿 관리"}
        description={"상품 템플릿을 관리하세요."}
        okBtnText={mode === 'create' ? "생성" : mode === 'edit' ? "수정" : undefined}
        onClickOk={mode === 'create' ? reqAddTemplate : mode === 'edit' ? reqModifyTemplate : undefined}
        isOpen={isOpen}
        closeModal={() => {
          resetToInitialState();
          closeModal();
        }}
        className="max-w-[700px] p-6 lg:p-10"
      >
        {mode === 'list' && (
          <>
            <div className="space-y-2 mb-4">
              {templates.length === 0 ? (
                <div className="text-center py-4 text-gray-500">등록된 템플릿이 없습니다.</div>
              ) : (
                templates.map((template) => (
                  <div
                    key={template.goods_template_id}
                    className="flex items-center justify-between p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer"
                    onClick={() => handleClickEdit(template)}
                  >
                    <span className="flex-1">{template.template_name}</span>
                    <div onClick={(e) => e.stopPropagation()}>
                      <Button
                        size="sm"
                        variant="outline"
                        startIcon={<TrashBinIcon />}
                        onClick={() => {
                          reqRemoveTemplate(template.goods_template_id);
                        }}
                      />
                    </div>
                  </div>
                ))
              )}
            </div>
            <div>
              <Button size="sm" variant="primary" startIcon={<PlusIcon />} onClick={handleClickCreate}>
                신규 생성
              </Button>
            </div>
          </>
        )}

        {(mode === 'create' || mode === 'edit') && (
          <>
            {mode === 'edit' && (
              <div>
                <Label>템플릿 이름</Label>
                <Input
                  type="text"
                  placeholder="템플릿 이름을 입력하세요"
                  value={templateName}
                  onChange={(e) => setTemplateName(e.target.value)}
                />
              </div>
            )}
            {currentElements.map((item, index) => (
              <div key={index}>
                <Label>상품정보 {index + 1}</Label>
                <div className="flex gap-2">
                  <div className="w-34">
                    <Input
                      type="text"
                      placeholder="컬럼번호"
                      value={item.slot}
                      onChange={(e) => handleChangeSlot(index, e.target.value)}
                    />
                  </div>
                  <div className="flex-1">
                    <Select
                      placeholder="상품을 선택하세요"
                      options={multiState.values.optGoodsList}
                      defaultValue={String(item.goods_id)}
                      onChange={(value) => handleChangeGoods(index, value)}
                      className="dark:bg-dark-900"
                    />
                  </div>
                  <div className="w-34">
                    <Input
                      type="number"
                      placeholder="재고수"
                      value={item.inventory || ""}
                      onChange={(e) => handleChangeInventory(index, e.target.value)}
                    />
                  </div>
                  <Button
                    size="sm"
                    variant="outline"
                    startIcon={<TrashBinIcon />}
                    onClick={() => handleClickDel(index)}
                  />
                </div>
              </div>
            ))}
            <div className="flex gap-2">
              <Button size="sm" variant="primary" startIcon={<PlusIcon />} onClick={handleClickAdd}>
                상품 추가하기
              </Button>
              <Button size="sm" variant="outline" onClick={handleClickCancel}>
                취소
              </Button>
            </div>
          </>
        )}
      </CtModal>
    // </div>
  );
}

