'use client';

import { useState } from 'react';
import {
  Box,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Button,
  CircularProgress,
  Alert,
  Typography,
} from '@mui/material';
import { Save, AccessTime } from '@mui/icons-material';
import { useAuth } from '@/lib/auth/AuthContext';
import { usersApi } from '@/lib/api/users';
import { useTranslation } from '@/hooks/useTranslation';

// Common timezones grouped by region
const TIMEZONES = {
  'Americas': [
    { value: 'America/New_York', label: 'Eastern Time (US & Canada)' },
    { value: 'America/Chicago', label: 'Central Time (US & Canada)' },
    { value: 'America/Denver', label: 'Mountain Time (US & Canada)' },
    { value: 'America/Los_Angeles', label: 'Pacific Time (US & Canada)' },
    { value: 'America/Anchorage', label: 'Alaska' },
    { value: 'Pacific/Honolulu', label: 'Hawaii' },
    { value: 'America/Phoenix', label: 'Arizona' },
    { value: 'America/Toronto', label: 'Toronto' },
    { value: 'America/Vancouver', label: 'Vancouver' },
    { value: 'America/Mexico_City', label: 'Mexico City' },
    { value: 'America/Sao_Paulo', label: 'São Paulo' },
    { value: 'America/Buenos_Aires', label: 'Buenos Aires' },
  ],
  'Europe': [
    { value: 'Europe/London', label: 'London' },
    { value: 'Europe/Paris', label: 'Paris' },
    { value: 'Europe/Berlin', label: 'Berlin' },
    { value: 'Europe/Rome', label: 'Rome' },
    { value: 'Europe/Madrid', label: 'Madrid' },
    { value: 'Europe/Amsterdam', label: 'Amsterdam' },
    { value: 'Europe/Brussels', label: 'Brussels' },
    { value: 'Europe/Vienna', label: 'Vienna' },
    { value: 'Europe/Athens', label: 'Athens' },
    { value: 'Europe/Moscow', label: 'Moscow' },
  ],
  'Asia': [
    { value: 'Asia/Dubai', label: 'Dubai' },
    { value: 'Asia/Kolkata', label: 'India (Kolkata)' },
    { value: 'Asia/Shanghai', label: 'China (Shanghai)' },
    { value: 'Asia/Hong_Kong', label: 'Hong Kong' },
    { value: 'Asia/Singapore', label: 'Singapore' },
    { value: 'Asia/Tokyo', label: 'Tokyo' },
    { value: 'Asia/Seoul', label: 'Seoul' },
    { value: 'Asia/Bangkok', label: 'Bangkok' },
    { value: 'Asia/Jakarta', label: 'Jakarta' },
  ],
  'Pacific': [
    { value: 'Australia/Sydney', label: 'Sydney' },
    { value: 'Australia/Melbourne', label: 'Melbourne' },
    { value: 'Australia/Brisbane', label: 'Brisbane' },
    { value: 'Pacific/Auckland', label: 'Auckland' },
    { value: 'Pacific/Fiji', label: 'Fiji' },
  ],
  'Africa': [
    { value: 'Africa/Cairo', label: 'Cairo' },
    { value: 'Africa/Johannesburg', label: 'Johannesburg' },
    { value: 'Africa/Lagos', label: 'Lagos' },
    { value: 'Africa/Nairobi', label: 'Nairobi' },
  ],
};

export function TimeZoneSelector() {
  const { user, refreshUser } = useAuth();
  const { t } = useTranslation('settings');
  const [timezone, setTimezone] = useState(user?.timezone || 'UTC');
  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({ timezone });
      await refreshUser();
      setSuccessMessage('Timezone updated successfully');
    } catch (err: any) {
      console.error('Failed to update timezone:', err);
      setError(err.response?.data?.message || 'Failed to update timezone');
    } finally {
      setIsLoading(false);
    }
  };

  const handleAutoDetect = () => {
    const detectedTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    setTimezone(detectedTimezone);
    setSuccessMessage(`Auto-detected timezone: ${detectedTimezone}`);
  };

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
        <AccessTime color="action" />
        <Typography variant="subtitle1" fontWeight="600">
          Time Zone
        </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 fullWidth sx={{ mb: 2 }}>
        <InputLabel>Time Zone</InputLabel>
        <Select
          value={timezone}
          onChange={(e) => setTimezone(e.target.value)}
          label="Time Zone"
          disabled={isLoading}
        >
          {Object.entries(TIMEZONES).map(([region, zones]) => [
            <MenuItem key={region} disabled sx={{ fontWeight: 'bold', color: 'text.primary' }}>
              {region}
            </MenuItem>,
            ...zones.map((zone) => (
              <MenuItem key={zone.value} value={zone.value} sx={{ pl: 4 }}>
                {zone.label}
              </MenuItem>
            )),
          ])}
          <MenuItem value="UTC">UTC (Universal Time)</MenuItem>
        </Select>
      </FormControl>

      <Box sx={{ display: 'flex', gap: 2 }}>
        <Button
          variant="outlined"
          onClick={handleAutoDetect}
          disabled={isLoading}
        >
          Auto-Detect
        </Button>
        <Button
          variant="contained"
          startIcon={isLoading ? <CircularProgress size={20} color="inherit" /> : <Save />}
          onClick={handleSave}
          disabled={isLoading || timezone === user?.timezone}
        >
          {isLoading ? 'Saving...' : 'Save'}
        </Button>
      </Box>
    </Box>
  );
}
