import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  Switch,
  FormControlLabel,
  Button,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Divider,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Tabs,
  Tab,
  Alert,
  CircularProgress,
  Chip,
} from '@mui/material';
import { Delete, Add, Upload, Link as LinkIcon, Edit, CloudUpload, Tv, Radio, Download } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useThemeStore } from '../store/themeStore';
import { useAuthStore } from '../store/authStore';
import UserManagement from '../components/UserManagement';
import ChangePasswordDialog from '../components/ChangePasswordDialog';
import TwoFactorSettings from '../components/TwoFactorSettings';
import VPNConfigManager from '../components/VPNConfigManager';
import BackupRestore from '../components/BackupRestore';
import SecurityStatusCard from '../components/SecurityStatusCard';
import SessionManagement from '../components/SessionManagement';

const Settings = () => {
  const { t, i18n } = useTranslation();
  const navigate = useNavigate();
  const { mode, toggleTheme } = useThemeStore();
  const { logout, token, user } = useAuthStore();
  const [playlists, setPlaylists] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [openDialog, setOpenDialog] = useState(false);
  const [tabValue, setTabValue] = useState(0);
  const [playlistUrl, setPlaylistUrl] = useState('');
  const [playlistName, setPlaylistName] = useState('');
  const [playlistUsername, setPlaylistUsername] = useState('');
  const [playlistPassword, setPlaylistPassword] = useState('');
  const [selectedFile, setSelectedFile] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  
  // M3U Library state
  const [m3uFiles, setM3uFiles] = useState([]);
  const [openM3uDialog, setOpenM3uDialog] = useState(false);
  const [m3uFileName, setM3uFileName] = useState('');
  const [selectedM3uFile, setSelectedM3uFile] = useState(null);
  const [uploadingM3u, setUploadingM3u] = useState(false);
  const [openImportDialog, setOpenImportDialog] = useState(false);
  const [importFileId, setImportFileId] = useState(null);
  const [importType, setImportType] = useState('tv'); // 'tv' or 'radio'
  const [renameDialogOpen, setRenameDialogOpen] = useState(false);
  const [renameFileId, setRenameFileId] = useState(null);
  const [renameValue, setRenameValue] = useState('');
  
  // Stream settings state
  const [streamSettings, setStreamSettings] = useState({
    hwaccel: 'auto',
    hwaccel_device: '/dev/dri/renderD128',
    codec: 'h264',
    preset: 'veryfast',
    buffer_size: '2M',
    max_bitrate: '8M'
  });
  const [hwCapabilities, setHwCapabilities] = useState({
    quicksync: false,
    nvenc: false,
    vaapi: false
  });

  useEffect(() => {
    fetchPlaylists();
    fetchM3uFiles();
    fetchStreamSettings();
    fetchHwCapabilities();
  }, []);

  const fetchPlaylists = async () => {
    try {
      const response = await fetch('/api/playlists', {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (response.ok) {
        const data = await response.json();
        setPlaylists(data);
      }
    } catch (err) {
      setError('Failed to load playlists');
    } finally {
      setLoading(false);
    }
  };

  const handleLanguageChange = (event) => {
    i18n.changeLanguage(event.target.value);
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const handleDeletePlaylist = async (id) => {
    try {
      const response = await fetch(`/api/playlists/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` },
      });
      if (response.ok) {
        fetchPlaylists();
      }
    } catch (err) {
      setError('Failed to delete playlist');
    }
  };

  const handleAddPlaylist = async () => {
    setSubmitting(true);
    setError('');
    try {
      if (tabValue === 0) {
        // URL method
        const response = await fetch('http://localhost:12345/api/playlists/url', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({
            url: playlistUrl,
            name: playlistName,
            username: playlistUsername,
            password: playlistPassword,
          }),
        });
        if (response.ok) {
          setOpenDialog(false);
          resetForm();
          fetchPlaylists();
        } else {
          setError('Failed to add playlist from URL');
        }
      } else {
        // File upload
        const formData = new FormData();
        formData.append('playlist', selectedFile);
        if (playlistName) formData.append('name', playlistName);

        const response = await fetch('/api/playlists/upload', {
          method: 'POST',
          headers: { Authorization: `Bearer ${token}` },
          body: formData,
        });
        if (response.ok) {
          setOpenDialog(false);
          resetForm();
          fetchPlaylists();
        } else {
          setError('Failed to upload playlist');
        }
      }
    } catch (err) {
      setError('Failed to add playlist');
    } finally {
      setSubmitting(false);
    }
  };

  const resetForm = () => {
    setPlaylistUrl('');
    setPlaylistName('');
    setPlaylistUsername('');
    setPlaylistPassword('');
    setSelectedFile(null);
    setTabValue(0);
    setError('');
  };

  // M3U Library functions
  const fetchM3uFiles = async () => {
    try {
      const response = await fetch('/api/m3u-files', {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (response.ok) {
        const data = await response.json();
        setM3uFiles(data);
      }
    } catch (err) {
      console.error('Failed to load M3U files:', err);
    }
  };

  // Stream settings functions
  const fetchStreamSettings = async () => {
    try {
      const response = await fetch('/api/settings/stream_settings', {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (response.ok) {
        const data = await response.json();
        setStreamSettings(data.value || streamSettings);
      }
    } catch (err) {
      console.debug('Using default stream settings');
    }
  };

  const fetchHwCapabilities = async () => {
    try {
      const response = await fetch('/api/stream/capabilities', {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (response.ok) {
        const data = await response.json();
        setHwCapabilities(data);
      }
    } catch (err) {
      console.error('Failed to fetch hardware capabilities');
    }
  };

  const handleStreamSettingChange = async (key, value) => {
    const newSettings = { ...streamSettings, [key]: value };
    setStreamSettings(newSettings);

    try {
      await fetch('/api/settings/stream_settings', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ value: streamSettings }),
      });
    } catch (err) {
      setError('Failed to update stream settings');
    }
  };


  const handleUploadM3u = async () => {
    if (!selectedM3uFile || !m3uFileName.trim()) {
      setError('Please select a file and provide a name');
      return;
    }

    setUploadingM3u(true);
    setError('');
    try {
      const formData = new FormData();
      formData.append('m3u', selectedM3uFile);
      formData.append('name', m3uFileName);

      const response = await fetch('/api/m3u-files/upload', {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}` },
        body: formData,
      });

      if (response.ok) {
        setOpenM3uDialog(false);
        resetM3uForm();
        fetchM3uFiles();
      } else {
        setError('Failed to upload M3U file');
      }
    } catch (err) {
      setError('Failed to upload M3U file');
    } finally {
      setUploadingM3u(false);
    }
  };

  const handleRenameM3u = async () => {
    if (!renameValue.trim()) {
      setError('Please provide a name');
      return;
    }

    try {
      const response = await fetch(`/api/m3u-files/${renameFileId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ name: newM3uFileName }),
      });

      if (response.ok) {
        setRenameDialogOpen(false);
        setRenameFileId(null);
        setRenameValue('');
        fetchM3uFiles();
      } else {
        setError('Failed to rename M3U file');
      }
    } catch (err) {
      setError('Failed to rename M3U file');
    }
  };

  const handleDeleteM3u = async (id) => {
    try {
      const response = await fetch(`/api/m3u-files/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` },
      });

      if (response.ok) {
        fetchM3uFiles();
      } else {
        setError('Failed to delete M3U file');
      }
    } catch (err) {
      setError('Failed to delete M3U file');
    }
  };

  const handleDownloadM3u = async (id, filename) => {
    try {
      const response = await fetch(`/api/m3u-files/${id}/download`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      
      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        setSuccess(t('settings.fileDownloaded'));
      } else {
        setError(t('settings.failedToDownload'));
      }
    } catch (err) {
      console.error('Download error:', err);
      setError(t('settings.failedToDownload'));
    }
  };

  const handleImportM3u = async () => {
    setError('');
    setSuccess('');
    setOpenImportDialog(false); // Close modal immediately
    setImportFileId(null);
    
    try {
      console.log('Importing M3U file:', importFileId, 'as type:', importType);
      setSuccess('Importing channels, please wait...');
      
      const response = await fetch(`/api/m3u-files/${importFileId}/import`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ type: importType }),
      });

      const data = await response.json();
      console.log('Import response:', data);

      if (response.ok) {
        fetchPlaylists();
        setSuccess(`✓ Successfully imported ${data.channels_added} ${importType === 'radio' ? 'radio stations' : 'TV channels'}`);
        setTimeout(() => setSuccess(''), 5000); // Clear after 5 seconds
      } else {
        setError(data.error || 'Failed to import M3U file');
        setTimeout(() => setError(''), 5000);
      }
    } catch (err) {
      console.error('Import error:', err);
      setError('Failed to import M3U file. Please try again.');
      setTimeout(() => setError(''), 5000);
    }
  };

  const resetM3uForm = () => {
    setM3uFileName('');
    setSelectedM3uFile(null);
  };

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString(i18n.language, {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };


  return (
    <Container maxWidth="md">
      <Box sx={{ py: 2 }}>
        <Typography variant="h5" sx={{ mb: 2 }}>
          {t('settings.title')}
        </Typography>

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

        <Paper sx={{ p: 2, mb: 2 }}>
          <Typography variant="subtitle1" sx={{ mb: 1.5, fontWeight: 600 }}>
            {t('settings.playlists')}
          </Typography>
          <Button
            size="small"
            variant="contained"
            startIcon={<Add />}
            onClick={() => setOpenDialog(true)}
            sx={{ mb: 1.5 }}
          >
            {t('settings.addPlaylist')}
          </Button>
          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 2 }}>
              <CircularProgress size={24} />
            </Box>
          ) : playlists.length === 0 ? (
            <Typography variant="body2" color="text.secondary" sx={{ py: 2, textAlign: 'center' }}>
              {t('settings.noPlaylists')}
            </Typography>
          ) : (
            <List dense disablePadding>
              {playlists.map((playlist) => (
                <React.Fragment key={playlist.id}>
                  <ListItem sx={{ px: 0 }}>
                    <ListItemText
                      primary={playlist.name}
                      secondary={`${playlist.channel_count || 0} channels`}
                      primaryTypographyProps={{ variant: 'body2' }}
                      secondaryTypographyProps={{ variant: 'caption' }}
                    />
                    <ListItemSecondaryAction>
                      <IconButton
                        edge="end"
                        size="small"
                        onClick={() => handleDeletePlaylist(playlist.id)}
                        color="error"
                      >
                        <Delete fontSize="small" />
                      </IconButton>
                    </ListItemSecondaryAction>
                  </ListItem>
                  <Divider />
                </React.Fragment>
              ))}
            </List>
          )}
        </Paper>

        <Paper sx={{ p: 2, mb: 2 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1.5 }}>
            <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
              {t('settings.m3uLibrary')}
            </Typography>
            <Button
              size="small"
              variant="contained"
              startIcon={<CloudUpload />}
              onClick={() => setOpenM3uDialog(true)}
            >
              {t('settings.uploadM3u')}
            </Button>
          </Box>
          {m3uFiles.length === 0 ? (
            <Typography variant="body2" color="text.secondary" sx={{ py: 2, textAlign: 'center' }}>
              {t('settings.noM3uFiles')}
            </Typography>
          ) : (
            <List dense disablePadding>
              {m3uFiles.map((file) => (
                <React.Fragment key={file.id}>
                  <ListItem sx={{ px: 0, flexWrap: 'wrap' }}>
                    <ListItemText
                      primary={file.name}
                      secondary={`${formatFileSize(file.size)} • ${formatDate(file.created_at)}`}
                      primaryTypographyProps={{ variant: 'body2', fontWeight: 500 }}
                      secondaryTypographyProps={{ variant: 'caption' }}
                    />
                    <Box sx={{ display: 'flex', gap: 0.5, ml: 'auto' }}>
                      <IconButton
                        size="small"
                        onClick={() => handleDownloadM3u(file.id, file.original_filename || `${file.name}.m3u`)}
                        title={t('settings.downloadM3uFile')}
                      >
                        <Download fontSize="small" />
                      </IconButton>
                      <IconButton
                        size="small"
                        onClick={() => {
                          setRenameFileId(file.id);
                          setRenameValue(file.name);
                          setRenameDialogOpen(true);
                        }}
                        title="Rename"
                      >
                        <Edit fontSize="small" />
                      </IconButton>
                      <Button
                        size="small"
                        variant="outlined"
                        startIcon={<Tv />}
                        onClick={() => {
                          setImportFileId(file.id);
                          setImportType('tv');
                          setOpenImportDialog(true);
                        }}
                        sx={{ minWidth: 'auto', px: 1 }}
                      >
                        {t('common.tv')}
                      </Button>
                      <Button
                        size="small"
                        variant="outlined"
                        startIcon={<Radio />}
                        onClick={() => {
                          setImportFileId(file.id);
                          setImportType('radio');
                          setOpenImportDialog(true);
                        }}
                        sx={{ minWidth: 'auto', px: 1 }}
                      >
                        {t('common.radio')}
                      </Button>
                      <IconButton
                        size="small"
                        color="error"
                        onClick={() => handleDeleteM3u(file.id)}
                        title="Delete"
                      >
                        <Delete fontSize="small" />
                      </IconButton>
                    </Box>
                  </ListItem>
                  <Divider />
                </React.Fragment>
              ))}
            </List>
          )}
        </Paper>

        <Paper sx={{ p: 2, mb: 2 }}>
          <Typography variant="subtitle1" sx={{ mb: 1.5, fontWeight: 600 }}>
            {t('settings.streaming')}
          </Typography>
          
          {Object.values(hwCapabilities).some(v => v) && (
            <Alert severity="success" sx={{ mb: 2, fontSize: '0.75rem' }}>
              {t('settings.hwAccelAvailable')}: {
                [
                  hwCapabilities.quicksync && 'Intel Quick Sync',
                  hwCapabilities.nvenc && 'NVIDIA NVENC',
                  hwCapabilities.vaapi && 'VAAPI'
                ].filter(Boolean).join(', ')
              }
            </Alert>
          )}
          
          <FormControl fullWidth size="small" sx={{ mb: 1.5 }}>
            <InputLabel>{t('settings.hwAccel')}</InputLabel>
            <Select
              value={streamSettings.hwaccel}
              onChange={(e) => handleStreamSettingChange('hwaccel', e.target.value)}
              label={t('settings.hwAccel')}
            >
              <MenuItem value="auto">{t('settings.hwAccelAuto')}</MenuItem>
              <MenuItem value="quicksync" disabled={!hwCapabilities.quicksync}>
                Intel Quick Sync {!hwCapabilities.quicksync && t('settings.hwAccelNotAvailable')}
              </MenuItem>
              <MenuItem value="vaapi" disabled={!hwCapabilities.vaapi}>
                VAAPI {!hwCapabilities.vaapi && t('settings.hwAccelNotAvailable')}
              </MenuItem>
              <MenuItem value="nvenc" disabled={!hwCapabilities.nvenc}>
                NVIDIA NVENC {!hwCapabilities.nvenc && t('settings.hwAccelNotAvailable')}
              </MenuItem>
              <MenuItem value="none">{t('settings.hwAccelNone')}</MenuItem>
            </Select>
          </FormControl>

          {streamSettings.hwaccel !== 'none' && streamSettings.hwaccel !== 'nvenc' && (
            <TextField
              fullWidth
              size="small"
              label={t('settings.hwDevice')}
              value={streamSettings.hwaccel_device}
              onChange={(e) => handleStreamSettingChange('hwaccel_device', e.target.value)}
              sx={{ mb: 1.5 }}
              helperText={t('settings.hwDeviceHelper')}
            />
          )}

          <FormControl fullWidth size="small" sx={{ mb: 1.5 }}>
            <InputLabel>{t('settings.encoderPreset')}</InputLabel>
            <Select
              value={streamSettings.preset}
              onChange={(e) => handleStreamSettingChange('preset', e.target.value)}
              label={t('settings.encoderPreset')}
            >
              <MenuItem value="ultrafast">{t('settings.presetUltrafast')}</MenuItem>
              <MenuItem value="superfast">{t('settings.presetSuperfast')}</MenuItem>
              <MenuItem value="veryfast">{t('settings.presetVeryfast')}</MenuItem>
              <MenuItem value="faster">{t('settings.presetFaster')}</MenuItem>
              <MenuItem value="fast">{t('settings.presetFast')}</MenuItem>
              <MenuItem value="medium">{t('settings.presetMedium')}</MenuItem>
              <MenuItem value="slow">{t('settings.presetSlow')}</MenuItem>
            </Select>
          </FormControl>

          <FormControl fullWidth size="small" sx={{ mb: 1.5 }}>
            <InputLabel>{t('settings.bufferSize')}</InputLabel>
            <Select
              value={streamSettings.buffer_size}
              onChange={(e) => handleStreamSettingChange('buffer_size', e.target.value)}
              label={t('settings.bufferSize')}
            >
              <MenuItem value="512K">512 KB ({t('settings.bufferLowLatency')})</MenuItem>
              <MenuItem value="1M">1 MB</MenuItem>
              <MenuItem value="2M">2 MB ({t('settings.hwAccelAuto').split(' ')[0]})</MenuItem>
              <MenuItem value="4M">4 MB</MenuItem>
              <MenuItem value="8M">8 MB ({t('settings.bufferSmooth')})</MenuItem>
            </Select>
          </FormControl>

          <FormControl fullWidth size="small">
            <InputLabel>{t('settings.maxBitrate')}</InputLabel>
            <Select
              value={streamSettings.max_bitrate}
              onChange={(e) => handleStreamSettingChange('max_bitrate', e.target.value)}
              label={t('settings.maxBitrate')}
            >
              <MenuItem value="2M">2 Mbps ({t('settings.bitrateLow')})</MenuItem>
              <MenuItem value="4M">4 Mbps</MenuItem>
              <MenuItem value="8M">8 Mbps ({t('settings.hwAccelAuto').split(' ')[0]})</MenuItem>
              <MenuItem value="12M">12 Mbps</MenuItem>
              <MenuItem value="20M">20 Mbps ({t('settings.bitrateHigh')})</MenuItem>
            </Select>
          </FormControl>

          <Alert severity="info" sx={{ mt: 2, fontSize: '0.75rem' }}>
            {t('settings.quickSyncInfo')}
          </Alert>
        </Paper>

        <Paper sx={{ p: 2, mb: 2 }}>
          <Typography variant="subtitle1" sx={{ mb: 1.5, fontWeight: 600 }}>
            {t('settings.appearance')}
          </Typography>
          <FormControlLabel
            control={<Switch checked={mode === 'dark'} onChange={toggleTheme} size="small" />}
            label={<Typography variant="body2">{t('settings.darkMode')}</Typography>}
          />
        </Paper>

        <Paper sx={{ p: 2, mb: 2 }}>
          <Typography variant="subtitle1" sx={{ mb: 1.5, fontWeight: 600 }}>
            {t('settings.language')}
          </Typography>
          <FormControl fullWidth size="small">
            <InputLabel>{t('settings.selectLanguage')}</InputLabel>
            <Select value={i18n.language} onChange={handleLanguageChange} label={t('settings.selectLanguage')}>
              <MenuItem value="en">English</MenuItem>
              <MenuItem value="ro">Română</MenuItem>
            </Select>
          </FormControl>
        </Paper>

        <Box sx={{ mb: 2 }}>
          <SecurityStatusCard />
        </Box>

        <Paper sx={{ p: 2, mb: 2 }}>
          <TwoFactorSettings />
        </Paper>

        <Paper sx={{ p: 2, mb: 2 }}>
          <SessionManagement />
        </Paper>

        <Paper sx={{ p: 2, mb: 2 }}>
          <VPNConfigManager />
        </Paper>

        <Box sx={{ mb: 2 }}>
          <BackupRestore />
        </Box>

        <Paper sx={{ p: 2 }}>
          <Typography variant="subtitle1" sx={{ mb: 1.5, fontWeight: 600 }}>
            {t('settings.account')}
          </Typography>
          <Button size="small" variant="outlined" color="error" onClick={handleLogout}>
            {t('settings.logout')}
          </Button>
        </Paper>
      </Box>

      <Dialog open={openDialog} onClose={() => { setOpenDialog(false); resetForm(); }} maxWidth="sm" fullWidth>
        <DialogTitle sx={{ pb: 1 }}>
          <Typography variant="h6">{t('settings.addPlaylist')}</Typography>
        </DialogTitle>
        <DialogContent>
          <Tabs value={tabValue} onChange={(e, v) => setTabValue(v)} sx={{ mb: 2 }}>
            <Tab icon={<LinkIcon />} label="URL" iconPosition="start" sx={{ minHeight: 40, fontSize: '0.8125rem' }} />
            <Tab icon={<Upload />} label="Upload" iconPosition="start" sx={{ minHeight: 40, fontSize: '0.8125rem' }} />
          </Tabs>

          {tabValue === 0 ? (
            <Box>
              <TextField
                fullWidth
                size="small"
                label="Playlist URL"
                value={playlistUrl}
                onChange={(e) => setPlaylistUrl(e.target.value)}
                sx={{ mb: 1.5 }}
              />
              <TextField
                fullWidth
                size="small"
                label={t('settings.playlistName')}
                value={playlistName}
                onChange={(e) => setPlaylistName(e.target.value)}
                sx={{ mb: 1.5 }}
              />
              <TextField
                fullWidth
                size="small"
                label="Username (optional)"
                value={playlistUsername}
                onChange={(e) => setPlaylistUsername(e.target.value)}
                sx={{ mb: 1.5 }}
              />
              <TextField
                fullWidth
                size="small"
                type="password"
                label="Password (optional)"
                value={playlistPassword}
                onChange={(e) => setPlaylistPassword(e.target.value)}
              />
            </Box>
          ) : (
            <Box>
              <Button
                variant="outlined"
                component="label"
                fullWidth
                size="small"
                sx={{ mb: 1.5, justifyContent: 'flex-start' }}
              >
                {selectedFile ? selectedFile.name : t('settings.selectFile')}
                <input
                  type="file"
                  hidden
                  accept=".m3u,.m3u8"
                  onChange={(e) => setSelectedFile(e.target.files[0])}
                />
              </Button>
              <TextField
                fullWidth
                size="small"
                label={t('settings.playlistName')}
                value={playlistName}
                onChange={(e) => setPlaylistName(e.target.value)}
              />
            </Box>
          )}
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button size="small" onClick={() => { setOpenDialog(false); resetForm(); }}>
            {t('common.cancel')}
          </Button>
          <Button
            size="small"
            variant="contained"
            onClick={handleAddPlaylist}
            disabled={submitting || (tabValue === 0 ? !playlistUrl : !selectedFile)}
          >
            {submitting ? <CircularProgress size={20} /> : t('common.add')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* M3U Upload Dialog */}
      <Dialog open={openM3uDialog} onClose={() => { setOpenM3uDialog(false); resetM3uForm(); }} maxWidth="sm" fullWidth>
        <DialogTitle sx={{ pb: 1 }}>
          <Typography variant="h6">{t('settings.uploadM3uFile')}</Typography>
        </DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            size="small"
            label={t('settings.fileName')}
            value={m3uFileName}
            onChange={(e) => setM3uFileName(e.target.value)}
            sx={{ mb: 1.5, mt: 1 }}
            helperText={t('settings.fileNameHelper')}
          />
          <Button
            variant="outlined"
            component="label"
            fullWidth
            size="small"
            startIcon={<Upload />}
            sx={{ justifyContent: 'flex-start' }}
          >
            {selectedM3uFile ? selectedM3uFile.name : t('settings.selectM3uFile')}
            <input
              type="file"
              hidden
              accept=".m3u,.m3u8"
              onChange={(e) => setSelectedM3uFile(e.target.files[0])}
            />
          </Button>
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button size="small" onClick={() => { setOpenM3uDialog(false); resetM3uForm(); }}>
            {t('common.cancel')}
          </Button>
          <Button
            size="small"
            variant="contained"
            onClick={handleUploadM3u}
            disabled={uploadingM3u || !selectedM3uFile || !m3uFileName.trim()}
          >
            {uploadingM3u ? <CircularProgress size={20} /> : t('common.upload')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Rename Dialog */}
      <Dialog open={renameDialogOpen} onClose={() => { setRenameDialogOpen(false); setRenameFileId(null); setRenameValue(''); }} maxWidth="xs" fullWidth>
        <DialogTitle sx={{ pb: 1 }}>
          <Typography variant="h6">{t('settings.renameM3uFile')}</Typography>
        </DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            size="small"
            label={t('settings.fileName')}
            value={renameValue}
            onChange={(e) => setRenameValue(e.target.value)}
            sx={{ mt: 1 }}
            autoFocus
          />
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button size="small" onClick={() => { setRenameDialogOpen(false); setRenameFileId(null); setRenameValue(''); }}>
            {t('common.cancel')}
          </Button>
          <Button
            size="small"
            variant="contained"
            onClick={handleRenameM3u}
            disabled={!renameValue.trim()}
          >
            {t('common.rename')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Import Dialog */}
      <Dialog open={openImportDialog} onClose={() => { setOpenImportDialog(false); setImportFileId(null); }} maxWidth="xs" fullWidth>
        <DialogTitle sx={{ pb: 1 }}>
          <Typography variant="h6">{t('settings.importM3uFile')}</Typography>
        </DialogTitle>
        <DialogContent>
          <Typography variant="body2" sx={{ mb: 2 }}>
            {t('settings.importMessage', { type: importType === 'tv' ? t('common.tv') : t('common.radio') })}
          </Typography>
          <Alert severity="info" sx={{ fontSize: '0.75rem' }}>
            {t('settings.importInfo', { section: importType === 'tv' ? t('settings.liveTV') : t('common.radio') })}
          </Alert>
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button size="small" onClick={() => { setOpenImportDialog(false); setImportFileId(null); }}>
            {t('common.cancel')}
          </Button>
          <Button
            size="small"
            variant="contained"
            onClick={handleImportM3u}
          >
            {t('common.import')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* User Management Section - Admin Only */}
      {user?.role === 'admin' && (
        <Paper sx={{ p: 2, mb: 2 }}>
          <Typography variant="h6" gutterBottom sx={{ fontSize: '1rem', fontWeight: 600 }}>
            {t('settings.userManagement')}
          </Typography>
          <UserManagement />
        </Paper>
      )}
    </Container>
  );
};

export default Settings;
