"use client";
import React, { useEffect, useState } from "react";
import { Card, CardContent, Typography, Box } from "@mui/material";
import { useTranslation } from "react-i18next";
import dayjs from "dayjs";
import { ProductProcessWithLinesResponse } from "@/app/api/jo/actions";

interface OverallTimeRemainingCardProps {
  processData?: ProductProcessWithLinesResponse | null;
}

const OverallTimeRemainingCard: React.FC<OverallTimeRemainingCardProps> = ({
  processData,
}) => {
  const { t } = useTranslation(["common", "jo"]);
  const [overallRemainingTime, setOverallRemainingTime] = useState<string | null>(null);
  const [isOverTime, setIsOverTime] = useState(false);

  useEffect(() => {
    console.log("🕐 OverallTimeRemainingCard - processData:", processData);
    console.log("🕐 OverallTimeRemainingCard - processData?.startTime:", processData?.startTime);
    console.log("🕐 OverallTimeRemainingCard - processData?.startTime type:", typeof processData?.startTime);
    console.log("🕐 OverallTimeRemainingCard - processData?.startTime isArray:", Array.isArray(processData?.startTime));
    
    const jobOrderStatus = String((processData as any)?.jobOrderStatus ?? "").trim().toLowerCase();
    const shouldStopCount =
      jobOrderStatus === "storing" ||
      jobOrderStatus === "completed" ||
      jobOrderStatus === "pendingqc" ||
      jobOrderStatus === "pending_qc";

    if (shouldStopCount || !processData?.startTime) {
      console.log("❌ OverallTimeRemainingCard - No startTime found");
      setOverallRemainingTime(null);
      setIsOverTime(false);
      return;
    }

    // 计算 Assume Time Need：从所有 productProcessLines 的 durationInMinutes 求和
    const assumeTimeNeed = processData?.productProcessLines?.reduce(
      (sum, line) => sum + (line.durationInMinutes || 0),
      0
    ) || 0;

    console.log("🕐 OverallTimeRemainingCard - productProcessLines:", processData?.productProcessLines);
    console.log("🕐 OverallTimeRemainingCard - assumeTimeNeed (minutes):", assumeTimeNeed);

    if (assumeTimeNeed === 0) {
      console.log("❌ OverallTimeRemainingCard - assumeTimeNeed is 0");
      setOverallRemainingTime(null);
      setIsOverTime(false);
      return;
    }

    // ✅ 修复：正确处理 startTime 可能是数组的情况
    let start: dayjs.Dayjs;
    if (Array.isArray(processData.startTime)) {
      console.log("🕐 OverallTimeRemainingCard - startTime is array:", processData.startTime);
      const [year, month, day, hour = 0, minute = 0, second = 0] = processData.startTime;
      console.log("🕐 OverallTimeRemainingCard - Parsed array values:", { year, month, day, hour, minute, second });
      start = dayjs(new Date(year, month - 1, day, hour, minute, second));
    } else if (typeof processData.startTime === 'string') {
      console.log("🕐 OverallTimeRemainingCard - startTime is string:", processData.startTime);
      
      // ✅ 检查是否是 "MM-DD HH:mm" 格式（缺少年份）
      const mmddHhmmPattern = /^(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})$/;
      const match = processData.startTime.match(mmddHhmmPattern);
      
      if (match) {
        console.log("🕐 OverallTimeRemainingCard - Detected MM-DD HH:mm format");
        const month = parseInt(match[1], 10);
        const day = parseInt(match[2], 10);
        const hour = parseInt(match[3], 10);
        const minute = parseInt(match[4], 10);
        
        // ✅ 使用当前年份，但如果跨年（startTime 是年末，当前是年初），使用上一年
        const now = dayjs();
        let year = now.year();
        
        // 检查是否跨年：如果 startTime 的月份大于当前月份，或者月份相同但日期大于当前日期
        // 且当前日期是年初（1月前10天），则可能是跨年情况
        const startMonthDay = month * 100 + day; // 例如 1229 = 12月29日
        const nowMonthDay = now.month() * 100 + now.date(); // 例如 101 = 1月1日
        
        // 如果 startTime 是年末（12月且日期>=20），当前是年初（1月且日期<=10），则使用上一年
        if (month === 12 && day >= 20 && now.month() === 0 && now.date() <= 10) {
          year = now.year() - 1;
          console.log("🕐 OverallTimeRemainingCard - Detected year crossover, using previous year:", year);
        } else {
          console.log("🕐 OverallTimeRemainingCard - Using current year:", year);
        }
        
        console.log("🕐 OverallTimeRemainingCard - Parsed MM-DD HH:mm values:", { year, month, day, hour, minute });
        start = dayjs(new Date(year, month - 1, day, hour, minute, 0));
      } else {
        // 尝试直接解析（可能是其他格式）
        console.log("🕐 OverallTimeRemainingCard - Trying to parse as standard date string");
        start = dayjs(processData.startTime);
      }
    } else {
      console.log("🕐 OverallTimeRemainingCard - startTime is unknown type, trying dayjs");
      start = dayjs(processData.startTime as any);
    }
    console.log("🕐 OverallTimeRemainingCard - start (dayjs):", start.format("YYYY-MM-DD HH:mm:ss"));
    console.log("🕐 OverallTimeRemainingCard - start isValid:", start.isValid());
    console.log("🕐 OverallTimeRemainingCard - start timestamp:", start.valueOf());

    if (!start.isValid()) {
      console.error("❌ OverallTimeRemainingCard - Invalid startTime:", processData.startTime);
      setOverallRemainingTime(null);
      setIsOverTime(false);
      return;
    }

    const assumeEnd = start.add(assumeTimeNeed, 'minute');
    console.log("🕐 OverallTimeRemainingCard - assumeEnd (dayjs):", assumeEnd.format("YYYY-MM-DD HH:mm:ss"));
    console.log("🕐 OverallTimeRemainingCard - assumeEnd timestamp:", assumeEnd.valueOf());
    console.log("🕐 OverallTimeRemainingCard - Duration from start to end (minutes):", assumeTimeNeed);

    const update = () => {
      const now = dayjs();
      const remaining = assumeEnd.diff(now, 'millisecond');

      console.log("🕐 OverallTimeRemainingCard - update() called:");
      console.log("  - now:", now.format("YYYY-MM-DD HH:mm:ss"));
      console.log("  - now timestamp:", now.valueOf());
      console.log("  - assumeEnd:", assumeEnd.format("YYYY-MM-DD HH:mm:ss"));
      console.log("  - assumeEnd timestamp:", assumeEnd.valueOf());
      console.log("  - remaining (ms):", remaining);
      console.log("  - remaining (minutes):", remaining / 60000);
      console.log("  - remaining (hours):", remaining / 3600000);

      if (remaining <= 0) {
        const overTime = Math.abs(remaining);
        console.log("  - overTime (ms):", overTime);
        console.log("  - overTime (minutes):", overTime / 60000);
        console.log("  - overTime (hours):", overTime / 3600000);
        
        // ✅ 修复：正确格式化时间，显示小时:分钟:秒
        const hours = Math.floor(overTime / 3600000);
        const minutes = Math.floor((overTime % 3600000) / 60000);
        const seconds = Math.floor((overTime % 60000) / 1000);
        
        console.log("  - Calculated hours:", hours);
        console.log("  - Calculated minutes:", minutes);
        console.log("  - Calculated seconds:", seconds);
        
        // 如果超过1小时，显示 HH:MM:SS，否则显示 MM:SS
        if (hours > 0) {
          const formatted = `-${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
          console.log("  - Formatted time (with hours):", formatted);
          setOverallRemainingTime(formatted);
        } else {
          const formatted = `-${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
          console.log("  - Formatted time (no hours):", formatted);
          setOverallRemainingTime(formatted);
        }
        setIsOverTime(true);
      } else {
        // ✅ 修复：正确格式化时间，显示小时:分钟:秒
        const hours = Math.floor(remaining / 3600000);
        const minutes = Math.floor((remaining % 3600000) / 60000);
        const seconds = Math.floor((remaining % 60000) / 1000);
        
        console.log("  - Calculated hours:", hours);
        console.log("  - Calculated minutes:", minutes);
        console.log("  - Calculated seconds:", seconds);
        
        // 如果超过1小时，显示 HH:MM:SS，否则显示 MM:SS
        if (hours > 0) {
          const formatted = `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
          console.log("  - Formatted time (with hours):", formatted);
          setOverallRemainingTime(formatted);
        } else {
          const formatted = `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
          console.log("  - Formatted time (no hours):", formatted);
          setOverallRemainingTime(formatted);
        }
        setIsOverTime(false);
      }
    };

    update();
    const timer = setInterval(update, 1000);
    return () => clearInterval(timer);
  }, [processData?.startTime, processData?.productProcessLines, (processData as any)?.jobOrderStatus]);

  if (!processData?.startTime || overallRemainingTime === null) {
    return null;
  }

  return (
    <Card sx={{ bgcolor: isOverTime ? 'error.50' : 'info.50', border: '2px solid', borderColor: isOverTime ? 'error.main' : 'info.main', mb: 3 }}>
      <CardContent>
        <Typography variant="h6" color={isOverTime ? 'error.main' : 'info.main'} gutterBottom fontWeight="bold">
          {t("Overall Time Remaining")}
        </Typography>
        <Box sx={{ mt: 2, p: 2, bgcolor: isOverTime ? 'error.100' : 'info.100', borderRadius: 1 }}>
          <Typography 
            variant="h4" 
            fontWeight="bold"
            color={isOverTime ? 'error.main' : 'info.main'}
            align="center"
          >
            {isOverTime ? `${t("Over Time")}: ${overallRemainingTime}` : overallRemainingTime}
          </Typography>
        </Box>
      </CardContent>
    </Card>
  );
};

export default OverallTimeRemainingCard;