'use client';

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

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 [settings, setSettings] = useState({
    // General Settings
    siteName: 'ParentFlow',
    adminEmail: 'admin@parentflowapp.com',
    supportEmail: 'support@parentflowapp.com',
    timezone: 'America/New_York',
    language: 'en',

    // Security Settings
    enforcePasswordPolicy: true,
    minPasswordLength: 8,
    requireUppercase: true,
    requireNumbers: true,
    requireSpecialChars: true,
    sessionTimeout: 30,
    maxLoginAttempts: 5,
    enableTwoFactor: false,

    // Notification Settings
    enableEmailNotifications: true,
    enablePushNotifications: true,
    adminNotifications: true,
    errorAlerts: true,
    newUserAlerts: true,
    systemHealthAlerts: true,

    // Email Settings
    smtpHost: 'smtp.gmail.com',
    smtpPort: 587,
    smtpUser: 'noreply@parentflowapp.com',
    smtpPassword: '********',
    emailFrom: 'ParentFlow <noreply@parentflowapp.com>',

    // Storage Settings
    maxFileSize: 10,
    allowedFileTypes: 'jpg,jpeg,png,pdf,doc,docx',
    storageProvider: 'minio',
    s3Bucket: 'parentflow-files',
    retentionDays: 90,

    // API Settings
    rateLimit: 100,
    rateLimitWindow: 60,
    apiTimeout: 30,
    enableGraphQL: true,
    enableWebSockets: true,
    corsOrigins: 'https://web.parentflowapp.com',
  });

  const handleSave = () => {
    // Save settings logic here
    setSaveSuccess(true);
    setTimeout(() => setSaveSuccess(false), 3000);
  };

  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}>
            <Grid container spacing={3}>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="Site Name"
                  value={settings.siteName}
                  onChange={(e) => setSettings({ ...settings, siteName: e.target.value })}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="Admin Email"
                  type="email"
                  value={settings.adminEmail}
                  onChange={(e) => setSettings({ ...settings, adminEmail: e.target.value })}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="Support Email"
                  type="email"
                  value={settings.supportEmail}
                  onChange={(e) => setSettings({ ...settings, supportEmail: e.target.value })}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <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>
              </Grid>
              <Grid item xs={12} md={6}>
                <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>
              </Grid>
            </Grid>
          </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 }}>
                  <Grid container spacing={2}>
                    <Grid item xs={12} md={6}>
                      <TextField
                        fullWidth
                        type="number"
                        label="Minimum Password Length"
                        value={settings.minPasswordLength}
                        onChange={(e) =>
                          setSettings({ ...settings, minPasswordLength: parseInt(e.target.value) })
                        }
                      />
                    </Grid>
                    <Grid item xs={12}>
                      <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>
                    </Grid>
                  </Grid>
                </Box>
              )}
              <Divider sx={{ my: 2 }} />
              <Grid container spacing={2}>
                <Grid item xs={12} md={6}>
                  <TextField
                    fullWidth
                    type="number"
                    label="Session Timeout (minutes)"
                    value={settings.sessionTimeout}
                    onChange={(e) =>
                      setSettings({ ...settings, sessionTimeout: parseInt(e.target.value) })
                    }
                  />
                </Grid>
                <Grid item xs={12} md={6}>
                  <TextField
                    fullWidth
                    type="number"
                    label="Max Login Attempts"
                    value={settings.maxLoginAttempts}
                    onChange={(e) =>
                      setSettings({ ...settings, maxLoginAttempts: parseInt(e.target.value) })
                    }
                  />
                </Grid>
              </Grid>
              <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}>
            <Grid container spacing={3}>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="SMTP Host"
                  value={settings.smtpHost}
                  onChange={(e) => setSettings({ ...settings, smtpHost: e.target.value })}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  type="number"
                  label="SMTP Port"
                  value={settings.smtpPort}
                  onChange={(e) =>
                    setSettings({ ...settings, smtpPort: parseInt(e.target.value) })
                  }
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="SMTP Username"
                  value={settings.smtpUser}
                  onChange={(e) => setSettings({ ...settings, smtpUser: e.target.value })}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  type="password"
                  label="SMTP Password"
                  value={settings.smtpPassword}
                  onChange={(e) => setSettings({ ...settings, smtpPassword: e.target.value })}
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="From Address"
                  value={settings.emailFrom}
                  onChange={(e) => setSettings({ ...settings, emailFrom: e.target.value })}
                />
              </Grid>
              <Grid item xs={12}>
                <Button variant="outlined">Test Email Configuration</Button>
              </Grid>
            </Grid>
          </TabPanel>

          {/* Storage Settings */}
          <TabPanel value={tabValue} index={4}>
            <Grid container spacing={3}>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  type="number"
                  label="Max File Size (MB)"
                  value={settings.maxFileSize}
                  onChange={(e) =>
                    setSettings({ ...settings, maxFileSize: parseInt(e.target.value) })
                  }
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="Allowed File Types"
                  value={settings.allowedFileTypes}
                  onChange={(e) => setSettings({ ...settings, allowedFileTypes: e.target.value })}
                  helperText="Comma-separated list of extensions"
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <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>
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="S3 Bucket Name"
                  value={settings.s3Bucket}
                  onChange={(e) => setSettings({ ...settings, s3Bucket: e.target.value })}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  type="number"
                  label="Data Retention (days)"
                  value={settings.retentionDays}
                  onChange={(e) =>
                    setSettings({ ...settings, retentionDays: parseInt(e.target.value) })
                  }
                />
              </Grid>
            </Grid>
          </TabPanel>

          {/* API Settings */}
          <TabPanel value={tabValue} index={5}>
            <Grid container spacing={3}>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  type="number"
                  label="Rate Limit (requests)"
                  value={settings.rateLimit}
                  onChange={(e) =>
                    setSettings({ ...settings, rateLimit: parseInt(e.target.value) })
                  }
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  type="number"
                  label="Rate Limit Window (seconds)"
                  value={settings.rateLimitWindow}
                  onChange={(e) =>
                    setSettings({ ...settings, rateLimitWindow: parseInt(e.target.value) })
                  }
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  type="number"
                  label="API Timeout (seconds)"
                  value={settings.apiTimeout}
                  onChange={(e) =>
                    setSettings({ ...settings, apiTimeout: parseInt(e.target.value) })
                  }
                />
              </Grid>
              <Grid item xs={12}>
                <FormGroup>
                  <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>
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  multiline
                  rows={3}
                  label="CORS Origins"
                  value={settings.corsOrigins}
                  onChange={(e) => setSettings({ ...settings, corsOrigins: e.target.value })}
                  helperText="One origin per line"
                />
              </Grid>
            </Grid>
          </TabPanel>

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