"use client";

import * as React from "react";
import dynamic from "next/dynamic";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { GenericData } from "./export-excel-form";
import * as GC from "@mescius/spread-sheets";
import { toast } from "sonner";
import { updateFormDataInDB } from "@/lib/forms/services";
import { Loader, Save } from "lucide-react";
import '@mescius/spread-sheets/styles/gc.spread.sheets.excel2016colorful.css';

// SpreadSheets를 동적으로 import (SSR 비활성화)
const SpreadSheets = dynamic(
  () => import("@mescius/spread-sheets-react").then(mod => mod.SpreadSheets),
  { 
    ssr: false,
    loading: () => (
      <div className="flex items-center justify-center h-full">
        <Loader className="mr-2 h-4 w-4 animate-spin" />
        Loading SpreadSheets...
      </div>
    )
  }
);

// 라이센스 키 설정을 클라이언트에서만 실행
if (typeof window !== 'undefined' && process.env.NEXT_PUBLIC_SPREAD_LICENSE) {
  GC.Spread.Sheets.LicenseKey = process.env.NEXT_PUBLIC_SPREAD_LICENSE;
}

interface TemplateItem {
  TMPL_ID: string;
  NAME: string;
  TMPL_TYPE: string;
  SPR_LST_SETUP: {
    ACT_SHEET: string;
    HIDN_SHEETS: Array<string>;
    CONTENT?: string;
    DATA_SHEETS: Array<{
      SHEET_NAME: string;
      REG_TYPE_ID: string;
      MAP_CELL_ATT: Array<{
        ATT_ID: string;
        IN: string;
      }>;
    }>;
  };
  GRD_LST_SETUP: {
    REG_TYPE_ID: string;
    SPR_ITM_IDS: Array<string>;
    ATTS: Array<{}>;
  };
  SPR_ITM_LST_SETUP: {
    ACT_SHEET: string;
    HIDN_SHEETS: Array<string>;
    CONTENT?: string;
    DATA_SHEETS: Array<{
      SHEET_NAME: string;
      REG_TYPE_ID: string;
      MAP_CELL_ATT: Array<{
        ATT_ID: string;
        IN: string;
      }>;
    }>;
  };
}

interface TemplateViewDialogProps {
  isOpen: boolean;
  onClose: () => void;
  templateData: TemplateItem[] | any;
  selectedRow?: GenericData; // SPR_ITM_LST_SETUP용
  tableData?: GenericData[]; // SPR_LST_SETUP용
  formCode: string;
  contractItemId: number;
  editableFieldsMap?: Map<string, string[]>;
  onUpdateSuccess?: (updatedValues: Record<string, any> | GenericData[]) => void;
}

