'use client';

import { useEffect } from 'react';
import {
  Box,
  FormControl,
  RadioGroup,
  FormControlLabel,
  Radio,
  Typography,
} from '@mui/material';
import { Schedule } from '@mui/icons-material';
import { useAuth } from '@/lib/auth/AuthContext';
import { useTranslation } from '@/hooks/useTranslation';

interface TimeFormatSelectorProps {
  value: '12h' | '24h';
  onChange: (timeFormat: '12h' | '24h') => void;
}

export function TimeFormatSelector({ value, onChange }: TimeFormatSelectorProps) {
  const { user } = useAuth();
  const { t } = useTranslation('settings');

  // Initialize with user's time format on mount
  useEffect(() => {
    if (user?.preferences?.timeFormat && !value) {
      onChange(user.preferences.timeFormat);
    }
  }, [user?.preferences?.timeFormat]);

  const currentTime = new Date();
  const preview12h = currentTime.toLocaleTimeString('en-US', {
    hour: 'numeric',
    minute: '2-digit',
    hour12: true,
  });
  const preview24h = currentTime.toLocaleTimeString('en-US', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  });

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
        <Schedule color="action" />
        <Typography variant="subtitle1" fontWeight="600">
          Time Format
        </Typography>
      </Box>

      <FormControl component="fieldset">
        <RadioGroup
          value={value || user?.preferences?.timeFormat || '12h'}
          onChange={(e) => onChange(e.target.value as '12h' | '24h')}
        >
          <FormControlLabel
            value="12h"
            control={<Radio />}
            label={
              <Box>
                <Typography variant="body1">12-hour format</Typography>
                <Typography variant="body2" color="text.secondary">
                  Example: {preview12h}
                </Typography>
              </Box>
            }
          />
          <FormControlLabel
            value="24h"
            control={<Radio />}
            label={
              <Box>
                <Typography variant="body1">24-hour format</Typography>
                <Typography variant="body2" color="text.secondary">
                  Example: {preview24h}
                </Typography>
              </Box>
            }
          />
        </RadioGroup>
      </FormControl>
    </Box>
  );
}
