import { state } from '../../core/state';
import { openHwModal } from '../../components/Modal/HWModal';
import { calculateAssetAge, normalizeDate } from '../../core/utils';
import { ASSET_SCHEMA } from '../../core/schema';

declare var Chart: any;

export function renderHwDashboard(container: HTMLElement) {
  const allHw = state.masterData.hw || [];
  
  // 1. 데이터 가공
  let totalAge = 0;
  let countWithDate = 0;
  let over5YearsCount = 0;
  let latestAsset: any | null = null;
  let latestYear = 0;

  const ageGroups = { stable: 0, warning: 0, critical: 0 };
  const yearlyCount: Record<string, number> = {};

  allHw.forEach(a => {
    const pDate = a[ASSET_SCHEMA.PURCHASE_DATE.key];
    if (!pDate) return;

    const age = calculateAssetAge(pDate);
    totalAge += age;
    countWithDate++;

    // 노후도 분류
    if (age >= 5) {
      over5YearsCount++;
      ageGroups.critical++;
    } else if (age >= 3) {
      ageGroups.warning++;
    } else {
      ageGroups.stable++;
    }

    // 연도별 도입 현황 추출
    const year = normalizeDate(pDate).split('-')[0];
    if (year && year.length === 4) {
      yearlyCount[year] = (yearlyCount[year] || 0) + 1;
      const yNum = parseInt(year);
      if (yNum > latestYear) {
        latestYear = yNum;
        latestAsset = a;
      }
    }
  });

  const avgAge = countWithDate > 0 ? (totalAge / countWithDate).toFixed(1) : '0';
  const over5Rate = allHw.length > 0 ? Math.round((over5YearsCount / allHw.length) * 100) : 0;
  
  // 교체 시급 대상 TOP 10 (오래된 순)
  const criticalList = [...allHw]
    .filter(a => a[ASSET_SCHEMA.PURCHASE_DATE.key])
    .sort((a, b) => {
      const dateA = new Date(normalizeDate(a[ASSET_SCHEMA.PURCHASE_DATE.key])).getTime();
      const dateB = new Date(normalizeDate(b[ASSET_SCHEMA.PURCHASE_DATE.key])).getTime();
      return dateA - dateB;
    })
    .slice(0, 10);

  // 2. UI 렌더링
  container.innerHTML = `
    <div class="view-container">
      <div class="dashboard-header-stats" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 1.5rem; margin-bottom: 2rem;">
        <div class="dashboard-card" style="min-height:auto;">
          <span style="font-size:1rem; font-weight:700; color:var(--text-main);">전체 평균 사용 연수</span>
          <div style="font-size: 0.8125rem; color:var(--text-muted); margin-bottom: 1rem;">전체 자산 기준 (권장 4.5년)</div>
          <div style="font-size: 2rem; font-weight:700; color:var(--dash-primary);">${avgAge}년</div>
          <div style="width: 100%; height: 4px; background-color: var(--border-color); border-radius: 2px; overflow: hidden; margin-top: 0.5rem;">
            <div style="width: ${Math.min(100, (Number(avgAge)/4.5)*100)}%; height: 100%; background-color: var(--dash-primary);"></div>
          </div>
        </div>
        <div class="dashboard-card" style="min-height:auto;">
          <span style="font-size:1rem; font-weight:700; color:var(--text-main);">5년 이상 노후 자산 비율</span>
          <div style="font-size: 0.8125rem; color:var(--text-muted); margin-bottom: 1rem;">총 ${over5YearsCount}대 해당</div>
          <div style="font-size: 2rem; font-weight:700; color:${over5Rate >= 20 ? 'var(--dash-danger)' : 'var(--dash-primary)'};">${over5Rate}%</div>
          <div style="width: 100%; height: 4px; background-color: var(--border-color); border-radius: 2px; overflow: hidden; margin-top: 0.5rem;">
            <div style="width: ${over5Rate}%; height: 100%; background-color: ${over5Rate >= 20 ? 'var(--dash-danger)' : 'var(--dash-primary)'};"></div>
          </div>
        </div>
        <div class="dashboard-card" style="min-height:auto;">
          <span style="font-size:1rem; font-weight:700; color:var(--text-main);">최신 도입 모델 (${latestYear}년)</span>
          <div style="font-size: 0.8125rem; color:var(--text-muted); margin-bottom: 1rem;">자산번호: ${latestAsset ? latestAsset[ASSET_SCHEMA.ASSET_CODE.key] : '-'}</div>
          <div style="font-size: 1.25rem; font-weight:700; color:var(--primary-color); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; height: 3rem; display: flex; align-items: center;" title="${latestAsset ? latestAsset[ASSET_SCHEMA.MODEL_NAME.key] : '정보 없음'}">
            ${latestAsset ? (latestAsset[ASSET_SCHEMA.MODEL_NAME.key] || latestAsset[ASSET_SCHEMA.ASSET_NAME.key] || '정보 없음') : '정보 없음'}
          </div>
          <div style="width: 100%; height: 4px; background-color: var(--primary-color); border-radius: 2px; margin-top: 0.5rem;"></div>
        </div>
      </div>

      <div class="dashboard-layout-2col" style="margin-bottom: 2rem;">
        <div class="dashboard-card">
          <h4 class="card-title">자산 노후도 분포</h4>
          <div style="height: 250px;"><canvas id="chart-aging-dist"></canvas></div>
        </div>
        <div class="dashboard-card">
          <h4 class="card-title">연도별 자산 도입 추이</h4>
          <div style="height: 250px;"><canvas id="chart-purchase-trend"></canvas></div>
        </div>
      </div>

      <h3 class="dashboard-section-title">⚠️ 교체 검토 대상 (가장 오래된 자산 TOP 10)</h3>
      <div class="table-container" style="background: white; border-radius: 8px; border: 1px solid var(--border-color);">
        <table>
          <thead>
            <tr>
              <th style="text-align:center;">순위</th>
              <th style="text-align:center;">자산번호</th>
              <th style="text-align:center;">유형</th>
              <th style="text-align:center;">모델명</th>
              <th style="text-align:center;">담당자</th>
              <th style="text-align:center;">구매일자</th>
              <th style="text-align:center;">연령</th>
            </tr>
          </thead>
          <tbody>
            ${criticalList.map((a, i) => {
              const pDate = a[ASSET_SCHEMA.PURCHASE_DATE.key];
              const age = calculateAssetAge(pDate);
              return `
              <tr class="clickable-row" data-id="${a.id}" style="cursor:pointer;">
                <td style="text-align:center; font-weight:600; color:var(--text-muted)">${i + 1}</td>
                <td style="text-align:center;">${a[ASSET_SCHEMA.ASSET_CODE.key] || '-'}</td>
                <td style="text-align:center;"><span class="badge-type">${a[ASSET_SCHEMA.ASSET_TYPE.key] || a.category || ''}</span></td>
                <td>${a[ASSET_SCHEMA.MODEL_NAME.key] || a[ASSET_SCHEMA.ASSET_NAME.key] || '-'}</td>
                <td style="text-align:center;">${a[ASSET_SCHEMA.MANAGER_MAIN.key] || '-'}</td>
                <td style="text-align:center;">${pDate || '-'}</td>
                <td style="text-align:center;"><strong style="color:${age >= 5 ? 'var(--danger)' : 'inherit'}">${age}년</strong></td>
              </tr>
              `;
            }).join('')}
          </tbody>
        </table>
      </div>
    </div>
  `;

  // 3. 차트 초기화
  setTimeout(() => {
    initAgingCharts(ageGroups, yearlyCount);
    
    // 행 클릭 이벤트 바인딩
    container.querySelectorAll('.clickable-row').forEach(row => {
      row.addEventListener('click', () => {
        const id = row.getAttribute('data-id');
        const asset = allHw.find(h => h.id === id);
        if (asset) openHwModal(asset, 'view');
      });
    });
  }, 100);
}

