import { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Typography,
  TextField,
  Button,
  Grid,
  Alert,
  CircularProgress,
  Divider,
} from '@mui/material';
import { Save, Send } from '@mui/icons-material';
import axios from 'axios';

const API_URL = import.meta.env.VITE_API_URL;

function Settings() {
  const [settings, setSettings] = useState({
    gmail_user: '',
    gmail_app_password: '',
    telegram_bot_token: '',
    telegram_chat_id: '',
  });
  const [loading, setLoading] = useState(true);
  const [testLoading, setTestLoading] = useState({ mail: false, telegram: false });
  const [alerts, setAlerts] = useState({ mail: null, telegram: null });

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

  const loadSettings = async () => {
    try {
      const response = await axios.get(`${API_URL}/api/settings`, {
        withCredentials: true,
      });
      setSettings(response.data.data);
    } catch (error) {
      console.error('Failed to load settings:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      await axios.put(`${API_URL}/api/settings`, settings, {
        withCredentials: true,
      });
      alert('Ayarlar kaydedildi!');
    } catch (error) {
      console.error('Failed to save settings:', error);
      alert('Ayarlar kaydedilemedi');
    }
  };

  const handleTestMail = async () => {
    setTestLoading({ ...testLoading, mail: true });
    try {
      const response = await axios.post(
        `${API_URL}/api/settings/test-mail`,
        {},
        { withCredentials: true }
      );
      setAlerts({ ...alerts, mail: { severity: 'success', message: response.data.message } });
    } catch (error) {
      setAlerts({
        ...alerts,
        mail: { severity: 'error', message: error.response?.data?.error || 'Test başarısız' },
      });
    } finally {
      setTestLoading({ ...testLoading, mail: false });
    }
  };

  const handleTestTelegram = async () => {
    setTestLoading({ ...testLoading, telegram: true });
    try {
      const response = await axios.post(
        `${API_URL}/api/settings/test-telegram`,
        {},
        { withCredentials: true }
      );
      setAlerts({ ...alerts, telegram: { severity: 'success', message: response.data.message } });
    } catch (error) {
      setAlerts({
        ...alerts,
        telegram: {
          severity: 'error',
          message: error.response?.data?.error || 'Test başarısız',
        },
      });
    } finally {
      setTestLoading({ ...testLoading, telegram: false });
    }
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="400px">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Sistem Ayarları
      </Typography>

      <Grid container spacing={3}>
        <Grid item xs={12} md={6}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              Gmail Ayarları
            </Typography>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              Gmail App Password kullanın (2FA aktif olmalı)
            </Typography>

            <TextField
              fullWidth
              margin="normal"
              label="Gmail Adresi"
              type="email"
              value={settings.gmail_user}
              onChange={(e) =>
                setSettings({ ...settings, gmail_user: e.target.value })
              }
            />
            <TextField
              fullWidth
              margin="normal"
              label="App Password"
              type="password"
              value={settings.gmail_app_password}
              onChange={(e) =>
                setSettings({ ...settings, gmail_app_password: e.target.value })
              }
            />

            {alerts.mail && (
              <Alert severity={alerts.mail.severity} sx={{ mt: 2 }}>
                {alerts.mail.message}
              </Alert>
            )}

            <Box mt={2} display="flex" gap={2}>
              <Button
                variant="contained"
                startIcon={<Save />}
                onClick={handleSave}
              >
                Kaydet
              </Button>
              <Button
                variant="outlined"
                startIcon={<Send />}
                onClick={handleTestMail}
                disabled={testLoading.mail}
              >
                Test Mail Gönder
              </Button>
            </Box>
          </Paper>
        </Grid>

        <Grid item xs={12} md={6}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              Telegram Ayarları
            </Typography>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              @BotFather'dan bot token alın, @userinfobot'dan chat ID öğrenin
            </Typography>

            <TextField
              fullWidth
              margin="normal"
              label="Bot Token"
              type="password"
              value={settings.telegram_bot_token}
              onChange={(e) =>
                setSettings({ ...settings, telegram_bot_token: e.target.value })
              }
            />
            <TextField
              fullWidth
              margin="normal"
              label="Chat ID"
              value={settings.telegram_chat_id}
              onChange={(e) =>
                setSettings({ ...settings, telegram_chat_id: e.target.value })
              }
            />

            {alerts.telegram && (
              <Alert severity={alerts.telegram.severity} sx={{ mt: 2 }}>
                {alerts.telegram.message}
              </Alert>
            )}

            <Box mt={2} display="flex" gap={2}>
              <Button
                variant="contained"
                startIcon={<Save />}
                onClick={handleSave}
              >
                Kaydet
              </Button>
              <Button
                variant="outlined"
                startIcon={<Send />}
                onClick={handleTestTelegram}
                disabled={testLoading.telegram}
              >
                Test Bildirimi
              </Button>
            </Box>
          </Paper>
        </Grid>
      </Grid>

      <Paper sx={{ p: 3, mt: 3 }}>
        <Typography variant="h6" gutterBottom>
          Tracking URL Bilgisi
        </Typography>
        <Divider sx={{ my: 2 }} />
        <Typography variant="body2" color="text.secondary">
          Tracking URL formatı: <strong>http://your-domain.com/t/TOKEN</strong>
        </Typography>
        <Typography variant="body2" color="text.secondary" mt={1}>
          Bu URL'ler mail şablonlarında otomatik olarak oluşturulur ve gönderilir.
        </Typography>
      </Paper>
    </Box>
  );
}

export default Settings;

