"use client";
import React, { useEffect, useState } from "react";
import {
  Box,
  Button,
  Typography,
} from "@mui/material";
import { useTranslation } from "react-i18next";
import {
  fetchProductProcessLineDetail,
  updateProductProcessLineQty,
  UpdateProductProcessLineQtyRequest,
  JobOrderProcessLineDetailResponse,
} from "@/app/api/jo/actions";
import ProductionOutputForm from "./ProductionOutputForm";

interface ProductionOutputFormPageProps {
  lineId: number | null;
  onBack: () => void;
}

const ProductionOutputFormPage: React.FC<ProductionOutputFormPageProps> = ({
  lineId,
  onBack,
}) => {
  const { t } = useTranslation();
  const [lineDetail, setLineDetail] = useState<JobOrderProcessLineDetailResponse | null>(null);
  const [outputData, setOutputData] = useState<UpdateProductProcessLineQtyRequest & {
    byproductName: string;
    byproductQty: number;
    byproductUom: string;
  }>({
    productProcessLineId: lineId ?? 0,
    outputFromProcessQty: 0,
    outputFromProcessUom: "",
    defectQty: 0,
    defectUom: "",
    defect2Qty: 0,
    defect2Uom: "",
    defect3Qty: 0,
    defect3Uom: "",
    defectDescription: "",
    defectDescription2: "",
    defectDescription3: "",
    scrapQty: 0,
    scrapUom: "",
    byproductName: "",
    byproductQty: 0,
    byproductUom: "",
  });

  useEffect(() => {
    if (!lineId) {
      setLineDetail(null);
      return;
    }
    fetchProductProcessLineDetail(lineId)
      .then((detail) => {
        setLineDetail(detail as any);
        setOutputData((prev) => ({
          ...prev,
          productProcessLineId: detail.id,
          outputFromProcessQty: (detail as any).outputFromProcessQty || 0,
          outputFromProcessUom: (detail as any).outputFromProcessUom || "",
          defectQty: detail.defectQty || 0,
          defectUom: detail.defectUom || "",
          scrapQty: detail.scrapQty || 0,
          scrapUom: detail.scrapUom || "",
          byproductName: detail.byproductName || "",
          byproductQty: detail.byproductQty || 0,
          byproductUom: detail.byproductUom || "",
        }));
      })
      .catch((err) => {
        console.error("Failed to load line detail", err);
        setLineDetail(null);
      });
  }, [lineId]);

  const handleSubmitOutput = async () => {
    if (!lineDetail?.id) return;

    try {
      await updateProductProcessLineQty({
        ...outputData,
        productProcessLineId: lineDetail.id || 0,
      });

      console.log("Output data submitted successfully");

      // 重新加载数据
      const detail = await fetchProductProcessLineDetail(lineDetail.id);
      setLineDetail(detail as any);
      setOutputData((prev) => ({
        ...prev,
        productProcessLineId: detail.id,
        outputFromProcessQty: (detail as any).outputFromProcessQty || 0,
        outputFromProcessUom: (detail as any).outputFromProcessUom || "",
        defectQty: detail.defectQty || 0,
        defectUom: detail.defectUom || "",
        scrapQty: detail.scrapQty || 0,
        scrapUom: detail.scrapUom || "",
        byproductName: detail.byproductName || "",
        byproductQty: detail.byproductQty || 0,
        byproductUom: detail.byproductUom || "",
      }));

      // 提交成功后返回
      onBack();
    } catch (error) {
      console.error("Error submitting output:", error);
      alert("Failed to submit output data. Please try again.");
    }
  };

  return (
    <Box>
      <Box sx={{ mb: 2 }}>
        <Button variant="outlined" onClick={onBack}>
          {t("Back to List")}
        </Button>
      </Box>

      <Box sx={{ mb: 3 }}>
        <Typography variant="h5" gutterBottom fontWeight="bold">
          {t("Production Output Data Entry")}
        </Typography>
        {lineDetail && (
          <Typography variant="body2" color="text.secondary">
            {t("Step")}: {lineDetail.name} (Seq: {lineDetail.seqNo})
          </Typography>
        )}
      </Box>

      <ProductionOutputForm
        outputData={outputData}
        setOutputData={setOutputData}
        onSubmit={handleSubmitOutput}
        onCancel={onBack}
      />
    </Box>
  );
};

export default ProductionOutputFormPage;