import { ChangeEvent } from 'react';
import { Box } from './Box';
import { Input } from './Input';
import { Text } from './Text';

export interface DurationFieldProps {
  label: string;
  value: number; // in minutes
  onChange: (value: number) => void;
  disabled?: boolean;
  error?: string;
}

export const DurationField = ({ 
  label, 
  value, 
  onChange, 
  disabled = false,
  error 
}: DurationFieldProps) => {
  const hours = Math.floor(value / 60);
  const minutes = value % 60;

  const handleHoursChange = (e: ChangeEvent<HTMLInputElement>) => {
    const h = parseInt(e.target.value) || 0;
    onChange(h * 60 + minutes);
  };

  const handleMinutesChange = (e: ChangeEvent<HTMLInputElement>) => {
    const m = parseInt(e.target.value) || 0;
    onChange(hours * 60 + m);
  };

  return (
    <Box>
      <Text as="label" size="xs" weight="bold" variant="low" block>
        {label}
      </Text>
      <Box display="flex" alignItems="center" gap={4}>
        <Box display="flex" alignItems="center" gap={2}>
          <Input
            type="number"
            value={hours}
            onChange={handleHoursChange}
            disabled={disabled}
            min={0}
            style={{ width: '4rem' }}
          />
          <Text size="sm" variant="low">h</Text>
        </Box>
        <Box display="flex" alignItems="center" gap={2}>
          <Input
            type="number"
            value={minutes}
            onChange={handleMinutesChange}
            disabled={disabled}
            min={0}
            max={59}
            style={{ width: '4rem' }}
          />
          <Text size="sm" variant="low">m</Text>
        </Box>
      </Box>
      {error && (
        <Box marginTop={1}>
          <Text size="xs" variant="critical">
            {error}
          </Text>
        </Box>
      )}
    </Box>
  );
};
