'use client';

import { useState } from 'react';
import {
  Box,
  FormControl,
  RadioGroup,
  FormControlLabel,
  Radio,
  Button,
  CircularProgress,
  Alert,
  Typography,
} from '@mui/material';
import { Save, Schedule } from '@mui/icons-material';
import { useAuth } from '@/lib/auth/AuthContext';
import { usersApi } from '@/lib/api/users';
import { useTranslation } from '@/hooks/useTranslation';

export function TimeFormatSelector() {
  const { user, refreshUser } = useAuth();
  const { t } = useTranslation('settings');
  const [timeFormat, setTimeFormat] = useState<'12h' | '24h'>(
    user?.preferences?.timeFormat || '12h'
  );
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  const handleSave = async () => {
    setIsLoading(true);
    setError(null);
    setSuccessMessage(null);

    try {
      await usersApi.updateProfile({
        preferences: {
          ...user?.preferences,
          timeFormat,
        },
      });
      await refreshUser();
      setSuccessMessage('Time format updated successfully');
    } catch (err: any) {
      console.error('Failed to update time format:', err);
      setError(err.response?.data?.message || 'Failed to update time format');
    } finally {
      setIsLoading(false);
    }
  };

  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>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
          {error}
        </Alert>
      )}

      {successMessage && (
        <Alert severity="success" sx={{ mb: 2 }} onClose={() => setSuccessMessage(null)}>
          {successMessage}
        </Alert>
      )}

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

      <Button
        variant="contained"
        startIcon={isLoading ? <CircularProgress size={20} color="inherit" /> : <Save />}
        onClick={handleSave}
        disabled={isLoading || timeFormat === user?.preferences?.timeFormat}
      >
        {isLoading ? 'Saving...' : 'Save'}
      </Button>
    </Box>
  );
}
