"use client";

import React, { useEffect, useRef } from "react";
import * as d3 from "d3";
import { ChartConfig, ChartData } from "../types";

interface StackedBarChartProps {
  data: ChartData;
  config: ChartConfig;
  width?: number;
  height?: number;
}

/**
 * D3 누적 막대 차트 컴포넌트
 */
export function StackedBarChart({ data, config, width = 600, height = 400 }: StackedBarChartProps) {
  const svgRef = useRef<SVGSVGElement>(null);

  useEffect(() => {
    if (!svgRef.current || !data.labels.length || !data.datasets.length) return;

    const svg = d3.select(svgRef.current);
    svg.selectAll("*").remove();

    const margin = { top: 40, right: 80, bottom: 80, left: 60 };
    const chartWidth = width - margin.left - margin.right;
    const chartHeight = height - margin.top - margin.bottom;

    const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);

    // 데이터 변환 (스택 데이터 생성)
    const stackData = data.labels.map((label, i) => {
      const obj: any = { label };
      data.datasets.forEach((dataset, j) => {
        obj[`series${j}`] = dataset.data[i];
      });
      return obj;
    });

    const series = data.datasets.map((_, i) => `series${i}`);

    // 스택 레이아웃
    const stack = d3.stack().keys(series);
    const stackedData = stack(stackData as any);

    // X축 스케일
    const xScale = d3.scaleBand().domain(data.labels).range([0, chartWidth]).padding(0.3);

    // Y축 스케일
    const maxValue =
      config.stackMode === "percent" ? 100 : d3.max(stackedData[stackedData.length - 1], (d) => d[1] as number) || 0;

    const yScale = d3
      .scaleLinear()
      .domain([0, maxValue * 1.1])
      .range([chartHeight, 0])
      .nice();

    // X축 그리기
    g.append("g")
      .attr("transform", `translate(0,${chartHeight})`)
      .call(d3.axisBottom(xScale))
      .selectAll("text")
      .attr("transform", "rotate(-45)")
      .style("text-anchor", "end")
      .style("font-size", "12px");

    // Y축 그리기 (값 표시 제거)
    g.append("g")
      .call(d3.axisLeft(yScale).tickFormat(() => ""))
      .style("font-size", "12px");

    // 그리드 라인 제거됨

    // 색상 팔레트
    const colors = config.colors || ["#3B82F6", "#EF4444", "#10B981", "#F59E0B"];

    // 퍼센트 모드인 경우 데이터 정규화
    if (config.stackMode === "percent") {
      stackData.forEach((label) => {
        const total = d3.sum(series.map((s) => (label as any)[s]));
        series.forEach((s) => {
          (label as any)[s] = total > 0 ? ((label as any)[s] / total) * 100 : 0;
        });
      });
    }

    // 누적 막대 그리기
    const layers = g
      .selectAll(".layer")
      .data(stackedData)
      .enter()
      .append("g")
      .attr("class", "layer")
      .attr("fill", (_, i) => data.datasets[i].color || colors[i % colors.length]);

    const bars = layers
      .selectAll("rect")
      .data((d) => d)
      .enter()
      .append("rect")
      .attr("x", (d) => xScale((d.data as any).label) || 0)
      .attr("y", chartHeight)
      .attr("width", xScale.bandwidth())
      .attr("height", 0)
      .attr("rx", 4);

    // 애니메이션
    if (config.enableAnimation !== false) {
      bars
        .transition()
        .duration(config.animationDuration || 750)
        .attr("y", (d) => yScale(d[1] as number))
        .attr("height", (d) => yScale(d[0] as number) - yScale(d[1] as number));
    } else {
      bars
        .attr("y", (d) => yScale(d[1] as number))
        .attr("height", (d) => yScale(d[0] as number) - yScale(d[1] as number));
    }

    // 각 세그먼트에 값 표시
    layers.each(function (layerData, layerIndex) {
      d3.select(this)
        .selectAll("text")
        .data(layerData)
        .enter()
        .append("text")
        .attr("x", (d) => (xScale((d.data as any).label) || 0) + xScale.bandwidth() / 2)
        .attr("y", (d) => {
          const segmentHeight = yScale(d[0] as number) - yScale(d[1] as number);
          const segmentMiddle = yScale(d[1] as number) + segmentHeight / 2;
          return segmentMiddle;
        })
        .attr("text-anchor", "middle")
        .attr("dominant-baseline", "middle")
        .style("font-size", "11px")
        .style("font-weight", "500")
        .style("fill", "white")
        .style("pointer-events", "none")
        .text((d) => {
          const value = (d[1] as number) - (d[0] as number);
          if (config.stackMode === "percent") {
            return value > 5 ? `${value.toFixed(0)}%` : "";
          }
          return value > 0 ? value.toLocaleString() : "";
        })
        .style("opacity", 0);

      // 애니메이션 (라벨)
      if (config.enableAnimation !== false) {
        d3.select(this)
          .selectAll("text")
          .transition()
          .delay(config.animationDuration || 750)
          .duration(300)
          .style("opacity", 1);
      } else {
        d3.select(this).selectAll("text").style("opacity", 1);
      }
    });

    // 툴팁
    if (config.showTooltip !== false) {
      bars
        .on("mouseover", function (event, d) {
          d3.select(this).attr("opacity", 0.7);

          const seriesIndex = stackedData.findIndex((s) => s.includes(d as any));
          const value = (d[1] as number) - (d[0] as number);
          const label = data.datasets[seriesIndex].label;

          const [mouseX, mouseY] = d3.pointer(event, g.node());
          const tooltipText = `${label}: ${value.toFixed(config.stackMode === "percent" ? 1 : 0)}${config.stackMode === "percent" ? "%" : ""}`;

          const tooltip = g
            .append("g")
            .attr("class", "tooltip")
            .attr("transform", `translate(${mouseX},${mouseY - 10})`);

          const text = tooltip
            .append("text")
            .attr("text-anchor", "middle")
            .attr("fill", "white")
            .attr("font-size", "12px")
            .attr("dy", "-0.5em")
            .text(tooltipText);

          const bbox = (text.node() as SVGTextElement).getBBox();
          const padding = 8;

          tooltip
            .insert("rect", "text")
            .attr("x", bbox.x - padding)
            .attr("y", bbox.y - padding)
            .attr("width", bbox.width + padding * 2)
            .attr("height", bbox.height + padding * 2)
            .attr("fill", "rgba(0,0,0,0.85)")
            .attr("rx", 6);
        })
        .on("mouseout", function () {
          d3.select(this).attr("opacity", 1);
          g.selectAll(".tooltip").remove();
        });
    }

    // 차트 제목
    if (config.title) {
      svg
        .append("text")
        .attr("x", width / 2)
        .attr("y", 20)
        .attr("text-anchor", "middle")
        .style("font-size", "16px")
        .style("font-weight", "bold")
        .text(config.title);
    }

    // X축 라벨
    if (config.xAxisLabel) {
      svg
        .append("text")
        .attr("x", width / 2)
        .attr("y", height - 5)
        .attr("text-anchor", "middle")
        .style("font-size", "12px")
        .style("fill", "#666")
        .text(config.xAxisLabel);
    }

    // Y축 라벨
    if (config.yAxisLabel) {
      svg
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("x", -height / 2)
        .attr("y", 15)
        .attr("text-anchor", "middle")
        .style("font-size", "12px")
        .style("fill", "#666")
        .text(config.yAxisLabel);
    }

    // 범례 (차트 하단 중앙)
    if (config.showLegend !== false) {
      const legendItemWidth = 120;
      const totalLegendWidth = data.datasets.length * legendItemWidth;
      const legendStartX = (width - totalLegendWidth) / 2;
      
      const legend = svg
        .append("g")
        .attr("class", "legend")
        .attr("transform", `translate(${legendStartX}, ${height - 20})`);

      data.datasets.forEach((dataset, i) => {
        const legendItem = legend
          .append("g")
          .attr("transform", `translate(${i * legendItemWidth}, 0)`);

        legendItem
          .append("rect")
          .attr("width", 15)
          .attr("height", 15)
          .attr("fill", dataset.color || colors[i % colors.length])
          .attr("rx", 3);

        legendItem
          .append("text")
          .attr("x", 20)
          .attr("y", 12)
          .style("font-size", "12px")
          .style("fill", "#333")
          .text(dataset.label);
      });
    }
  }, [data, config, width, height]);

  return <svg ref={svgRef} width={width} height={height} style={{ fontFamily: "sans-serif" }} />;
}