function initAgingCharts(ageGroups: any, yearlyCount: Record<string, number>) {
  const agingCtx = document.getElementById('chart-aging-dist') as HTMLCanvasElement;
  if (agingCtx && typeof Chart !== 'undefined') {
    new Chart(agingCtx, {
      type: 'doughnut',
      data: {
        labels: ['안정 (3년 미만)', '주의 (3~5년)', '위험 (5년 이상)'],
        datasets: [{
          data: [ageGroups.stable, ageGroups.warning, ageGroups.critical],
          backgroundColor: ['#1E5149', '#9CA3AF', '#E11D48'],
          borderWidth: 0
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { position: 'right' } },
        cutout: '70%'
      }
    });
  }

  const trendCtx = document.getElementById('chart-purchase-trend') as HTMLCanvasElement;
  if (trendCtx && typeof Chart !== 'undefined') {
    const years = Object.keys(yearlyCount).sort();
    new Chart(trendCtx, {
      type: 'bar',
      data: {
        labels: years,
        datasets: [{
          label: '도입 수량',
          data: years.map(y => yearlyCount[y]),
          backgroundColor: '#1E5149',
          borderRadius: 4
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: { beginAtZero: true, ticks: { stepSize: 1 } },
          x: { grid: { display: false } }
        }
      }
    });
  }
}
