"use client"
import PageBreadcrumb from "@/components/common/PageBreadCrumb2";
import ComponentCard from '@/components/common/ComponentCard2';
import CtTable1 from '@/components/tables/CtTable1';
import Button from '@/components/ui/button/Button2';
import { DocsIcon, FileIcon, PlusIcon, TrashBinIcon, TableIcon, PencilIcon, GridIcon } from "@/icons";
import Label from '@/components/form/Label2';
import Input from '@/components/form/input/InputField2';
import Select from '@/components/form/Select2';
import DatePicker from '@/components/form/date-picker2';
import Badge from "@/components/ui/badge/Badge";
import Checkbox from '@/components/form/input/Checkbox';
import SaveTemplateNameModal from './GoodsTemplateNameModal';

import React, { Key } from "react";
import { useEffect, useState } from 'react';
//import { useSearchParams, useRouter } from "next/navigation";
import { useRouter, useSearchParams } from "next/navigation";
import api, { convertDateTime3, getUrlParam, useAuthStore } from '@/lib/_AG';
import DeviceGoodsList from '@/components/DeviceGoodsItem';



interface DeviceGooodsItem {
  slot: string;
  goods_id: number;
  price?: number;
  inventory?: number;
  inventory_max?: number;
  inventory_alarm?: number;
  idx?: number;
}

interface GoodsTemplateItem {
  goods_template_id: number;
  template_name: string;
  template_reg_time?: string;
  template_inventory: number;
  template_inventory_max: number;
  template_inventory_alarm: number;
  goods_template_elements: Array<{
    goods_template_element_id: number;
    goods_id: number;
    slot: string;
    inventory: number;
    inventory_max?: number;
    inventory_alarm?: number;
    idx: number;
  }>;
}

function makeParams(device_id: string, prev_device_goods: DeviceGooodsItem[], new_device_goods: DeviceGooodsItem[], isSaveTemplate: boolean, templateName: string, biz_group_id: string | undefined, inventorySetValue: { inventory: number; inventory_max: number; inventory_alarm: number } ) {
  const filteredPrev = prev_device_goods.filter(item => item.slot !== "" && item.goods_id !== 0);
  const filteredNew = new_device_goods.filter(item => item.slot !== "" && item.goods_id !== 0);

  const final_device_goods = filteredPrev.filter(prevItem => 
    !filteredNew.find(newItem => 
      newItem.slot === prevItem.slot && newItem.goods_id === prevItem.goods_id && newItem.inventory === prevItem.inventory && newItem.inventory_max === prevItem.inventory_max && newItem.inventory_alarm === prevItem.inventory_alarm
    )
  );

  const final_new_device_goods = filteredNew.filter(newItem => 
    !filteredPrev.find(prevItem => 
      prevItem.slot === newItem.slot && prevItem.goods_id === newItem.goods_id && newItem.inventory === prevItem.inventory && newItem.inventory_max === prevItem.inventory_max && newItem.inventory_alarm === prevItem.inventory_alarm
    )
  );

  console.log("saved prev_device_goods: " + JSON.stringify(prev_device_goods));
  console.log("saved new_device_goods: " + JSON.stringify(new_device_goods));
  console.log("filteredNew: " + JSON.stringify(filteredNew));
  console.log("final_device_goods: " + JSON.stringify(final_device_goods));
  console.log("final_new_device_goods: " + JSON.stringify(final_new_device_goods));

  const params: any = { 
    device_id: Number(device_id), 
    prev_device_goods: final_device_goods,
    new_device_goods: final_new_device_goods
  };

  params.isSaveTemplate = isSaveTemplate;
  params.templateName = templateName;
  params.biz_group_id = biz_group_id;
  params.goods_template_elements = filteredNew;
  params.goods_template_inventory = {
    inventory_count: inventorySetValue?.inventory || 0,
    inventory_max: inventorySetValue?.inventory_max || 0,
    inventory_alarm: inventorySetValue?.inventory_alarm || 0
  };


  console.log("params: " + JSON.stringify(params));
  return params;
}

