import { create } from 'zustand';
import { getWallCpeOfficial as getWallCpe, getRoofCpeOfficial as getRoofCpe } from '../lib/coefficients';
import { useWindStore } from './appStore';
import type { WallCoefficients, RoofCoefficients } from '../lib/coefficients';

interface GalpaoState {
  // Dimensões do Galpão Retangular
  width: number;
  length: number;
  height: number;
  roofPitch: number;

  // Saídas calculadas (Cpe)
  wallCpe: WallCoefficients;
  roofCpe: RoofCoefficients;

  // Ações
  setWidth: (val: number) => void;
  setLength: (val: number) => void;
  setHeight: (val: number) => void;
  setRoofPitch: (val: number) => void;
  updateCoefficients: () => void;
}

const initWidth = 15;
const initLength = 30;
const initHeight = 6;
const initPitch = 10;
const initAngle: 0 | 90 = 0;

export const useGalpaoStore = create<GalpaoState>((set, get) => ({
  width: initWidth,
  length: initLength,
  height: initHeight,
  roofPitch: initPitch,
  wallCpe: getWallCpe(initLength, initWidth, initHeight, initAngle),
  roofCpe: getRoofCpe(initLength, initWidth, initHeight, initPitch, initAngle),

  updateCoefficients: () => {
    const { length, width, height, roofPitch } = get();
    const windAngle = useWindStore.getState().windAngle;
    set({
      wallCpe: getWallCpe(length, width, height, windAngle),
      roofCpe: getRoofCpe(length, width, height, roofPitch, windAngle),
    });
  },

  setWidth: (val) => {
    set({ width: val });
    get().updateCoefficients();
    useWindStore.getState().setDimensions(Math.max(val, get().length), get().height);
  },
  setLength: (val) => {
    set({ length: val });
    get().updateCoefficients();
    useWindStore.getState().setDimensions(Math.max(get().width, val), get().height);
  },
  setHeight: (val) => {
    set({ height: val });
    get().updateCoefficients();
    useWindStore.getState().setDimensions(Math.max(get().width, get().length), val);
  },
  setRoofPitch: (val) => {
    set({ roofPitch: val });
    get().updateCoefficients();
  },
}));