'use client';

import { useState, useEffect, useMemo } from 'react';
import { Box, TextField, FormHelperText, Typography, styled } from '@mui/material';
import { useTranslation } from "react-i18next";

interface ShelfLifeInputProps {
  value?: number; // Total days
  onChange?: (value: number) => void;
  label?: string;
  sx?: any;
  showHelperText?: boolean;
  /** When true, shows "保質期: X 日" under the 年 field only */
  helperUnderYear?: boolean;
  /** Labels above fields instead of on the outline (avoids clipping) */
  externalLabels?: boolean;
  /** Only render Y/M/D inputs (labels & helper rendered by parent) */
  inputsOnly?: boolean;
}

const UnitLabel: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <Typography
    component="span"
    sx={{
      fontWeight: 600,
      fontSize: { xs: '0.95rem', sm: '1.05rem' },
      lineHeight: 1.4,
      color: 'text.secondary',
      mb: 0.75,
      textAlign: 'center',
    }}
  >
    {children}
  </Typography>
);

const ShelfLifeContainer = styled(Box)(({ theme }) => ({
  display: 'flex',
  gap: theme.spacing(2),
  alignItems: 'flex-start',
  width: '100%',
  '& .MuiTextField-root': {
    flex: 1,
    minWidth: 88,
    '& input': {
      textAlign: 'center',
    },
  },
}));

const daysToDuration = (totalDays: number) => {
  const years = Math.floor(totalDays / 365);
  const remainingDaysAfterYears = totalDays % 365;
  const months = Math.floor(remainingDaysAfterYears / 30); // **This is Approximate months (Not according to locale)
  const days = remainingDaysAfterYears % 30;
  return { years, months, days };
};

const durationToDays = (years: number, months: number, days: number) => {
  return years * 365 + months * 30 + days;
};

// Format duration to readable string with proper roll-over (Assuming 30 days per month)
const formatDuration = (years: number, months: number, days: number) => {
  let adjustedYears = years;
  let adjustedMonths = months;
  let adjustedDays = days;

  // Roll over days to months
  if (days >= 30) {
    adjustedMonths += Math.floor(days / 30);
    adjustedDays = days % 30;
  }

  // Roll over months to years
  if (adjustedMonths >= 12) {
    adjustedYears += Math.floor(adjustedMonths / 12);
    adjustedMonths = adjustedMonths % 12;
  }

  const parts: string[] = [];
  if (adjustedYears > 0) parts.push(`${adjustedYears} 年`);
  if (adjustedMonths > 0) parts.push(`${adjustedMonths} 個月 ${adjustedDays > 0 ? ' + ' : ''}`);
  if (adjustedDays > 0) parts.push(`${adjustedDays} 日`);
  return parts.length > 0 ? parts.join(' ') : '0 日';
};

const ShelfLifeInput: React.FC<ShelfLifeInputProps> = ({
  value = 0,
  onChange = () => {},
  label = 'Shelf Life',
  sx,
  showHelperText = true,
  helperUnderYear = false,
  externalLabels = false,
  inputsOnly = false,
}) => {
  const { t } = useTranslation("purchaseOrder");
  
  const { years, months, days } = daysToDuration(value);
  const [duration, setDuration] = useState({
    years: years || 0,
    months: months || 0,
    days: days || 0,
  });

  const totalDays = useMemo(() => {
    return durationToDays(duration.years, duration.months, duration.days);
  }, [duration]);

  useEffect(() => {
    onChange(totalDays);
  }, [totalDays]);

  // Set value when value prop changes
  useEffect(() => {
    if (value != totalDays) {
      setDuration(daysToDuration(value));
    }
  }, [value]);

  // Handle input changes
  const handleChange = (field: 'years' | 'months' | 'days') => (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const input = event.target.value;
    // Allow only non-negative integers
    if (input === '' || (/^\d+$/.test(input) && parseInt(input) >= 0)) {
      setDuration((prev) => ({
        ...prev,
        [field]: input === '' ? 0 : parseInt(input),
      }));
    }
  };

  const shelfLifeSummary = showHelperText && (
    <Typography
      component="div"
      sx={{
        fontSize: { xs: '0.95rem', sm: '1.05rem' },
        mt: 0.75,
        lineHeight: 1.4,
        whiteSpace: 'nowrap',
        color: 'text.secondary',
      }}
    >
      {label}:{' '}
      <Box component="span" sx={{ color: 'error.main', fontWeight: 600 }}>
        {totalDays} 日
      </Box>
    </Typography>
  );

  const hiddenLabelProps = { shrink: true, sx: { display: 'none' } };

  const yearField = (
    <TextField
      label={externalLabels ? ' ' : '年'}
      value={duration.years}
      onChange={handleChange('years')}
      sx={sx}
      type="text"
      fullWidth
      InputLabelProps={externalLabels ? hiddenLabelProps : { shrink: true }}
      inputProps={{
        inputMode: 'numeric',
        pattern: '[0-9]*',
      }}
      size="medium"
    />
  );

  const monthField = (
    <TextField
      label={externalLabels ? ' ' : '月'}
      value={duration.months}
      onChange={handleChange('months')}
      type="text"
      sx={sx}
      fullWidth
      InputLabelProps={externalLabels ? hiddenLabelProps : { shrink: true }}
      inputProps={{
        inputMode: 'numeric',
        pattern: '[0-9]*',
      }}
      size="medium"
    />
  );

  const dayField = (
    <TextField
      label={externalLabels ? ' ' : '日'}
      value={duration.days}
      onChange={handleChange('days')}
      sx={sx}
      type="text"
      fullWidth
      InputLabelProps={externalLabels ? hiddenLabelProps : { shrink: true }}
      inputProps={{
        inputMode: 'numeric',
        pattern: '[0-9]*',
      }}
      size="medium"
    />
  );

  const inputsRow = (
    <ShelfLifeContainer>
      <Box sx={{ flex: 1, minWidth: 0, overflow: 'visible' }}>
        {!inputsOnly && externalLabels && <UnitLabel>年</UnitLabel>}
        {yearField}
        {!inputsOnly && helperUnderYear && shelfLifeSummary}
      </Box>
      <Box sx={{ flex: 1, minWidth: 0 }}>
        {!inputsOnly && externalLabels && <UnitLabel>月</UnitLabel>}
        {monthField}
      </Box>
      <Box sx={{ flex: 1, minWidth: 0 }}>
        {!inputsOnly && externalLabels && <UnitLabel>日</UnitLabel>}
        {dayField}
      </Box>
    </ShelfLifeContainer>
  );

  if (inputsOnly) {
    return <Box sx={{ width: '100%' }}>{inputsRow}</Box>;
  }

  return (
    <Box sx={{ width: '100%', overflow: 'visible' }}>
      {inputsRow}
      {showHelperText && !helperUnderYear && shelfLifeSummary}
    </Box>
  );
};

export default ShelfLifeInput;