export default function ManageGoods() {

  const searchParams = useSearchParams();
  const device_id = searchParams?.get('id') ?? "";
  
  const router = useRouter();
  const tokenPayload = useAuthStore((s) => s.tokenPayload);  //Bruce, JWT
  
  const [ biz_group_id, setBiz_group_id ] = useState<string>("");
  const [ biz_group_name, setBiz_group_name ] = useState<string>("");
  const [ biz_reg_num, setBiz_reg_num ] = useState<string>("");
  const [ device_name, setDevice_name ] = useState<string>("");

  const [ optGoodsList, setOptGoodsList ] = useState<any>([]);
  
  const [ prev_device_goods, setPrev_device_goods ] = useState<any[]>([]);
  const [ new_device_goods, setNew_device_goods ] = useState<any[]>(Array.from({ length: 30 }, (_, i) => ({ idx: i + 1, slot: String(i + 1).padStart(2, "0"), goods_id: 0, inventory: 0, inventory_max: 0, inventory_alarm: 0 })));
  
  const [ isSaveTemplate, setIsSaveTemplate ] = useState<boolean>(false);
  const [ isModalOpen, setIsModalOpen ] = useState<boolean>(false);
  const [ goodsTemplateList, setGoodsTemplateList ] = useState<GoodsTemplateItem[]>([]);
  const [ inventorySetValue, setInventorySetValue ] = useState<{ inventory: number; inventory_max: number; inventory_alarm: number }>({ inventory: 0, inventory_max: 0, inventory_alarm: 0 });

  function reqDeviceGoodsList(device_id: string) {
    const params = {
      device_id: device_id
    }

    api.post('/api/get-device-goods.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
        if (resp.data.result.goods_list.length == 0) {
          alert("등록된 상품이 없습니다. 좌측 '상품관리' 메뉴에서 상품목록을 등록하세요.");
          //router.back();
          router.push("/device");
          return;
        }
        /*
        biz_group_id를 goods_list 에서 가져옮으로서 잘못된 biz_group이 선택되고 있는 문제 해결 필요   
        */
        setDevice_name(resp.data.result.device_name);
        setBiz_group_name(resp.data.result.goods_list[0].biz_group_name);
        setBiz_reg_num(resp.data.result.goods_list[0].biz_reg_num);

        const goodsList: { label: string; value: string; }[] = [];
        resp.data.result.goods_list.map((item: any) => (
          goodsList.push({ label: item.name + "(" + item.code + ")", value: String(item.goods_id) })
        ));
        setOptGoodsList(goodsList);

        setBiz_group_id(resp.data.result.goods_list[0].biz_group_id);
        if (resp.data.result.device_goods_list.length > 0) {
          setPrev_device_goods(structuredClone(resp.data.result.device_goods_list));

          setNew_device_goods(prev => prev.map(item => {
            const updated = resp.data.result.device_goods_list.find((u: { idx: string; }) => u.idx === item.idx);
            return updated ? { ...item, ...updated } : item;
          }));
        }

        if (resp.data.result.goods_template_list && resp.data.result.goods_template_list.length > 0) {
          setGoodsTemplateList(resp.data.result.goods_template_list);
          setInventorySetValue( { inventory: resp.data.result.goods_template_list[0].inventory_count || 0, inventory_max: resp.data.result.goods_template_list[0].inventory_max || 0, inventory_alarm: resp.data.result.goods_template_list[0].inventory_alarm || 0 } );
        }
      }
      else {
        alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }
  
  // function part
  //
  function onGoback() {
    //router.back();
    router.push("/device");
  }
  
  // event processing part
  //
  const handleClickDel = (row: number) => {
    const newArray: DeviceGooodsItem[] =
      new_device_goods.filter((_, index) => index !== row);

    setNew_device_goods(newArray);
  }

  const handleChangeSlot = (index: number, newValue: string) => {
    const newArray: DeviceGooodsItem[] = [...new_device_goods];
    newArray[index].slot = newValue;

    setNew_device_goods(newArray);
  };

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

    setNew_device_goods(newArray);
  };

  const handleChangeInventoryMax = (index: number, newValue: string) => {
    const newArray: DeviceGooodsItem[] = [...new_device_goods];
    newArray[index].inventory_max = Number(newValue);

    setNew_device_goods(newArray);
  };

  const handleChangeInventoryAlarm = (index: number, newValue: string) => {
    const newArray: DeviceGooodsItem[] = [...new_device_goods];
    newArray[index].inventory_alarm = Number(newValue);

    setNew_device_goods(newArray);
  };

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

    setNew_device_goods(newArray);
  };

  const handleChangeInventorySetValue = (field: 'inventory' | 'inventory_max' | 'inventory_alarm', value: number) => {
    setInventorySetValue(prev => ({ ...prev, [field]: value }));
  };
  
  const handleClickAdd = () => {
    //const newItem: DeviceGooodsItem = { slot: "", goods_id: parseInt(optGoodsList[0].value) }
    const newItem: DeviceGooodsItem = { slot: "", goods_id: 0 }
    const newArray: DeviceGooodsItem[] = [...new_device_goods, newItem];

    setNew_device_goods(newArray);
  }
  //

  const handleClickAddOrModify = () => {
    if (isSaveTemplate) {
      setIsModalOpen(true);
      return;
    } else {
      executeSave(false, "");
    }
  }

  const handleModalClose = (tName: string) => {
    setIsModalOpen(false);
    if (tName !== "") {
      executeSave(true, tName);
    } else {
      return; // 사전저장하기 했는데 이름안정했으면 저장 취소되도록함.
    }
  };

  const executeSave = (saveTemplate: boolean, name: string) => {
    const params = makeParams(device_id, prev_device_goods, new_device_goods, saveTemplate, name, biz_group_id, inventorySetValue);
    
    api.post('/api/manage-device-goods.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
          alert("자판기에 상품내용이 적용되었습니다.");
          router.push("/device");
          //onOk();
      }
      else if (resp.data.errCode == -11) {
          alert("컬럼번호는 중복될 수 없습니다.");
      }
      else {
          alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }

  const handleApplyGoodsTemplate = (goodsTemplateId: number) => {
    const goodsTemplate = goodsTemplateList.find((item: GoodsTemplateItem) => item.goods_template_id === goodsTemplateId);
    if (goodsTemplate && goodsTemplate.goods_template_elements) {
      // 기존 값을 모두 비우고 초기 상태로 리셋
      const resetGoods = Array.from({ length: 30 }, (_, i) => ({ 
        idx: i + 1, 
        slot: String(i + 1).padStart(2, "0"), 
        goods_id: 0, 
        inventory: 0 
      }));

      setInventorySetValue( { inventory: goodsTemplate.template_inventory, inventory_max: goodsTemplate.template_inventory_max, inventory_alarm: goodsTemplate.template_inventory_alarm } );

      
      // 템플릿의 goods_template_elements를 DeviceGooodsItem 형태로 변환
      const mappedGoods: DeviceGooodsItem[] = goodsTemplate.goods_template_elements.map((element) => ({
        slot: element.slot,
        goods_id: Number(element.goods_id),
        inventory: element.inventory,
        inventory_max: element.inventory_max,
        inventory_alarm: element.inventory_alarm,
        idx: element.idx
      }));
      
      // 템플릿 요소로 채우기
      const updatedGoods = resetGoods.map(item => {
        const templateItem = mappedGoods.find((t: DeviceGooodsItem) => t.idx === item.idx);
        return templateItem ? { ...item, ...templateItem } : item;
      });
      
      setNew_device_goods(updatedGoods);
    }
  }

  useEffect(() => {
    reqDeviceGoodsList(device_id);
    // reqGoodsTemplateList(tokenPayload?.biz_group_id || "");
  }, [tokenPayload]);

  return (
    <div>
      <PageBreadcrumb pageTitle1="무인기기 관리" pageLink1="/device" pageTitle2={"무인기기 상품관리"} />

      <div className="space-y-3">
        <ComponentCard>
        
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-5">
            <div>
              <Label>사업자원장</Label>
              <Input type="text" value={biz_group_name + "(" + biz_reg_num + ")"} disabled />
            </div>
            <div>
              <Label>무인기기명 또는 관리이름</Label>
              <Input type="text" value={device_name} disabled />
            </div>
            <div></div>
            <div>
              <Label>상품 사전설정 목록</Label>
              <Select
                options={goodsTemplateList.map((item: any) => (
                  { value: item.goods_template_id, label: item.template_name }
                ))}
                placeholder="선택하세요"
                onChange={(value) => handleApplyGoodsTemplate(Number(value))}
                className="dark:bg-dark-900"
              />
            </div>
            <div>
              <Label>&nbsp;</Label>
              <Button size="sm" variant="outline" startIcon={<PencilIcon />} onClick={() => router.push("/goods-template")}>목록관리</Button>
            </div>
          </div>

          <DeviceGoodsList
            deviceGoodsList={new_device_goods}
            optGoodsList={optGoodsList}
            inventroySetValue={inventorySetValue}
            onChangeInventorySetValue={handleChangeInventorySetValue}
            onSlotChange={handleChangeSlot}
            onGoodsChange={handleChangeGoods}
            onInventoryChange={handleChangeInventory}
            onInventoryMaxChange={handleChangeInventoryMax}
            onInventoryAlarmChange={handleChangeInventoryAlarm}
            onClickAdd={handleClickAdd}
          />
        </ComponentCard>

        <ComponentCard>
          <div className="space-y-2">
              <div>
                <Checkbox 
                  checked={isSaveTemplate} 
                  onChange={(checked) => setIsSaveTemplate(checked)}
                  label="현재 저장값을 사전설정 목록에 추가하기"
                />
              </div>
              <div className="flex items-center gap-5">
                <Button size="sm" variant="primary" onClick={handleClickAddOrModify}>적용하기</Button>
                <Button size="sm" variant="outline" onClick={onGoback}>취소</Button>
              </div>
            </div>
        </ComponentCard>

        <SaveTemplateNameModal
            isOpen={isModalOpen}
            closeModal={handleModalClose}
          />
      </div>
    </div>
  );
}
