"use client"
import PageBreadcrumb from "@/components/common/PageBreadCrumb2";
import ComponentCard from '@/components/common/ComponentCard2';
import Button from '@/components/ui/button/Button2';
import { GridIcon, DocsIcon } from "@/icons";
import Label from '@/components/form/Label2';
import Input from '@/components/form/input/InputField2';
import DeviceGoodsList from '@/components/DeviceGoodsItem';

import React from "react";
import { useEffect, useState } from 'react';
import { useRouter, useParams, useSearchParams } from "next/navigation";
import api, { convertDateTime2, useAuthStore } from '@/lib/_AG';

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

interface GoodsTemplateData {
  goods_template_id: number;
  goods_template_name: string;
  goods_template_reg_time: string;
}

export default function GoodsTemplateEdit() {
  const searchParams = useSearchParams();
  const templateId = searchParams?.get('id') ?? "";
  const isNewTemplate = templateId === "";
  const cds = searchParams?.get('cds') ?? "";

  const router = useRouter();
  const tokenPayload = useAuthStore((s) => s.tokenPayload);
  
  const [deviceGoods, setDeviceGoods] = useState<DeviceGooodsItem[]>(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 [optGoodsList, setOptGoodsList] = useState<{ label: string; value: string; }[]>([]);
  const [goodsTemplate, setGoodsTemplate] = useState<GoodsTemplateData | null>(null);
  const [inventorySetValue, setInventorySetValue] = useState<{ inventory: number; inventory_max: number; inventory_alarm: number }>({ inventory: 0, inventory_max: 0, inventory_alarm: 0 });

  function reqGoodsTemplate() {
    const params = {
      goods_template_id: Number(templateId)
    }

    api.post('/api/get-goods-templates.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
        if (resp.data.result.goods_template_elements && resp.data.result.goods_template_elements.length > 0) {
            const template = resp.data.result.goods_template_elements[0];
            setGoodsTemplate({
              goods_template_id: template.goods_template_id,
              goods_template_name: template.template_name,
              goods_template_reg_time: template.template_reg_time
            });

            setInventorySetValue({
              inventory: template.template_inventory || 0,
              inventory_max: template.template_inventory_max || 0,
              inventory_alarm: template.template_inventory_alarm || 0
            });
            
            setDeviceGoods(prev => prev.map(item => {
              const templateItem = resp.data.result.goods_template_elements.find((t: DeviceGooodsItem) => t.idx === item.idx);
              return templateItem ? { ...item, ...templateItem } : item;
            }));
          }
          if (resp.data.result.goods_list && resp.data.result.goods_list.length > 0) {
            setOptGoodsList(resp.data.result.goods_list.map((item: any) => ({ label: item.name + "(" + item.code + ")", value: String(item.goods_id) })));
          }
      }
      else {
        alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })  
    .catch((err) => console.error(err))
  }

  function reqGoodsList() {
    const params = {
      biz_group_id: cds,
      limit: 100
    }

    api.post('/api/get-goods.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
        const goodsList: { label: string; value: string; }[] = [];
        resp.data.result.list.map((item: any) => (
          goodsList.push({ label: item.name + "(" + item.code + ")", value: String(item.goods_id) })
        ));
        setOptGoodsList(goodsList);
      }
      else {
        alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }

  const handleChangeSlot = (index: number, value: string) => {
    const newGoods = [...deviceGoods];
    newGoods[index].slot = value;
    setDeviceGoods(newGoods);
  };

  const handleChangeGoods = (index: number, value: string) => {
    const newGoods = [...deviceGoods];
    newGoods[index].goods_id = Number(value);
    setDeviceGoods(newGoods);
  };

  const handleChangeInventory = (index: number, value: string) => {
    const newGoods = [...deviceGoods];
    newGoods[index].inventory = Number(value) || 0;
    setDeviceGoods(newGoods);
  };

  const handleChangeInventoryMax = (index: number, value: string) => {
    const newGoods = [...deviceGoods];
    newGoods[index].inventory_max = Number(value) || 0;
    setDeviceGoods(newGoods);
  };

  const handleChangeInventoryAlarm = (index: number, value: string) => {
    const newGoods = [...deviceGoods];
    newGoods[index].inventory_alarm = Number(value) || 0;
    setDeviceGoods(newGoods);
  };

  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[] = [...deviceGoods, newItem];

    setDeviceGoods(newArray);
  }

  const handleSave = () => {
    if (!goodsTemplate?.goods_template_name) {
      alert("사전설정명을 입력해주세요.");
      return;
    }

    const validGoods = deviceGoods.filter(item => 
      item.slot && item.goods_id && item.inventory != null && item.inventory > 0
    );

    if (validGoods.length === 0) {
      alert("상품 정보를 입력해주세요.");
      return;
    }

    const params: any = {
      biz_group_id: Number(cds),
      goods_template_name: goodsTemplate?.goods_template_name,
      goods_template_inventory: {
        inventory: inventorySetValue.inventory,
        inventory_max: inventorySetValue.inventory_max,
        inventory_alarm: inventorySetValue.inventory_alarm
      },
      goods_template_elements: validGoods.map(item => ({
        slot: item.slot,
        goods_id: item.goods_id,
        inventory: item.inventory,
        idx: item.idx,
        inventory_max: item.inventory_max,
        inventory_alarm: item.inventory_alarm
      }))
    };

    if (!isNewTemplate) {
      params.goods_template_id = Number(templateId);
    }

    api.post('/api/manage-goods-template.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
        alert(isNewTemplate ? "사전설정이 저장되었습니다." : "사전설정이 수정되었습니다.");
        router.push('/goods-template');
      }
      else {
        alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  };

  const handleCancel = () => {
    if (confirm("변경사항이 저장되지 않습니다. 취소하시겠습니까?")) {
      router.push('/goods-template');
    }
  };
  //

  useEffect(() => {
    if (!cds) {
      alert("잘못된 접근입니다");
      router.push('/goods-template');
      return;
    }

    if (isNewTemplate) {
      reqGoodsList();
      return;
    }
    
    if (tokenPayload) {
      reqGoodsTemplate();
    }
  }, [tokenPayload, cds, isNewTemplate]);

  return (
    <div>
      <PageBreadcrumb pageTitle1="상품 사전설정 관리" pageTitle2={isNewTemplate ? "신규 생성" : "수정"} />

      <div className="space-y-3">
        <ComponentCard title="사전설정 정보" titleIcon={<DocsIcon />}>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            <div>
              <Label>사전설정명</Label>
              <Input 
                type="text" 
                placeholder="사전설정명을 입력하세요" 
                value={goodsTemplate?.goods_template_name || ""} 
                onChange={(e) => setGoodsTemplate({ ...goodsTemplate, goods_template_name: e.target.value } as GoodsTemplateData)} 
              />
            </div>
            {!isNewTemplate && goodsTemplate?.goods_template_reg_time && (
              <div>
                <Label>등록일시</Label>
                <Input 
                  type="text" 
                  value={convertDateTime2(goodsTemplate?.goods_template_reg_time) || ""}
                  disabled
                />
              </div>
            )}
          </div>
        </ComponentCard>

        <ComponentCard title="사전설정 목록 설정" titleIcon={<GridIcon />}>
          <DeviceGoodsList
            deviceGoodsList={deviceGoods}
            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 className="flex items-center gap-5">
              <Button size="sm" variant="primary" onClick={handleSave}>
                {isNewTemplate ? "생성" : "수정"}
              </Button>
              <Button size="sm" variant="outline" onClick={handleCancel}>
                취소
              </Button>
            </div>
          </div>
        </ComponentCard>
      </div>
    </div>
  );
}