"use client";

import { useState, useEffect, useCallback } from "react";
import type { AllMonitoringSettings, MonitoringSettingsMap } from "@/types/monitoringSettings";
import {
  DEFAULT_ALL_SETTINGS,
  DEFAULT_PRODUCTION_SETTINGS,
  DEFAULT_EQUIPMENT_SETTINGS,
  DEFAULT_QUALITY_SETTINGS,
} from "@/lib/monitoringSettingsDefaults";
import useAuth from "@/hooks/useAuth";

const STORAGE_KEY_PREFIX = "monitoring_settings_";

function getStorageKey(companyCode: string) {
  return `${STORAGE_KEY_PREFIX}${companyCode}`;
}

function loadFromStorage(companyCode: string): AllMonitoringSettings {
  try {
    const raw = localStorage.getItem(getStorageKey(companyCode));
    if (!raw) return structuredClone(DEFAULT_ALL_SETTINGS);
    const parsed = JSON.parse(raw);
    // 기존 저장값과 기본값 병합 (새 필드 추가 대응)
    return {
      production: {
        ...DEFAULT_PRODUCTION_SETTINGS,
        ...parsed.production,
        displayFields: { ...DEFAULT_PRODUCTION_SETTINGS.displayFields, ...parsed.production?.displayFields },
      },
      equipment: {
        ...DEFAULT_EQUIPMENT_SETTINGS,
        ...parsed.equipment,
        displayFields: { ...DEFAULT_EQUIPMENT_SETTINGS.displayFields, ...parsed.equipment?.displayFields },
      },
      quality: {
        ...DEFAULT_QUALITY_SETTINGS,
        ...parsed.quality,
        inspectionTypes: { ...DEFAULT_QUALITY_SETTINGS.inspectionTypes, ...parsed.quality?.inspectionTypes },
        tableColumns: { ...DEFAULT_QUALITY_SETTINGS.tableColumns, ...parsed.quality?.tableColumns },
      },
    };
  } catch {
    return structuredClone(DEFAULT_ALL_SETTINGS);
  }
}

function saveToStorage(companyCode: string, settings: AllMonitoringSettings) {
  try {
    localStorage.setItem(getStorageKey(companyCode), JSON.stringify(settings));
  } catch {
    // localStorage 용량 초과 등 무시
  }
}

// ─── 개별 모니터링 페이지용 훅 ──────────────────────────────

export function useMonitoringSettings<T extends keyof MonitoringSettingsMap>(
  monitorType: T,
): {
  settings: MonitoringSettingsMap[T];
  isLoaded: boolean;
} {
  const { companyCode } = useAuth();
  const defaults = {
    production: DEFAULT_PRODUCTION_SETTINGS,
    equipment: DEFAULT_EQUIPMENT_SETTINGS,
    quality: DEFAULT_QUALITY_SETTINGS,
  }[monitorType] as MonitoringSettingsMap[T];

  const [settings, setSettings] = useState<MonitoringSettingsMap[T]>(defaults);
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    if (!companyCode) return;
    const all = loadFromStorage(companyCode);
    setSettings(all[monitorType] as MonitoringSettingsMap[T]);
    setIsLoaded(true);
  }, [companyCode, monitorType]);

  // 다른 탭에서 설정 변경 시 동기화
  useEffect(() => {
    if (!companyCode) return;
    const handler = (e: StorageEvent) => {
      if (e.key === getStorageKey(companyCode) && e.newValue) {
        try {
          const parsed = JSON.parse(e.newValue);
          setSettings(parsed[monitorType]);
        } catch {
          // 파싱 실패 무시
        }
      }
    };
    window.addEventListener("storage", handler);
    return () => window.removeEventListener("storage", handler);
  }, [companyCode, monitorType]);

  return { settings, isLoaded };
}

// ─── 설정 페이지용 훅 ───────────────────────────────────────

export function useMonitoringSettingsAll(): {
  settings: AllMonitoringSettings;
  setSettings: React.Dispatch<React.SetStateAction<AllMonitoringSettings>>;
  saveAll: () => void;
  resetAll: () => void;
  isLoaded: boolean;
} {
  const { companyCode } = useAuth();
  const [settings, setSettings] = useState<AllMonitoringSettings>(structuredClone(DEFAULT_ALL_SETTINGS));
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    if (!companyCode) return;
    setSettings(loadFromStorage(companyCode));
    setIsLoaded(true);
  }, [companyCode]);

  const saveAll = useCallback(() => {
    if (!companyCode) return;
    saveToStorage(companyCode, settings);
  }, [companyCode, settings]);

  const resetAll = useCallback(() => {
    const defaults = structuredClone(DEFAULT_ALL_SETTINGS);
    setSettings(defaults);
    if (companyCode) {
      saveToStorage(companyCode, defaults);
    }
  }, [companyCode]);

  return { settings, setSettings, saveAll, resetAll, isLoaded };
}
