import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Card,
  CardContent,
  Tab,
  Tabs,
  Grid,
  Paper,
  Button,
  TextField,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
} from '@mui/material';
import { GridItem } from '../components/GridItem';
import {
  Dashboard,
  Quiz as QuizIcon,
  ShoppingBag,
  People,
  Settings,
  Add,
  Edit,
  Delete,
  BarChart,
  DragIndicator,
} from '@mui/icons-material';
import { useAuth } from '../context/AuthContext';
import { apiService } from '../services/api';
import type { Quiz, Reward, Analytics, Question, Option } from '../types';

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

const TabPanel: React.FC<TabPanelProps> = ({ children, value, index }) => {
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`admin-tabpanel-${index}`}
      aria-labelledby={`admin-tab-${index}`}
    >
      {value === index && <Box sx={{ mt: 2 }}>{children}</Box>}
    </div>
  );
};

export const AdminPage: React.FC = () => {
  const { user } = useAuth();
  const [value, setValue] = useState(0);
  const [analytics, setAnalytics] = useState<Analytics | null>(null);
  const [quizzes, setQuizzes] = useState<Quiz[]>([]);
  const [rewards, setRewards] = useState<Reward[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Form states
  const [newQuiz, setNewQuiz] = useState({
    title: '',
    description: '',
    image_url: '',
    reward_stars: 10,
    has_timer: false,
    timer_per_question: 30,
    can_repeat: false,
    repeat_cooldown_hours: 24,
    is_active: true,
  });

  const [questions, setQuestions] = useState<Question[]>([]);
  const [currentQuestion, setCurrentQuestion] = useState<Partial<Question>>({
    text: '',
    type: 'multiple',
    options: [
      { id: 1, text: '', is_correct: false },
      { id: 2, text: '', is_correct: false },
    ],
    order_index: 0,
  });

  const [newReward, setNewReward] = useState({
    title: '',
    description: '',
    image_url: '',
    price_stars: 100,
    delivery_type: 'digital' as 'physical' | 'digital',
    instructions: '',
    stock: -1, // -1 = infinite stock
    is_active: true,
  });

  // Dialog states
  const [quizDialogOpen, setQuizDialogOpen] = useState(false);
  const [rewardDialogOpen, setRewardDialogOpen] = useState(false);
  const [editingQuiz, setEditingQuiz] = useState<Quiz | null>(null);
  const [editingReward, setEditingReward] = useState<Reward | null>(null);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [analyticsResponse, quizzesResponse, rewardsResponse] = await Promise.all([
          apiService.getAnalytics(),
          apiService.getAllQuizzes(),
          apiService.getAllRewards(),
        ]);

        if (analyticsResponse.success && analyticsResponse.data) {
          setAnalytics(analyticsResponse.data);
        }

        if (quizzesResponse.success && quizzesResponse.data) {
          setQuizzes(quizzesResponse.data);
        }

        if (rewardsResponse.success && rewardsResponse.data) {
          setRewards(rewardsResponse.data);
        }
      } catch (err) {
        console.error('Error fetching admin data:', err);
        setError('Произошла ошибка при загрузке данных');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  const handleChange = (_event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
  };

  const handleCreateQuiz = async () => {
    if (questions.length === 0) {
      setError('Добавьте хотя бы один вопрос');
      return;
    }

    setSubmitting(true);
    try {
      const response = await apiService.createQuiz(newQuiz);
      if (response.success) {
        const quizId = response.data.id;

        // Create all questions for the quiz
        for (const question of questions) {
          await apiService.createQuestion(quizId, question);
        }

        setQuizzes(prev => [...prev, { ...response.data, questions }]);
        setQuizDialogOpen(false);
        setNewQuiz({
          title: '',
          description: '',
          image_url: '',
          reward_stars: 10,
          has_timer: false,
          timer_per_question: 30,
          can_repeat: false,
          repeat_cooldown_hours: 24,
          is_active: true,
        });
        resetQuestions();
      } else {
        setError(response.message || 'Не удалось создать викторину');
      }
    } catch (err) {
      console.error('Error creating quiz:', err);
      setError('Произошла ошибка при создании викторины');
    } finally {
      setSubmitting(false);
    }
  };

  const handleUpdateQuiz = async () => {
    if (!editingQuiz) return;

    setSubmitting(true);
    try {
      const response = await apiService.updateQuiz(editingQuiz.id, editingQuiz);
      if (response.success) {
        // Get existing questions for the quiz
        const quizResponse = await apiService.getQuizById(editingQuiz.id);
        const existingQuestions = quizResponse.success ? quizResponse.data.questions || [] : [];

        // Delete questions that are no longer needed
        for (const existingQuestion of existingQuestions) {
          if (!questions.find(q => q.id === existingQuestion.id)) {
            await apiService.deleteQuestion(editingQuiz.id, existingQuestion.id);
          }
        }

        // Update or create questions
        for (const question of questions) {
          if (question.id && question.id < 1000000) { // Existing question (not temporary ID)
            await apiService.updateQuestion(editingQuiz.id, question.id, question);
          } else {
            // New question
            await apiService.createQuestion(editingQuiz.id, question);
          }
        }

        setQuizzes(prev => prev.map(q => q.id === editingQuiz.id ? { ...response.data, questions } : q));
        setQuizDialogOpen(false);
        setEditingQuiz(null);
        resetQuestions();
      } else {
        setError(response.message || 'Не удалось обновить викторину');
      }
    } catch (err) {
      console.error('Error updating quiz:', err);
      setError('Произошла ошибка при обновлении викторины');
    } finally {
      setSubmitting(false);
    }
  };

  const handleDeleteQuiz = async (quizId: number) => {
    if (!confirm('Вы уверены, что хотите удалить эту викторину?')) return;

    try {
      const response = await apiService.deleteQuiz(quizId);
      if (response.success) {
        setQuizzes(prev => prev.filter(q => q.id !== quizId));
      } else {
        setError(response.message || 'Не удалось удалить викторину');
      }
    } catch (err) {
      console.error('Error deleting quiz:', err);
      setError('Произошла ошибка при удалении викторины');
    }
  };

  const handleCreateReward = async () => {
    setSubmitting(true);
    try {
      const response = await apiService.createReward(newReward);
      if (response.success) {
        setRewards(prev => [...prev, response.data]);
        setRewardDialogOpen(false);
        setNewReward({
          title: '',
          description: '',
          image_url: '',
          price_stars: 100,
          delivery_type: 'digital',
          instructions: '',
          stock: -1, // -1 = infinite stock
          is_active: true,
        });
      } else {
        setError(response.message || 'Не удалось создать приз');
      }
    } catch (err) {
      console.error('Error creating reward:', err);
      setError('Произошла ошибка при создании приза');
    } finally {
      setSubmitting(false);
    }
  };

  const handleUpdateReward = async () => {
    if (!editingReward) return;

    setSubmitting(true);
    try {
      const response = await apiService.updateReward(editingReward.id, editingReward);
      if (response.success) {
        setRewards(prev => prev.map(r => r.id === editingReward.id ? response.data : r));
        setRewardDialogOpen(false);
        setEditingReward(null);
      } else {
        setError(response.message || 'Не удалось обновить приз');
      }
    } catch (err) {
      console.error('Error updating reward:', err);
      setError('Произошла ошибка при обновлении приза');
    } finally {
      setSubmitting(false);
    }
  };

  const handleDeleteReward = async (rewardId: number) => {
    if (!confirm('Вы уверены, что хотите удалить этот приз?')) return;

    try {
      const response = await apiService.deleteReward(rewardId);
      if (response.success) {
        setRewards(prev => prev.filter(r => r.id !== rewardId));
      } else {
        setError(response.message || 'Не удалось удалить приз');
      }
    } catch (err) {
      console.error('Error deleting reward:', err);
      setError('Произошла ошибка при удалении приза');
    }
  };

  const openEditQuizDialog = async (quiz: Quiz) => {
    setEditingQuiz(quiz);

    // Load questions for this quiz
    try {
      const response = await apiService.getQuizById(quiz.id);
      if (response.success && response.data.questions) {
        setQuestions(response.data.questions);
      } else {
        setQuestions([]);
      }
    } catch (err) {
      console.error('Error loading questions:', err);
      setQuestions([]);
    }

    setQuizDialogOpen(true);
  };

  const openEditRewardDialog = (reward: Reward) => {
    setEditingReward(reward);
    setRewardDialogOpen(true);
  };

  // Question management functions
  const addOption = () => {
    const newId = Math.max(...(currentQuestion.options?.map(o => o.id) || [0]), 0) + 1;
    setCurrentQuestion(prev => ({
      ...prev,
      options: [...(prev.options || []), { id: newId, text: '', is_correct: false }]
    }));
  };

  const removeOption = (optionId: number) => {
    if (currentQuestion.options && currentQuestion.options.length > 2) {
      setCurrentQuestion(prev => ({
        ...prev,
        options: prev.options?.filter(o => o.id !== optionId) || []
      }));
    }
  };

  const updateOption = (optionId: number, field: keyof Option, value: any) => {
    setCurrentQuestion(prev => ({
      ...prev,
      options: prev.options?.map(o =>
        o.id === optionId ? { ...o, [field]: value } : o
      ) || []
    }));
  };

  const addQuestion = () => {
    console.log('addQuestion called, currentQuestion:', currentQuestion);
    console.log('questions before add:', questions.length);

    if (currentQuestion.text && currentQuestion.options && currentQuestion.options.length >= 2) {
      const validOptions = currentQuestion.options.filter(o => o.text.trim() !== '');
      const hasCorrectAnswer = validOptions.some(o => o.is_correct);

      console.log('validOptions:', validOptions.length, 'hasCorrectAnswer:', hasCorrectAnswer);

      if (validOptions.length >= 2 && hasCorrectAnswer) {
        const question: Question = {
          id: Date.now(), // Temporary ID
          quiz_id: editingQuiz?.id || 0,
          text: currentQuestion.text,
          type: 'multiple',
          options: validOptions,
          order_index: questions.length
        };

        setQuestions(prev => {
          console.log('Setting questions, prev length:', prev.length, 'new length:', prev.length + 1);
          return [...prev, question];
        });

        setCurrentQuestion({
          text: '',
          type: 'multiple',
          options: [
            { id: 1, text: '', is_correct: false },
            { id: 2, text: '', is_correct: false },
          ],
          order_index: questions.length + 1
        });
      }
    }
  };

  const removeQuestion = (index: number) => {
    setQuestions(prev => prev.filter((_, i) => i !== index));
  };

  const resetQuestions = () => {
    console.log('resetQuestions called');
    setQuestions([]);
    setCurrentQuestion({
      text: '',
      type: 'multiple',
      options: [
        { id: 1, text: '', is_correct: false },
        { id: 2, text: '', is_correct: false },
      ],
      order_index: 0
    });
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
        <Typography sx={{ color: '#888' }}>Загрузка...</Typography>
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ textAlign: 'center', mt: 4 }}>
        <Typography sx={{ color: '#f44336' }}>{error}</Typography>
      </Box>
    );
  }

  return (
    <Box>
      {/* Header */}
      <Box sx={{ mb: 4 }}>
        <Typography
          variant="h4"
          sx={{
            color: '#FFD700',
            fontWeight: 'bold',
            mb: 1,
          }}
        >
          Админ-панель
        </Typography>
        <Typography
          variant="body1"
          sx={{ color: '#888' }}
        >
          Добро пожаловать, {user?.first_name}!
        </Typography>
      </Box>

      {/* Stats Cards */}
      {analytics && (
        <Grid container component="div" spacing={3} sx={{ mb: 4 }}>
          <GridItem xs={12} sm={6} md={3} component="div">
            <Card sx={{ backgroundColor: '#1a1a1a', border: '1px solid #333' }}>
              <CardContent>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                  <People sx={{ color: '#4CAF50', fontSize: 32 }} />
                  <Box>
                    <Typography variant="h4" sx={{ color: '#ffffff' }}>
                      {analytics.total_users}
                    </Typography>
                    <Typography variant="body2" sx={{ color: '#888' }}>
                      Пользователи
                    </Typography>
                  </Box>
                </Box>
              </CardContent>
            </Card>
          </GridItem>
          <GridItem xs={12} sm={6} md={3} component="div">
            <Card sx={{ backgroundColor: '#1a1a1a', border: '1px solid #333' }}>
              <CardContent>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                  <QuizIcon sx={{ color: '#2196F3', fontSize: 32 }} />
                  <Box>
                    <Typography variant="h4" sx={{ color: '#ffffff' }}>
                      {analytics.total_quizzes_completed}
                    </Typography>
                    <Typography variant="body2" sx={{ color: '#888' }}>
                      Викторин пройдено
                    </Typography>
                  </Box>
                </Box>
              </CardContent>
            </Card>
          </GridItem>
          <GridItem xs={12} sm={6} md={3} component="div">
            <Card sx={{ backgroundColor: '#1a1a1a', border: '1px solid #333' }}>
              <CardContent>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                  <BarChart sx={{ color: '#FFD700', fontSize: 32 }} />
                  <Box>
                    <Typography variant="h4" sx={{ color: '#ffffff' }}>
                      {analytics.total_stars_earned}
                    </Typography>
                    <Typography variant="body2" sx={{ color: '#888' }}>
                      Звёзд выдано
                    </Typography>
                  </Box>
                </Box>
              </CardContent>
            </Card>
          </GridItem>
          <GridItem xs={12} sm={6} md={3} component="div">
            <Card sx={{ backgroundColor: '#1a1a1a', border: '1px solid #333' }}>
              <CardContent>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                  <ShoppingBag sx={{ color: '#FF9800', fontSize: 32 }} />
                  <Box>
                    <Typography variant="h4" sx={{ color: '#ffffff' }}>
                      {analytics.total_purchases}
                    </Typography>
                    <Typography variant="body2" sx={{ color: '#888' }}>
                      Покупок
                    </Typography>
                  </Box>
                </Box>
              </CardContent>
            </Card>
          </GridItem>
        </Grid>
      )}

      {/* Tabs */}
      <Box sx={{ borderBottom: 1, borderColor: '#333' }}>
        <Tabs
          value={value}
          onChange={handleChange}
          sx={{
            '& .MuiTab-root': {
              color: '#888',
              '&.Mui-selected': {
                color: '#FFD700',
              },
            },
            '& .MuiTabs-indicator': {
              backgroundColor: '#FFD700',
            },
          }}
        >
          <Tab
            icon={<Dashboard />}
            label="Обзор"
            id="admin-tab-0"
            aria-controls="admin-tabpanel-0"
          />
          <Tab
            icon={<QuizIcon />}
            label="Викторины"
            id="admin-tab-1"
            aria-controls="admin-tabpanel-1"
          />
          <Tab
            icon={<ShoppingBag />}
            label="Призы"
            id="admin-tab-2"
            aria-controls="admin-tabpanel-2"
          />
          <Tab
            icon={<Settings />}
            label="Настройки"
            id="admin-tab-3"
            aria-controls="admin-tabpanel-3"
          />
        </Tabs>
      </Box>

      {/* Tab Panels */}
      <TabPanel value={value} index={0}>
        <Typography variant="h6" sx={{ color: '#ffffff', mb: 2 }}>
          Обзор системы
        </Typography>
        <Card sx={{ backgroundColor: '#1a1a1a', border: '1px solid #333' }}>
          <CardContent>
            <Typography sx={{ color: '#888' }}>
              Здесь будет отображаться подробная статистика и аналитика системы.
            </Typography>
          </CardContent>
        </Card>
      </TabPanel>

      <TabPanel value={value} index={1}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Typography variant="h6" sx={{ color: '#ffffff' }}>
            Управление викторинами
          </Typography>
          <Button
            variant="contained"
            onClick={() => {
              setEditingQuiz(null);
              setQuizDialogOpen(true);
            }}
            startIcon={<Add />}
            sx={{
              backgroundColor: '#FFD700',
              color: '#000000',
            }}
          >
            Создать викторину
          </Button>
        </Box>

        <TableContainer component={Paper} sx={{ backgroundColor: '#1a1a1a' }}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell sx={{ color: '#ffffff' }}>Название</TableCell>
                <TableCell sx={{ color: '#ffffff' }}>Вопросов</TableCell>
                <TableCell sx={{ color: '#ffffff' }}>Награда</TableCell>
                <TableCell sx={{ color: '#ffffff' }}>Статус</TableCell>
                <TableCell sx={{ color: '#ffffff' }}>Действия</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {quizzes.map((quiz) => (
                <TableRow key={quiz.id}>
                  <TableCell sx={{ color: '#ffffff' }}>{quiz.title}</TableCell>
                  <TableCell sx={{ color: '#ffffff' }}>{quiz.questions?.length || 0}</TableCell>
                  <TableCell sx={{ color: '#ffffff' }}>{quiz.reward_stars} ⭐</TableCell>
                  <TableCell>
                    <Chip
                      label={quiz.is_active ? 'Активна' : 'Неактивна'}
                      size="small"
                      sx={{
                        backgroundColor: quiz.is_active ? 'rgba(76, 175, 80, 0.2)' : 'rgba(244, 67, 54, 0.2)',
                        color: quiz.is_active ? '#4CAF50' : '#f44336',
                      }}
                    />
                  </TableCell>
                  <TableCell>
                    <IconButton
                      size="small"
                      sx={{ color: '#FFD700' }}
                      onClick={() => openEditQuizDialog(quiz)}
                    >
                      <Edit />
                    </IconButton>
                    <IconButton
                      size="small"
                      sx={{ color: '#f44336' }}
                      onClick={() => handleDeleteQuiz(quiz.id)}
                    >
                      <Delete />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </TabPanel>

      <TabPanel value={value} index={2}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Typography variant="h6" sx={{ color: '#ffffff' }}>
            Управление призами
          </Typography>
          <Button
            variant="contained"
            onClick={() => {
              setEditingReward(null);
              setRewardDialogOpen(true);
            }}
            startIcon={<Add />}
            sx={{
              backgroundColor: '#FFD700',
              color: '#000000',
            }}
          >
            Создать приз
          </Button>
        </Box>

        <TableContainer component={Paper} sx={{ backgroundColor: '#1a1a1a' }}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell sx={{ color: '#ffffff' }}>Название</TableCell>
                <TableCell sx={{ color: '#ffffff' }}>Цена</TableCell>
                <TableCell sx={{ color: '#ffffff' }}>Остаток</TableCell>
                <TableCell sx={{ color: '#ffffff' }}>Статус</TableCell>
                <TableCell sx={{ color: '#ffffff' }}>Действия</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {rewards.map((reward) => (
                <TableRow key={reward.id}>
                  <TableCell sx={{ color: '#ffffff' }}>{reward.title}</TableCell>
                  <TableCell sx={{ color: '#ffffff' }}>{reward.price_stars} ⭐</TableCell>
                  <TableCell sx={{ color: '#ffffff' }}>
                    {reward.stock === -1 ? '∞' : reward.stock}
                  </TableCell>
                  <TableCell>
                    <Chip
                      label={reward.is_active ? 'Активен' : 'Неактивен'}
                      size="small"
                      sx={{
                        backgroundColor: reward.is_active ? 'rgba(76, 175, 80, 0.2)' : 'rgba(244, 67, 54, 0.2)',
                        color: reward.is_active ? '#4CAF50' : '#f44336',
                      }}
                    />
                  </TableCell>
                  <TableCell>
                    <IconButton
                      size="small"
                      sx={{ color: '#FFD700' }}
                      onClick={() => openEditRewardDialog(reward)}
                    >
                      <Edit />
                    </IconButton>
                    <IconButton
                      size="small"
                      sx={{ color: '#f44336' }}
                      onClick={() => handleDeleteReward(reward.id)}
                    >
                      <Delete />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </TabPanel>

      <TabPanel value={value} index={3}>
        <Typography variant="h6" sx={{ color: '#ffffff', mb: 2 }}>
          Настройки системы
        </Typography>
        <Card sx={{ backgroundColor: '#1a1a1a', border: '1px solid #333' }}>
          <CardContent>
            <Typography sx={{ color: '#888' }}>
              Здесь будут настройки системы, управление операторами и другие административные функции.
            </Typography>
          </CardContent>
        </Card>
      </TabPanel>

      {/* Create Quiz Dialog */}
      <Dialog
        open={quizDialogOpen}
        onClose={() => {
          setQuizDialogOpen(false);
          setEditingQuiz(null);
          resetQuestions();
        }}
        maxWidth="lg"
        fullWidth
        PaperProps={{
          sx: {
            backgroundColor: '#1a1a1a',
            border: '1px solid #333',
          },
        }}
      >
        <DialogTitle sx={{ color: '#ffffff' }}>
          {editingQuiz ? 'Редактировать викторину' : 'Создать викторину'}
        </DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            label="Название"
            value={editingQuiz?.title || newQuiz.title}
            onChange={(e) => {
              if (editingQuiz) {
                setEditingQuiz(prev => prev ? { ...prev, title: e.target.value } : null);
              } else {
                setNewQuiz(prev => ({ ...prev, title: e.target.value }));
              }
            }}
            margin="normal"
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
            }}
          />
          <TextField
            fullWidth
            label="Описание"
            value={editingQuiz?.description || newQuiz.description}
            onChange={(e) => {
              if (editingQuiz) {
                setEditingQuiz(prev => prev ? { ...prev, description: e.target.value } : null);
              } else {
                setNewQuiz(prev => ({ ...prev, description: e.target.value }));
              }
            }}
            margin="normal"
            multiline
            rows={3}
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
            }}
          />
          <TextField
            fullWidth
            label="URL изображения"
            value={editingQuiz?.image_url || newQuiz.image_url}
            onChange={(e) => {
              if (editingQuiz) {
                setEditingQuiz(prev => prev ? { ...prev, image_url: e.target.value } : null);
              } else {
                setNewQuiz(prev => ({ ...prev, image_url: e.target.value }));
              }
            }}
            margin="normal"
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
            }}
          />
          <TextField
            fullWidth
            label="Награда (звезды)"
            type="number"
            value={editingQuiz?.reward_stars || newQuiz.reward_stars}
            onChange={(e) => {
              const value = parseInt(e.target.value) || 0;
              if (editingQuiz) {
                setEditingQuiz(prev => prev ? { ...prev, reward_stars: value } : null);
              } else {
                setNewQuiz(prev => ({ ...prev, reward_stars: value }));
              }
            }}
            margin="normal"
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
            }}
          />

          {/* Questions Section */}
          <Box sx={{ mt: 4, mb: 2 }}>
            <Typography variant="h6" sx={{ color: '#ffffff', mb: 2 }}>
              Вопросы ({questions.length})
            </Typography>

            {/* Current Question Form */}
            <Card sx={{ backgroundColor: '#2a2a2a', border: '1px solid #333', mb: 2 }}>
              <CardContent>
                <TextField
                  fullWidth
                  label="Текст вопроса"
                  value={currentQuestion.text}
                  onChange={(e) => setCurrentQuestion(prev => ({ ...prev, text: e.target.value }))}
                  margin="normal"
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      '& fieldset': { borderColor: '#333' },
                      '&:hover fieldset': { borderColor: '#FFD700' },
                    },
                    '& .MuiInputLabel-root': { color: '#888' },
                    '& .MuiInputBase-input': { color: '#ffffff' },
                  }}
                />

                <Box sx={{ mt: 2, mb: 2 }}>
                  <Typography variant="body2" sx={{ color: '#888', mb: 1 }}>
                    Тип вопроса: Несколько ответов
                  </Typography>
                </Box>

                {/* Options */}
                <Box sx={{ mt: 2 }}>
                  <Typography variant="body2" sx={{ color: '#888', mb: 1 }}>
                    Варианты ответов:
                  </Typography>
                  {currentQuestion.options?.map((option, index) => (
                    <Box key={option.id} sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                      <DragIndicator sx={{ color: '#666' }} />
                      <TextField
                        fullWidth
                        size="small"
                        placeholder={`Вариант ${index + 1}`}
                        value={option.text}
                        onChange={(e) => updateOption(option.id, 'text', e.target.value)}
                        sx={{
                          '& .MuiOutlinedInput-root': {
                            '& fieldset': { borderColor: '#333' },
                            '&:hover fieldset': { borderColor: '#FFD700' },
                          },
                          '& .MuiInputBase-input': { color: '#ffffff' },
                        }}
                      />
                      <IconButton
                        size="small"
                        onClick={() => updateOption(option.id, 'is_correct', !option.is_correct)}
                        sx={{
                          color: option.is_correct ? '#4CAF50' : '#666',
                          backgroundColor: option.is_correct ? 'rgba(76, 175, 80, 0.1)' : 'transparent',
                        }}
                      >
                        ✓
                      </IconButton>
                      {currentQuestion.options && currentQuestion.options.length > 2 && (
                        <IconButton
                          size="small"
                          onClick={() => removeOption(option.id)}
                          sx={{ color: '#f44336' }}
                        >
                          <Delete fontSize="small" />
                        </IconButton>
                      )}
                    </Box>
                  ))}

                  <Button
                    onClick={addOption}
                    startIcon={<Add />}
                    size="small"
                    sx={{ color: '#FFD700', mt: 1 }}
                  >
                    Добавить вариант
                  </Button>
                </Box>

                <Button
                  onClick={addQuestion}
                  variant="contained"
                  sx={{
                    backgroundColor: '#FFD700',
                    color: '#000000',
                    mt: 2,
                  }}
                  disabled={!currentQuestion.text?.trim() || !currentQuestion.options?.some(o => o.text.trim() !== '') || !currentQuestion.options?.some(o => o.is_correct)}
                >
                  Добавить вопрос
                </Button>
              </CardContent>
            </Card>

            {/* Questions List */}
            {questions.length > 0 && (
              <Box sx={{ mt: 2 }}>
                <Typography variant="body2" sx={{ color: '#888', mb: 1 }}>
                  Добавленные вопросы:
                </Typography>
                {questions.map((question, index) => (
                  <Card key={question.id} sx={{ backgroundColor: '#2a2a2a', border: '1px solid #333', mb: 1 }}>
                    <CardContent sx={{ py: 1 }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Box>
                          <Typography variant="body2" sx={{ color: '#ffffff' }}>
                            {index + 1}. {question.text}
                          </Typography>
                          <Typography variant="caption" sx={{ color: '#666' }}>
                            {question.type === 'single' ? 'Один ответ' : 'Несколько ответов'} • {question.options.length} вариантов
                          </Typography>
                        </Box>
                        <IconButton
                          size="small"
                          onClick={() => removeQuestion(index)}
                          sx={{ color: '#f44336' }}
                        >
                          <Delete fontSize="small" />
                        </IconButton>
                      </Box>
                    </CardContent>
                  </Card>
                ))}
              </Box>
            )}
          </Box>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => {
              setQuizDialogOpen(false);
              setEditingQuiz(null);
              resetQuestions();
            }}
            sx={{ color: '#888' }}
          >
            Отмена
          </Button>
          <Button
            onClick={() => {
              console.log('Button clicked, questions:', questions.length);
              console.log('Submitting:', submitting);
              if (editingQuiz) {
                handleUpdateQuiz();
              } else {
                handleCreateQuiz();
              }
            }}
            disabled={submitting}
            sx={{
              backgroundColor: '#FFD700',
              color: '#000000',
            }}
          >
            {submitting ? 'Сохранение...' : (editingQuiz ? 'Сохранить' : 'Создать')} ({questions.length})
          </Button>
        </DialogActions>
      </Dialog>

      {/* Create Reward Dialog */}
      <Dialog
        open={rewardDialogOpen}
        onClose={() => {
          setRewardDialogOpen(false);
          setEditingReward(null);
        }}
        maxWidth="md"
        fullWidth
        PaperProps={{
          sx: {
            backgroundColor: '#1a1a1a',
            border: '1px solid #333',
          },
        }}
      >
        <DialogTitle sx={{ color: '#ffffff' }}>
          {editingReward ? 'Редактировать приз' : 'Создать приз'}
        </DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            label="Название"
            value={editingReward?.title || newReward.title}
            onChange={(e) => {
              if (editingReward) {
                setEditingReward(prev => prev ? { ...prev, title: e.target.value } : null);
              } else {
                setNewReward(prev => ({ ...prev, title: e.target.value }));
              }
            }}
            margin="normal"
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
            }}
          />
          <TextField
            fullWidth
            label="Описание"
            value={editingReward?.description || newReward.description}
            onChange={(e) => {
              if (editingReward) {
                setEditingReward(prev => prev ? { ...prev, description: e.target.value } : null);
              } else {
                setNewReward(prev => ({ ...prev, description: e.target.value }));
              }
            }}
            margin="normal"
            multiline
            rows={3}
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
            }}
          />
          <TextField
            fullWidth
            label="URL изображения"
            value={editingReward?.image_url || newReward.image_url}
            onChange={(e) => {
              if (editingReward) {
                setEditingReward(prev => prev ? { ...prev, image_url: e.target.value } : null);
              } else {
                setNewReward(prev => ({ ...prev, image_url: e.target.value }));
              }
            }}
            margin="normal"
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
            }}
          />
          <TextField
            fullWidth
            label="Цена (звезды)"
            type="number"
            value={editingReward?.price_stars || newReward.price_stars}
            onChange={(e) => {
              const value = parseInt(e.target.value) || 0;
              if (editingReward) {
                setEditingReward(prev => prev ? { ...prev, price_stars: value } : null);
              } else {
                setNewReward(prev => ({ ...prev, price_stars: value }));
              }
            }}
            margin="normal"
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
            }}
          />
          <TextField
            fullWidth
            select
            label="Тип доставки"
            value={editingReward?.delivery_type || newReward.delivery_type}
            onChange={(e) => {
              const value = e.target.value as 'physical' | 'digital';
              if (editingReward) {
                setEditingReward(prev => prev ? { ...prev, delivery_type: value } : null);
              } else {
                setNewReward(prev => ({ ...prev, delivery_type: value }));
              }
            }}
            margin="normal"
            SelectProps={{
              native: true,
            }}
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
              '& .MuiSelect-select': { color: '#ffffff' },
            }}
          >
            <option value="digital">Цифровой</option>
            <option value="physical">Физический</option>
          </TextField>
          <TextField
            fullWidth
            label="Инструкции по получению"
            value={editingReward?.instructions || newReward.instructions}
            onChange={(e) => {
              if (editingReward) {
                setEditingReward(prev => prev ? { ...prev, instructions: e.target.value } : null);
              } else {
                setNewReward(prev => ({ ...prev, instructions: e.target.value }));
              }
            }}
            margin="normal"
            multiline
            rows={3}
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
            }}
          />
          <TextField
            fullWidth
            label="Количество на складе (-1 = бесконечно)"
            type="number"
            value={editingReward?.stock || newReward.stock}
            onChange={(e) => {
              const value = parseInt(e.target.value) || 0;
              if (editingReward) {
                setEditingReward(prev => prev ? { ...prev, stock: value } : null);
              } else {
                setNewReward(prev => ({ ...prev, stock: value }));
              }
            }}
            margin="normal"
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: '#333' },
                '&:hover fieldset': { borderColor: '#FFD700' },
              },
              '& .MuiInputLabel-root': { color: '#888' },
              '& .MuiInputBase-input': { color: '#ffffff' },
            }}
          />
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => {
              setRewardDialogOpen(false);
              setEditingReward(null);
            }}
            sx={{ color: '#888' }}
          >
            Отмена
          </Button>
          <Button
            onClick={editingReward ? handleUpdateReward : handleCreateReward}
            disabled={submitting}
            sx={{
              backgroundColor: '#FFD700',
              color: '#000000',
            }}
          >
            {submitting ? 'Сохранение...' : (editingReward ? 'Сохранить' : 'Создать')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};