export function TemplateViewDialog({
  isOpen,
  onClose,
  templateData,
  selectedRow,
  tableData = [],
  formCode,
  contractItemId,
  editableFieldsMap = new Map(),
  onUpdateSuccess
}: TemplateViewDialogProps) {
  const [hostStyle, setHostStyle] = React.useState({
    width: '100%',
    height: '100%'
  });

  const [isPending, setIsPending] = React.useState(false);
  const [hasChanges, setHasChanges] = React.useState(false);
  const [currentSpread, setCurrentSpread] = React.useState<any>(null);
  const [cellMappings, setCellMappings] = React.useState<Array<{attId: string, cellAddress: string, isEditable: boolean}>>([]);
  const [isClient, setIsClient] = React.useState(false);
  const [templateType, setTemplateType] = React.useState<'SPR_LST_SETUP' | 'SPR_ITM_LST_SETUP' | null>(null);

  // 클라이언트 사이드에서만 렌더링되도록 보장
  React.useEffect(() => {
    setIsClient(true);
  }, []);

  // 템플릿 데이터를 배열로 정규화하고 CONTENT가 있는 것 찾기
  const { normalizedTemplate, detectedTemplateType } = React.useMemo(() => {
    if (!templateData) return { normalizedTemplate: null, detectedTemplateType: null };
    
    let templates: TemplateItem[];
    if (Array.isArray(templateData)) {
      templates = templateData as TemplateItem[];
    } else {
      templates = [templateData as TemplateItem];
    }
    
    // CONTENT가 있는 템플릿 찾기
    for (const template of templates) {
      if (template.SPR_LST_SETUP?.CONTENT) {
        return { normalizedTemplate: template, detectedTemplateType: 'SPR_LST_SETUP' as const };
      }
      if (template.SPR_ITM_LST_SETUP?.CONTENT) {
        return { normalizedTemplate: template, detectedTemplateType: 'SPR_ITM_LST_SETUP' as const };
      }
    }
    
    return { normalizedTemplate: null, detectedTemplateType: null };
  }, [templateData]);

  // 템플릿 타입 설정
  React.useEffect(() => {
    setTemplateType(detectedTemplateType);
  }, [detectedTemplateType]);

  // 필드가 편집 가능한지 판별하는 함수
  const isFieldEditable = React.useCallback((attId: string) => {
    // TAG_NO와 TAG_DESC는 기본적으로 편집 가능
    if (attId === "TAG_NO" || attId === "TAG_DESC") {
      return true;
    }
    
    // SPR_ITM_LST_SETUP인 경우 selectedRow.shi 확인
    if (templateType === 'SPR_ITM_LST_SETUP' && selectedRow) {
      return selectedRow.shi !== true;
    }
    
    // SPR_LST_SETUP인 경우는 기본적으로 편집 가능 (개별 행의 shi 상태는 저장시 확인)
    return true;
  }, [templateType, selectedRow]);

  // 편집 가능한 필드 개수 계산
  const editableFieldsCount = React.useMemo(() => {
    return cellMappings.filter(m => m.isEditable).length;
  }, [cellMappings]);

  // 셀 주소를 행과 열로 변환하는 함수
  const parseCellAddress = (address: string): {row: number, col: number} | null => {
    if (!address || address.trim() === "") return null;
    
    const match = address.match(/^([A-Z]+)(\d+)$/);
    if (!match) return null;
    
    const [, colStr, rowStr] = match;
    
    let col = 0;
    for (let i = 0; i < colStr.length; i++) {
      col = col * 26 + (colStr.charCodeAt(i) - 65 + 1);
    }
    col -= 1;
    
    const row = parseInt(rowStr) - 1;
    
    return { row, col };
  };

  const initSpread = React.useCallback((spread: any) => {
    if (!spread || !normalizedTemplate) return;

    try {
      setCurrentSpread(spread);
      setHasChanges(false);

      // 템플릿 타입에 따라 CONTENT와 DATA_SHEETS 가져오기
      let contentJson = null;
      let dataSheets = null;
      
      if (templateType === 'SPR_LST_SETUP') {
        contentJson = normalizedTemplate.SPR_LST_SETUP.CONTENT;
        dataSheets = normalizedTemplate.SPR_LST_SETUP.DATA_SHEETS;
        console.log('Using SPR_LST_SETUP.CONTENT for template:', normalizedTemplate.NAME);
      } else if (templateType === 'SPR_ITM_LST_SETUP') {
        contentJson = normalizedTemplate.SPR_ITM_LST_SETUP.CONTENT;
        dataSheets = normalizedTemplate.SPR_ITM_LST_SETUP.DATA_SHEETS;
        console.log('Using SPR_ITM_LST_SETUP.CONTENT for template:', normalizedTemplate.NAME);
      }

      if (!contentJson) {
        console.warn('No CONTENT found in template:', normalizedTemplate.NAME);
        return;
      }

      console.log(`Loading template content for: ${normalizedTemplate.NAME} (Type: ${templateType})`);
      
      const jsonData = typeof contentJson === 'string' 
        ? JSON.parse(contentJson) 
        : contentJson;

      // 렌더링 일시 중단
      spread.suspendPaint();

      try {
        // fromJSON으로 템플릿 구조 로드
        spread.fromJSON(jsonData);

        // 활성 시트 가져오기
        const activeSheet = spread.getActiveSheet();
        
        // 시트 보호 먼저 해제
        activeSheet.options.isProtected = false;

        // MAP_CELL_ATT 정보를 사용해서 데이터 매핑
        if (dataSheets && dataSheets.length > 0) {
          const mappings: Array<{attId: string, cellAddress: string, isEditable: boolean}> = [];
          
          dataSheets.forEach(dataSheet => {
            if (dataSheet.MAP_CELL_ATT) {
              dataSheet.MAP_CELL_ATT.forEach(mapping => {
                const { ATT_ID, IN } = mapping;
                
                if (IN && IN.trim() !== "") {
                  const cellPos = parseCellAddress(IN);
                  if (cellPos) {
                    const isEditable = isFieldEditable(ATT_ID);
                    mappings.push({
                      attId: ATT_ID,
                      cellAddress: IN,
                      isEditable: isEditable
                    });
                    
                    // 템플릿 타입에 따라 다른 데이터 처리
                    if (templateType === 'SPR_ITM_LST_SETUP' && selectedRow) {
                      // 단일 행 처리 (기존 로직)
                      const cell = activeSheet.getCell(cellPos.row, cellPos.col);
                      const value = selectedRow[ATT_ID];
                      if (value !== undefined && value !== null) {
                        cell.value(value);
                      }
                      
                      // 스타일 적용
                      cell.locked(!isEditable);
                      const existingStyle = activeSheet.getStyle(cellPos.row, cellPos.col);
                      const newStyle = existingStyle ? Object.assign(new GC.Spread.Sheets.Style(), existingStyle) : new GC.Spread.Sheets.Style();
                      
                      if (isEditable) {
                        newStyle.backColor = "#f0fdf4";
                      } else {
                        newStyle.backColor = "#f9fafb";
                        newStyle.foreColor = "#6b7280";
                      }
                      
                      activeSheet.setStyle(cellPos.row, cellPos.col, newStyle);
                      
                    } else if (templateType === 'SPR_LST_SETUP' && tableData.length > 0) {
                      // 복수 행 처리 - 첫 번째 행부터 시작해서 아래로 채움
                      tableData.forEach((rowData, index) => {
                        const targetRow = cellPos.row + index;
                        const cell = activeSheet.getCell(targetRow, cellPos.col);
                        const value = rowData[ATT_ID];
                        
                        if (value !== undefined && value !== null) {
                          cell.value(value);
                        }
                        
                        // 개별 행의 편집 가능 여부 확인 (shi 필드 기준)
                        const rowEditable = isEditable && (rowData.shi !== true);
                        cell.locked(!rowEditable);
                        
                        // 스타일 적용
                        const existingStyle = activeSheet.getStyle(targetRow, cellPos.col);
                        const newStyle = existingStyle ? Object.assign(new GC.Spread.Sheets.Style(), existingStyle) : new GC.Spread.Sheets.Style();
                        
                        if (rowEditable) {
                          newStyle.backColor = "#f0fdf4";
                        } else {
                          newStyle.backColor = "#f9fafb";
                          newStyle.foreColor = "#6b7280";
                        }
                        
                        activeSheet.setStyle(targetRow, cellPos.col, newStyle);
                      });
                    }
                    
                    console.log(`Mapped ${ATT_ID} to cell ${IN} - ${isEditable ? 'Editable' : 'Read-only'}`);
                  }
                }
              });
            }
          });
          
          setCellMappings(mappings);
          
          // 시트 보호 설정
          activeSheet.options.isProtected = true;
          activeSheet.options.protectionOptions = {
            allowSelectLockedCells: true,
            allowSelectUnlockedCells: true,
            allowSort: false,
            allowFilter: false,
            allowEditObjects: false,
            allowResizeRows: false,
            allowResizeColumns: false
          };

          // 이벤트 리스너 추가
          activeSheet.bind(GC.Spread.Sheets.Events.CellChanged, (event: any, info: any) => {
            console.log('Cell changed:', info);
            setHasChanges(true);
          });

          activeSheet.bind(GC.Spread.Sheets.Events.ValueChanged, (event: any, info: any) => {
            console.log('Value changed:', info);
            setHasChanges(true);
          });

          // 편집 시작 시 읽기 전용 셀 확인
          activeSheet.bind(GC.Spread.Sheets.Events.EditStarting, (event: any, info: any) => {
            const mapping = mappings.find(m => {
              const cellPos = parseCellAddress(m.cellAddress);
              return cellPos && cellPos.row <= info.row && cellPos.col === info.col;
            });
            
            if (mapping) {
              // SPR_LST_SETUP인 경우 해당 행의 데이터에서 shi 확인
              if (templateType === 'SPR_LST_SETUP') {
                const dataRowIndex = info.row - parseCellAddress(mapping.cellAddress)!.row;
                const rowData = tableData[dataRowIndex];
                if (rowData && rowData.shi === true) {
                  toast.warning(`Row ${dataRowIndex + 1}: ${mapping.attId} field is read-only (SHI mode)`);
                  info.cancel = true;
                  return;
                }
              }
              
              if (!mapping.isEditable) {
                toast.warning(`${mapping.attId} field is read-only`);
                info.cancel = true;
              }
            }
          });
        }
      } finally {
        spread.resumePaint();
      }

    } catch (error) {
      console.error('Error initializing spread:', error);
      toast.error('Failed to load template');
      if (spread && spread.resumePaint) {
        spread.resumePaint();
      }
    }
  }, [normalizedTemplate, templateType, selectedRow, tableData, isFieldEditable]);

  // 변경사항 저장 함수
  const handleSaveChanges = React.useCallback(async () => {
    if (!currentSpread || !hasChanges) {
      toast.info("No changes to save");
      return;
    }

    try {
      setIsPending(true);

      const activeSheet = currentSpread.getActiveSheet();

      if (templateType === 'SPR_ITM_LST_SETUP' && selectedRow) {
        // 단일 행 저장 (기존 로직)
        const dataToSave = { ...selectedRow };

        cellMappings.forEach(mapping => {
          if (mapping.isEditable) {
            const cellPos = parseCellAddress(mapping.cellAddress);
            if (cellPos) {
              const cellValue = activeSheet.getValue(cellPos.row, cellPos.col);
              dataToSave[mapping.attId] = cellValue;
            }
          }
        });

        dataToSave.TAG_NO = selectedRow.TAG_NO;

        const { success, message } = await updateFormDataInDB(
          formCode,
          contractItemId,
          dataToSave
        );

        if (!success) {
          toast.error(message);
          return;
        }

        toast.success("Changes saved successfully!");
        onUpdateSuccess?.(dataToSave);

      } else if (templateType === 'SPR_LST_SETUP' && tableData.length > 0) {
        // 복수 행 저장
        const updatedRows: GenericData[] = [];
        let saveCount = 0;

        for (let i = 0; i < tableData.length; i++) {
          const originalRow = tableData[i];
          const dataToSave = { ...originalRow };
          let hasRowChanges = false;

          // 각 매핑에 대해 해당 행의 값 확인
          cellMappings.forEach(mapping => {
            if (mapping.isEditable && originalRow.shi !== true) { // shi가 true인 행은 편집 불가
              const cellPos = parseCellAddress(mapping.cellAddress);
              if (cellPos) {
                const targetRow = cellPos.row + i;
                const cellValue = activeSheet.getValue(targetRow, cellPos.col);
                
                // 값이 변경되었는지 확인
                if (cellValue !== originalRow[mapping.attId]) {
                  dataToSave[mapping.attId] = cellValue;
                  hasRowChanges = true;
                }
              }
            }
          });

          // 변경사항이 있는 행만 저장
          if (hasRowChanges) {
            dataToSave.TAG_NO = originalRow.TAG_NO; // TAG_NO는 절대 변경되지 않도록

            const { success } = await updateFormDataInDB(
              formCode,
              contractItemId,
              dataToSave
            );

            if (success) {
              updatedRows.push(dataToSave);
              saveCount++;
            }
          } else {
            updatedRows.push(originalRow); // 변경사항이 없으면 원본 유지
          }
        }

        if (saveCount > 0) {
          toast.success(`${saveCount} rows saved successfully!`);
          onUpdateSuccess?.(updatedRows);
        } else {
          toast.info("No changes to save");
        }
      }

      setHasChanges(false);

    } catch (error) {
      console.error("Error saving changes:", error);
      toast.error("An unexpected error occurred while saving");
    } finally {
      setIsPending(false);
    }
  }, [currentSpread, hasChanges, templateType, selectedRow, tableData, formCode, contractItemId, onUpdateSuccess, cellMappings]);

  if (!isOpen) return null;

  // 데이터 유효성 검사
  const isDataValid = templateType === 'SPR_ITM_LST_SETUP' ? !!selectedRow : tableData.length > 0;
  const dataCount = templateType === 'SPR_ITM_LST_SETUP' ? 1 : tableData.length;

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent 
        className="w-[80%] max-w-none h-[80vh] flex flex-col" 
        style={{maxWidth:"80vw"}}
      >
        <DialogHeader className="flex-shrink-0">
          <DialogTitle>SEDP Template - {formCode}</DialogTitle>
          <DialogDescription>
            {templateType && (
              <span className="font-medium text-blue-600">
                Template Type: {templateType === 'SPR_LST_SETUP' ? 'List View' : 'Item View'}
              </span>
            )}
            {templateType === 'SPR_ITM_LST_SETUP' && selectedRow && (
              <span className="ml-2">• Selected TAG_NO: {selectedRow.TAG_NO || 'N/A'}</span>
            )}
            {templateType === 'SPR_LST_SETUP' && (
              <span className="ml-2">• {dataCount} rows</span>
            )}
            {hasChanges && (
              <span className="ml-2 text-orange-600 font-medium">
                • Unsaved changes
              </span>
            )}
            <br />
            <div className="flex items-center gap-4 mt-2">
              <span className="text-xs text-muted-foreground">
                <span className="inline-block w-3 h-3 bg-green-100 border border-green-400 mr-1"></span>
                Editable fields
              </span>
              <span className="text-xs text-muted-foreground">
                <span className="inline-block w-3 h-3 bg-gray-100 border border-gray-300 mr-1"></span>
                Read-only fields
              </span>
              {cellMappings.length > 0 && (
                <span className="text-xs text-blue-600">
                  {editableFieldsCount} of {cellMappings.length} fields editable
                </span>
              )}
            </div>
          </DialogDescription>
        </DialogHeader>
        
        {/* SpreadSheets 컴포넌트 영역 */}
        <div className="flex-1 overflow-hidden">
          {normalizedTemplate && isClient && isDataValid ? (
            <SpreadSheets 
              key={`${templateType}-${normalizedTemplate.TMPL_ID}`}
              workbookInitialized={initSpread}
              hostStyle={hostStyle}
            />
          ) : (
            <div className="flex items-center justify-center h-full text-muted-foreground">
              {!isClient ? (
                <>
                  <Loader className="mr-2 h-4 w-4 animate-spin" />
                  Loading...
                </>
              ) : !normalizedTemplate ? (
                "No template available"
              ) : !isDataValid ? (
                `No ${templateType === 'SPR_ITM_LST_SETUP' ? 'selected row' : 'data'} available`
              ) : (
                "Template not ready"
              )}
            </div>
          )}
        </div>

        <DialogFooter className="flex-shrink-0">
          <Button variant="outline" onClick={onClose}>
            Close
          </Button>
          
          {hasChanges && (
            <Button 
              variant="default" 
              onClick={handleSaveChanges}
              disabled={isPending}
            >
              {isPending ? (
                <>
                  <Loader className="mr-2 h-4 w-4 animate-spin" />
                  Saving...
                </>
              ) : (
                <>
                  <Save className="mr-2 h-4 w-4" />
                  Save Changes
                </>
              )}
            </Button>
          )}
          
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}