'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  TextField,
  Button,
  Switch,
  FormControlLabel,
  FormGroup,
  Divider,
  Alert,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Tabs,
  Tab,
  Paper,
  CircularProgress,
} from '@mui/material';
import {
  Save,
  Security,
  Notifications,
  Email,
  Storage,
  Api,
} from '@mui/icons-material';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div role="tabpanel" hidden={value !== index} {...other}>
      {value === index && <Box sx={{ pt: 3 }}>{children}</Box>}
    </div>
  );
}

export default function SettingsPage() {
  const [tabValue, setTabValue] = useState(0);
  const [saveSuccess, setSaveSuccess] = useState(false);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [settings, setSettings] = useState<any>({});

  useEffect(() => {
    fetchSettings();
  }, []);

  const fetchSettings = async () => {
    try {
      setLoading(true);
      const data = await apiClient.get('/admin/dashboard/settings');
      setSettings(data);
    } catch (error) {
      console.error('Failed to fetch settings:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      await apiClient.post('/admin/dashboard/settings', settings);
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 3000);
    } catch (error) {
      console.error('Failed to save settings:', error);
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <AdminLayout>
        <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '400px' }}>
          <CircularProgress />
        </Box>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <Box sx={{ mb: 3 }}>
        <Typography variant="h4" gutterBottom sx={{ fontWeight: 600 }}>
          Settings
        </Typography>
        <Typography variant="body1" color="text.secondary">
          Configure system settings and preferences
        </Typography>
      </Box>

      {saveSuccess && (
        <Alert severity="success" sx={{ mb: 3 }}>
          Settings saved successfully!
        </Alert>
      )}

      <Paper sx={{ borderRadius: 2 }}>
        <Tabs
          value={tabValue}
          onChange={(e, newValue) => setTabValue(newValue)}
          sx={{ borderBottom: 1, borderColor: 'divider', px: 2 }}
        >
          <Tab label="General" />
          <Tab label="Security" icon={<Security />} iconPosition="start" />
          <Tab label="Notifications" icon={<Notifications />} iconPosition="start" />
          <Tab label="Email" icon={<Email />} iconPosition="start" />
          <Tab label="Storage" icon={<Storage />} iconPosition="start" />
          <Tab label="API" icon={<Api />} iconPosition="start" />
        </Tabs>

        <Box sx={{ p: 3 }}>
          {/* General Settings */}
          <TabPanel value={tabValue} index={0}>
            <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, gap: 3 }}>
                <TextField
                  fullWidth
                  label="Site Name"
                  value={settings.siteName}
                  onChange={(e) => setSettings({ ...settings, siteName: e.target.value })}
                />
              
              
                <TextField
                  fullWidth
                  label="Admin Email"
                  type="email"
                  value={settings.adminEmail}
                  onChange={(e) => setSettings({ ...settings, adminEmail: e.target.value })}
                />
              
              
                <TextField
                  fullWidth
                  label="Support Email"
                  type="email"
                  value={settings.supportEmail}
                  onChange={(e) => setSettings({ ...settings, supportEmail: e.target.value })}
                />
              
              
                <FormControl fullWidth>
                  <InputLabel>Timezone</InputLabel>
                  <Select
                    value={settings.timezone}
                    label="Timezone"
                    onChange={(e) => setSettings({ ...settings, timezone: e.target.value })}
                  >
                    <MenuItem value="America/New_York">Eastern Time</MenuItem>
                    <MenuItem value="America/Chicago">Central Time</MenuItem>
                    <MenuItem value="America/Denver">Mountain Time</MenuItem>
                    <MenuItem value="America/Los_Angeles">Pacific Time</MenuItem>
                    <MenuItem value="Europe/London">London</MenuItem>
                    <MenuItem value="Europe/Paris">Paris</MenuItem>
                    <MenuItem value="Asia/Tokyo">Tokyo</MenuItem>
                  </Select>
                </FormControl>
              
              
                <FormControl fullWidth>
                  <InputLabel>Language</InputLabel>
                  <Select
                    value={settings.language}
                    label="Language"
                    onChange={(e) => setSettings({ ...settings, language: e.target.value })}
                  >
                    <MenuItem value="en">English</MenuItem>
                    <MenuItem value="es">Spanish</MenuItem>
                    <MenuItem value="fr">French</MenuItem>
                    <MenuItem value="pt">Portuguese</MenuItem>
                    <MenuItem value="zh">Chinese</MenuItem>
                  </Select>
                </FormControl>
            </Box>
          </TabPanel>

          {/* Security Settings */}
          <TabPanel value={tabValue} index={1}>
            <FormGroup>
              <FormControlLabel
                control={
                  <Switch
                    checked={settings.enforcePasswordPolicy}
                    onChange={(e) =>
                      setSettings({ ...settings, enforcePasswordPolicy: e.target.checked })
                    }
                  />
                }
                label="Enforce Password Policy"
              />
              {settings.enforcePasswordPolicy && (
                <Box sx={{ ml: 4, mt: 2 }}>
                  <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, gap: 2, mb: 2 }}>
                      <TextField
                        fullWidth
                        type="number"
                        label="Minimum Password Length"
                        value={settings.minPasswordLength}
                        onChange={(e) =>
                          setSettings({ ...settings, minPasswordLength: parseInt(e.target.value) })
                        }
                      />
                  </Box>
                      <FormGroup>
                        <FormControlLabel
                          control={
                            <Switch
                              checked={settings.requireUppercase}
                              onChange={(e) =>
                                setSettings({ ...settings, requireUppercase: e.target.checked })
                              }
                            />
                          }
                          label="Require Uppercase Letters"
                        />
                        <FormControlLabel
                          control={
                            <Switch
                              checked={settings.requireNumbers}
                              onChange={(e) =>
                                setSettings({ ...settings, requireNumbers: e.target.checked })
                              }
                            />
                          }
                          label="Require Numbers"
                        />
                        <FormControlLabel
                          control={
                            <Switch
                              checked={settings.requireSpecialChars}
                              onChange={(e) =>
                                setSettings({ ...settings, requireSpecialChars: e.target.checked })
                              }
                            />
                          }
                          label="Require Special Characters"
                        />
                      </FormGroup>
                    
                  
                </Box>
              )}
              <Divider sx={{ my: 2 }} />
              <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, gap: 2 }}>
                  <TextField
                    fullWidth
                    type="number"
                    label="Session Timeout (minutes)"
                    value={settings.sessionTimeout}
                    onChange={(e) =>
                      setSettings({ ...settings, sessionTimeout: parseInt(e.target.value) })
                    }
                  />
                
                
                  <TextField
                    fullWidth
                    type="number"
                    label="Max Login Attempts"
                    value={settings.maxLoginAttempts}
                    onChange={(e) =>
                      setSettings({ ...settings, maxLoginAttempts: parseInt(e.target.value) })
                    }
                  />
              </Box>
              <FormControlLabel
                control={
                  <Switch
                    checked={settings.enableTwoFactor}
                    onChange={(e) =>
                      setSettings({ ...settings, enableTwoFactor: e.target.checked })
                    }
                  />
                }
                label="Enable Two-Factor Authentication"
                sx={{ mt: 2 }}
              />
            </FormGroup>
          </TabPanel>

          {/* Notification Settings */}
          <TabPanel value={tabValue} index={2}>
            <FormGroup>
              <FormControlLabel
                control={
                  <Switch
                    checked={settings.enableEmailNotifications}
                    onChange={(e) =>
                      setSettings({ ...settings, enableEmailNotifications: e.target.checked })
                    }
                  />
                }
                label="Enable Email Notifications"
              />
              <FormControlLabel
                control={
                  <Switch
                    checked={settings.enablePushNotifications}
                    onChange={(e) =>
                      setSettings({ ...settings, enablePushNotifications: e.target.checked })
                    }
                  />
                }
                label="Enable Push Notifications"
              />
              <Divider sx={{ my: 2 }} />
              <Typography variant="subtitle1" sx={{ mb: 1 }}>
                Admin Notifications
              </Typography>
              <FormControlLabel
                control={
                  <Switch
                    checked={settings.adminNotifications}
                    onChange={(e) =>
                      setSettings({ ...settings, adminNotifications: e.target.checked })
                    }
                  />
                }
                label="Receive Admin Notifications"
              />
              <FormControlLabel
                control={
                  <Switch
                    checked={settings.errorAlerts}
                    onChange={(e) =>
                      setSettings({ ...settings, errorAlerts: e.target.checked })
                    }
                  />
                }
                label="Error Alerts"
              />
              <FormControlLabel
                control={
                  <Switch
                    checked={settings.newUserAlerts}
                    onChange={(e) =>
                      setSettings({ ...settings, newUserAlerts: e.target.checked })
                    }
                  />
                }
                label="New User Registration Alerts"
              />
              <FormControlLabel
                control={
                  <Switch
                    checked={settings.systemHealthAlerts}
                    onChange={(e) =>
                      setSettings({ ...settings, systemHealthAlerts: e.target.checked })
                    }
                  />
                }
                label="System Health Alerts"
              />
            </FormGroup>
          </TabPanel>

          {/* Email Settings */}
          <TabPanel value={tabValue} index={3}>
            <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, gap: 3 }}>
                <TextField
                  fullWidth
                  label="SMTP Host"
                  value={settings.smtpHost}
                  onChange={(e) => setSettings({ ...settings, smtpHost: e.target.value })}
                />
              
              
                <TextField
                  fullWidth
                  type="number"
                  label="SMTP Port"
                  value={settings.smtpPort}
                  onChange={(e) =>
                    setSettings({ ...settings, smtpPort: parseInt(e.target.value) })
                  }
                />
              
              
                <TextField
                  fullWidth
                  label="SMTP Username"
                  value={settings.smtpUser}
                  onChange={(e) => setSettings({ ...settings, smtpUser: e.target.value })}
                />
              
              
                <TextField
                  fullWidth
                  type="password"
                  label="SMTP Password"
                  value={settings.smtpPassword}
                  onChange={(e) => setSettings({ ...settings, smtpPassword: e.target.value })}
                />
              
              
                <TextField
                  fullWidth
                  label="From Address"
                  value={settings.emailFrom}
                  onChange={(e) => setSettings({ ...settings, emailFrom: e.target.value })}
                />
                <Button variant="outlined" sx={{ gridColumn: { xs: '1', md: 'span 2' } }}>Test Email Configuration</Button>
            </Box>
          </TabPanel>

          {/* Storage Settings */}
          <TabPanel value={tabValue} index={4}>
            <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, gap: 3 }}>
                <TextField
                  fullWidth
                  type="number"
                  label="Max File Size (MB)"
                  value={settings.maxFileSize}
                  onChange={(e) =>
                    setSettings({ ...settings, maxFileSize: parseInt(e.target.value) })
                  }
                />
              
              
                <TextField
                  fullWidth
                  label="Allowed File Types"
                  value={settings.allowedFileTypes}
                  onChange={(e) => setSettings({ ...settings, allowedFileTypes: e.target.value })}
                  helperText="Comma-separated list of extensions"
                />
              
              
                <FormControl fullWidth>
                  <InputLabel>Storage Provider</InputLabel>
                  <Select
                    value={settings.storageProvider}
                    label="Storage Provider"
                    onChange={(e) => setSettings({ ...settings, storageProvider: e.target.value })}
                  >
                    <MenuItem value="local">Local Storage</MenuItem>
                    <MenuItem value="s3">Amazon S3</MenuItem>
                    <MenuItem value="minio">MinIO</MenuItem>
                    <MenuItem value="gcs">Google Cloud Storage</MenuItem>
                  </Select>
                </FormControl>
              
              
                <TextField
                  fullWidth
                  label="S3 Bucket Name"
                  value={settings.s3Bucket}
                  onChange={(e) => setSettings({ ...settings, s3Bucket: e.target.value })}
                />
              
              
                <TextField
                  fullWidth
                  type="number"
                  label="Data Retention (days)"
                  value={settings.retentionDays}
                  onChange={(e) =>
                    setSettings({ ...settings, retentionDays: parseInt(e.target.value) })
                  }
                />
            </Box>
          </TabPanel>

          {/* API Settings */}
          <TabPanel value={tabValue} index={5}>
            <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, gap: 3 }}>
                <TextField
                  fullWidth
                  type="number"
                  label="Rate Limit (requests)"
                  value={settings.rateLimit}
                  onChange={(e) =>
                    setSettings({ ...settings, rateLimit: parseInt(e.target.value) })
                  }
                />
              
              
                <TextField
                  fullWidth
                  type="number"
                  label="Rate Limit Window (seconds)"
                  value={settings.rateLimitWindow}
                  onChange={(e) =>
                    setSettings({ ...settings, rateLimitWindow: parseInt(e.target.value) })
                  }
                />
              
              
                <TextField
                  fullWidth
                  type="number"
                  label="API Timeout (seconds)"
                  value={settings.apiTimeout}
                  onChange={(e) =>
                    setSettings({ ...settings, apiTimeout: parseInt(e.target.value) })
                  }
                />
                <FormGroup sx={{ gridColumn: { xs: '1', md: 'span 2' } }}>
                  <FormControlLabel
                    control={
                      <Switch
                        checked={settings.enableGraphQL}
                        onChange={(e) =>
                          setSettings({ ...settings, enableGraphQL: e.target.checked })
                        }
                      />
                    }
                    label="Enable GraphQL API"
                  />
                  <FormControlLabel
                    control={
                      <Switch
                        checked={settings.enableWebSockets}
                        onChange={(e) =>
                          setSettings({ ...settings, enableWebSockets: e.target.checked })
                        }
                      />
                    }
                    label="Enable WebSockets"
                  />
                </FormGroup>
                <TextField
                  fullWidth
                  multiline
                  rows={3}
                  label="CORS Origins"
                  value={settings.corsOrigins}
                  onChange={(e) => setSettings({ ...settings, corsOrigins: e.target.value })}
                  helperText="One origin per line"
                  sx={{ gridColumn: { xs: '1', md: 'span 2' } }}
                />
            </Box>
          </TabPanel>

          {/* Save Button */}
          <Box sx={{ mt: 4, display: 'flex', justifyContent: 'flex-end' }}>
            <Button
              variant="contained"
              size="large"
              startIcon={saving ? <CircularProgress size={20} /> : <Save />}
              onClick={handleSave}
              disabled={saving}
            >
              {saving ? 'Saving...' : 'Save Settings'}
            </Button>
          </Box>
        </Box>
      </Paper>
    </AdminLayout>
  );
}