import React from "react";
import { View, Text, StyleSheet } from "react-native";
import { HistoryPoint } from "../services/api";

interface BarChartProps {
  history: HistoryPoint[];
}

const GRADE_COLORS = {
  A:  "#16a34a",
  B:  "#d97706",
  C:  "#dc2626",
  TL: "#6b7280",
};

export default function BarChart({ history }: BarChartProps) {
  if (!history?.length) return null;

  const show = history.slice(-5);
  const maxVal = Math.max(...show.flatMap((h) => [h.A, h.B, h.C, h.TL ?? 0]), 1);
  const rawMax = Math.max(...show.flatMap((h) => [h.A, h.B, h.C, h.TL ?? 0]), 1);
  const niceMax = Math.ceil(rawMax / 10) * 10;

  const ySteps = [
    niceMax,
    niceMax * 0.75,
    niceMax * 0.5,
    niceMax * 0.25,
    0,
  ];

  return (
    <View style={styles.container}>
      {/* Y Vertical */}
      <View style={styles.yAxisRow}>
        <View style={styles.yAxis}>
          {/* {[100, 75, 50, 25, 0].map((v) => ( */}
          {ySteps.map((v, i) => (
            // <Text key={v} style={styles.yLabel}>{v}</Text>
            <Text key={i} style={styles.yLabel}>{Math.round(v)}</Text>
          ))}
        </View>

        {/* Chart area */}
        <View style={styles.chartArea}>
          {ySteps.map((_, i) => (
            <View
              key={i}
              style={[
                styles.gridLine,
                {
                  bottom: `${(i / (ySteps.length - 1)) * 100}%`,
                },
              ]}
            />
          ))}

          {/* Bars */}
          <View style={styles.chartRow}>
            {show.map((item, i) => (
              <View key={i} style={styles.barGroup}>
                <View style={styles.barsContainer}>
                  {(["A", "B", "C", "TL"] as const).map((g) => {
                    const val = item[g] ?? 0;
                    // const heightPct = Math.max(2, (val / maxVal) * 100);
                    const heightPct = Math.max(2, (val / niceMax) * 100);
                    return (
                      <View key={g} style={styles.barWrapper}>
                        <Text style={[styles.barValue, { color: GRADE_COLORS[g] }]}>
                          {val > 0 ? val : ""}
                        </Text>
                        <View
                          style={[
                            styles.bar,
                            {
                              height: (heightPct / 100) * 160,
                              backgroundColor: GRADE_COLORS[g],
                            },
                          ]}
                        />
                      </View>
                    );
                  })}
                </View>
                <Text style={styles.timeLabel}>{item.time}</Text>
              </View>
            ))}
          </View>
        </View>
      </View>

      {/* Legend */}
      <View style={styles.legend}>
        {(["A", "B", "C", "TL"] as const).map((g) => (
          <View key={g} style={styles.legendItem}>
            <View style={[styles.legendDot, { backgroundColor: GRADE_COLORS[g] }]} />
            <Text style={styles.legendText}>
              {g === "TL" ? "Tidak Layak" : `Grade ${g}`}
            </Text>
          </View>
        ))}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: 8,
    paddingTop: 8,
  },

  /* Y-axis + chart side-by-side */
  yAxisRow: {
    flexDirection: "row",
    alignItems: "flex-end",
  },
  yAxis: {
    width: 28,
    height: 180,        // matches chartArea height
    justifyContent: "space-between",
    alignItems: "flex-end",
    paddingRight: 4,
    paddingBottom: 22,  // reserve space for time labels
  },
  yLabel: {
    fontSize: 9,
    color: "#94a3b8",
  },

  /* Chart area */
  chartArea: {
    flex: 1,
    height: 180,
    position: "relative",
    justifyContent: "flex-end",
  },
  gridLine: {
    position: "absolute",
    left: 0,
    right: 0,
    height: 1,
    backgroundColor: "#e2e8f0",
    opacity: 0.6,
  },

  /* Bar row */
  chartRow: {
    flexDirection: "row",
    alignItems: "flex-end",
    height: 160,
    gap: 6,
    paddingHorizontal: 2,
  },
  barGroup: {
    flex: 1,
    alignItems: "center",
  },
  barsContainer: {
    flexDirection: "row",
    alignItems: "flex-end",
    gap: 2,
    height: 160,
  },
  barWrapper: {
    alignItems: "center",
    justifyContent: "flex-end",
  },
  barValue: {
    fontSize: 8,
    fontWeight: "600",
    marginBottom: 1,
  },
  bar: {
    width: 10,
    borderRadius: 3,
  },
  timeLabel: {
    fontSize: 9,
    color: "#64748b",
    marginTop: 5,
    textAlign: "center",
  },

  /* Legend */
  legend: {
    flexDirection: "row",
    justifyContent: "center",
    flexWrap: "wrap",
    gap: 14,
    marginTop: 14,
    paddingBottom: 4,
  },
  legendItem: {
    flexDirection: "row",
    alignItems: "center",
    gap: 5,
  },
  legendDot: {
    width: 10,
    height: 10,
    borderRadius: 3,
  },
  legendText: {
    fontSize: 12,
    color: "#475569",
    fontWeight: "500",
  },
});