import { useGalpaoStore } from '../store/galpaoStore';
import { useWindStore } from '../store/appStore';
import {
  getColumnLinearLoads,
  getRoofLinearLoads,
  getAllPillarBaseReactions,
  getPillarBaseMoment,
} from './line-loads';

export function exportGalpaoToCSV() {
  const galpao = useGalpaoStore.getState();
  const wind = useWindStore.getState();

  const q = wind.q;
  const cpi = wind.cpi;

  const pressure = (cpe: number) => (q * (cpe - cpi)).toFixed(3);

  const lines: string[][] = [
    ['--- Dados do Projeto ---'],
    ['Velocidade Básica V0 (m/s)', wind.v0.toString()],
    ['Fator S1', wind.s1.toString()],
    ['Fator S2', wind.s2.toString()],
    ['Fator S3', wind.s3.toString()],
    ['Velocidade Característica Vk (m/s)', wind.vk.toFixed(2)],
    ['Pressão Dinâmica q (kN/m2)', q.toFixed(4)],
    [],
    ['--- Geometria ---'],
    ['Largura b (m)', galpao.width.toString()],
    ['Comprimento a (m)', galpao.length.toString()],
    ['Altura h (m)', galpao.height.toString()],
    ['Inclinação Telhado (graus)', galpao.roofPitch.toString()],
    ['Direção do Vento (graus)', wind.windAngle.toString()],
    [],
    ['--- Pressão Interna ---'],
    ['Caso de Permeabilidade', wind.permeabilityCase],
    ['Coeficiente Cpi', cpi.toFixed(2)],
    [],
    ['--- Coeficientes de Pressão (Cpe), Cpi e Pressão Líquida (kN/m2) ---'],
    ['Face', 'Região', 'Cpe', 'Cpi', 'p = q·(Cpe − Cpi)'],
  ];

  Object.entries(galpao.wallCpe).forEach(([face, cpe]) => {
    lines.push([`Parede`, face, cpe.toString(), cpi.toFixed(2), pressure(cpe as number)]);
  });

  Object.entries(galpao.roofCpe).forEach(([face, cpe]) => {
    lines.push([`Telhado`, face, cpe.toString(), cpi.toFixed(2), pressure(cpe as number)]);
  });

  const FRAME_SPACING_DEFAULT = 6.0;
  const PURLIN_SPACING_DEFAULT = 1.5;
  const columnLoads = getColumnLinearLoads(cpi, q, galpao.wallCpe, FRAME_SPACING_DEFAULT, wind.windAngle);
  const roofLoads = getRoofLinearLoads(cpi, q, galpao.roofCpe, PURLIN_SPACING_DEFAULT, galpao.roofPitch);
  const reactions = getAllPillarBaseReactions(columnLoads, galpao.height);

  lines.push([]);
  lines.push(['--- Cargas Lineares M9.2 ---']);
  lines.push(['Espaçamento entre pórticos (m)', FRAME_SPACING_DEFAULT.toString()]);
  lines.push(['Espaçamento entre terças (m)', PURLIN_SPACING_DEFAULT.toString()]);
  lines.push([]);
  lines.push(['Cargas nos pilares [kN/m] (sinal: + empuxo, - sucção)']);
  lines.push(['Pilar', 'Cpe', 'Cpi', 'p [kN/m²]', 'w [kN/m]']);
  lines.push(['Barlavento', galpao.wallCpe.A.toFixed(2), cpi.toFixed(2),
    pressure(galpao.wallCpe.A), columnLoads.windward.toFixed(3)]);
  lines.push(['Sotavento', galpao.wallCpe.D.toFixed(2), cpi.toFixed(2),
    pressure(galpao.wallCpe.D), columnLoads.leeward.toFixed(3)]);
  lines.push(['Lateral A', galpao.wallCpe.B.toFixed(2), cpi.toFixed(2),
    pressure(galpao.wallCpe.B), columnLoads.sideA.toFixed(3)]);
  lines.push(['Lateral B', galpao.wallCpe.C.toFixed(2), cpi.toFixed(2),
    pressure(galpao.wallCpe.C), columnLoads.sideB.toFixed(3)]);
  lines.push([]);
  lines.push(['Cargas nas terças [kN/m] (inclinação aplicada)']);
  lines.push(['Zona', 'Cpe', 'w [kN/m]']);
  lines.push(['E', galpao.roofCpe.E.toFixed(2), roofLoads.E.toFixed(3)]);
  lines.push(['F', galpao.roofCpe.F.toFixed(2), roofLoads.F.toFixed(3)]);
  lines.push(['G', galpao.roofCpe.G.toFixed(2), roofLoads.G.toFixed(3)]);
  lines.push(['H', galpao.roofCpe.H.toFixed(2), roofLoads.H.toFixed(3)]);
  lines.push(['I', galpao.roofCpe.I.toFixed(2), roofLoads.I.toFixed(3)]);
  lines.push(['J', galpao.roofCpe.J.toFixed(2), roofLoads.J.toFixed(3)]);
  lines.push([]);
  lines.push(['Reações na base dos pilares [kN] e momentos [kN·m]']);
  lines.push(['Pilar', 'V_base [kN]', 'M_base [kN·m]']);
  lines.push(['Barlavento', reactions.windward.toFixed(3),
    getPillarBaseMoment(columnLoads.windward, galpao.height).toFixed(3)]);
  lines.push(['Sotavento', reactions.leeward.toFixed(3),
    getPillarBaseMoment(columnLoads.leeward, galpao.height).toFixed(3)]);
  lines.push(['Lateral A', reactions.sideA.toFixed(3),
    getPillarBaseMoment(columnLoads.sideA, galpao.height).toFixed(3)]);
  lines.push(['Lateral B', reactions.sideB.toFixed(3),
    getPillarBaseMoment(columnLoads.sideB, galpao.height).toFixed(3)]);
  lines.push([]);
  lines.push(['Reação total', reactions.total.toFixed(3), '']);

  const csvContent = lines.map((row) => row.join(',')).join('\n');

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);

  const link = document.createElement('a');
  link.setAttribute('href', url);
  link.setAttribute('download', 'relatorio_vento_nbr6123.csv');
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}