"use client";
import React, { useEffect, useState } from "react";
import { PoResult } from "@/app/api/po";
import { fetchPoListClient } from "@/app/api/po/actions";
import { useTranslation } from "react-i18next";
import SafeApexCharts from "@/components/charts/SafeApexCharts";

interface Props {
  // params type
  po: PoResult[];
}

const DashboardProgressChart: React.FC = () => {
  const { t } = useTranslation("dashboard");
  const [series, setSeries] = useState<number[]>([]);
  const [total, setTotal] = useState(0);
  const [pending, setPending] = useState(0);
  const [receiving, setReceiving] = useState(0);

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetchPoListClient();
      const records = res?.records || [];
      const pendingCount = records.filter(
        (r: any) => r.status === "pending",
      ).length;
      const receivingCount = records.filter(
        (r: any) => r.status === "receiving",
      ).length;
      const totalCount = records.length;

      setPending(pendingCount);
      setReceiving(receivingCount);
      setTotal(totalCount);
      setSeries([pendingCount, receivingCount]);
    };
    fetchData();
  }, []);

  const options = {
    chart: {
      type: "donut" as const,
    },
    labels: [t("pending"), t("receiving")],
    dataLabels: {
      formatter: (val: number) => `${(Number(val) || 0).toFixed(1)}%`,
      dropShadow: {
        enabled: false,
      },
      style: {
        fontSize: "18px",
        fontWeight: "bold",
      },
    },
    legend: {
      position: "bottom" as const,
      fontSize: "16px",
      markers: {
        width: 16,
        height: 16,
        radius: 8,
      },
    },
    colors: ["#A3C9F9", "#8DD7A9"],
    plotOptions: {
      pie: {
        donut: {
          size: "70%",
          labels: {
            show: true,
            name: { show: false },
            value: {
              show: true,
              fontSize: "32px",
              fontWeight: 600,
              color: "#333",
              formatter: function (val: string) {
                return `${val}%`;
              },
            },
            total: {
              show: false,
            },
          },
        },
      },
    },
    stroke: {
      show: true,
      width: 2,
      colors: ["#fff"],
    },
  };

  return (
    <div
      style={{
        border: "1px solid #e0e0e0",
        borderRadius: 12,
        padding: 24,
        maxWidth: 400,
        margin: "0 ",
        background: "#fff",
        boxShadow: "0 2px 8px rgba(0,0,0,0.04)",
      }}
    >
      <div style={{ fontWeight: 600, fontSize: 18, marginBottom: 12 }}>
        {t("採購訂單概覽")}
      </div>
      <div
        style={{
          width: 320,
          height: 320,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          margin: "0 auto",
        }}
      >
        {series.length > 0 ? (
          <SafeApexCharts
            options={options}
            series={series}
            type="donut"
            width={280}
            height={280}
          />
        ) : (
          <div
            style={{
              height: 200,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            載入中...
          </div>
        )}
      </div>
      <div style={{ marginTop: 16, textAlign: "left" }}>
        <div>
          {t("pending")}：{pending}
        </div>
        <div>
          {t("receiving")}：{receiving}
        </div>
        <div>
          {t("total")}：{total}
        </div>
      </div>
    </div>
  );
};

export default DashboardProgressChart;
