import React, { useEffect, useState } from 'react';

import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import CircularProgress from '@mui/material/CircularProgress';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import MenuItem from '@mui/material/MenuItem';
import { useNavigate, useParams } from 'react-router-dom';
import { observer } from 'mobx-react-lite';

import { adminApi } from '../../../../api';
import { ApiError } from '../../../../api/httpClient.ts';
import { useStore } from '../../../../shared/hooks/useStore.ts';

const AdminNewsEditFormComponent: React.FC = () => {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const { news } = useStore();
  const currentNews = slug ? news.getBySlug(slug) : undefined;

  const [form, setForm] = useState({
    title: '',
    slug: '',
    summary: '',
    content: '',
    imageUrl: '',
    status: 'draft' as 'draft' | 'published' | 'archived',
  });
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    if (slug && !currentNews && !news.isLoading) {
      void news.fetchBySlug(slug).catch(() => {
        /* error handled via store */
      });
    }
  }, [slug, currentNews, news]);

  useEffect(() => {
    if (!currentNews) {
      return;
    }
    setForm({
      title: currentNews.title,
      slug: currentNews.slug,
      summary: currentNews.summary,
      content: currentNews.content,
      imageUrl: currentNews.imageUrl ?? '',
      status: currentNews.status,
    });
  }, [currentNews, currentNews?.id]);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = event.target;
    setForm((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!slug) {
      return;
    }

    setIsSaving(true);
    setError(null);
    setSuccess(null);

    try {
      const payload = {
        title: form.title.trim(),
        slug: form.slug.trim(),
        summary: form.summary.trim(),
        content: form.content.trim(),
        imageUrl: form.imageUrl.trim() || undefined,
        status: form.status,
      };
      await adminApi.updateNews(slug, payload);
      await news.fetchBySlug(payload.slug);
      setSuccess('Новость успешно обновлена.');
      if (payload.slug !== slug) {
        navigate(`/admin/dashboard/news/${payload.slug}/edit`, { replace: true });
      }
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message || 'Не удалось сохранить изменения.');
      } else {
        setError('Не удалось сохранить изменения.');
      }
    } finally {
      setIsSaving(false);
    }
  };

  const isLoadingEntry = news.isLoading && !currentNews;

  return (
    <Box component="form" onSubmit={handleSubmit} sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <Stack direction="row" spacing={2} alignItems="center" justifyContent="space-between" flexWrap="wrap">
        <div>
          <Typography variant="h5">Редактирование новости</Typography>
          <Typography color="text.secondary">Обновите содержимое и сохраните изменения.</Typography>
        </div>
        <Button variant="outlined" size="small" onClick={() => navigate('/admin/dashboard/news')}>
          Назад к списку
        </Button>
      </Stack>

      {isLoadingEntry && (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress size={28} />
        </Box>
      )}

      {!isLoadingEntry && news.error && <Alert severity="error">{news.error}</Alert>}

      {!isLoadingEntry && !currentNews && !news.error && <Alert severity="warning">Новость не найдена. Возможно, она была удалена.</Alert>}

      {!isLoadingEntry && currentNews && (
        <Stack spacing={2}>
          {error && <Alert severity="error">{error}</Alert>}
          {success && <Alert severity="success">{success}</Alert>}
          <TextField label="Заголовок" name="title" required value={form.title} onChange={handleChange} fullWidth />
          <TextField label="Slug" name="slug" required value={form.slug} onChange={handleChange} helperText="Используется в URL новости" fullWidth />
          <TextField label="Краткое описание" name="summary" required value={form.summary} onChange={handleChange} fullWidth />
          <TextField label="Содержимое" name="content" required multiline rows={6} value={form.content} onChange={handleChange} fullWidth />
          <TextField
            label="Изображение (URL)"
            name="imageUrl"
            value={form.imageUrl}
            onChange={handleChange}
            placeholder="https://example.com/image.jpg"
            fullWidth
          />
          <TextField select label="Статус" name="status" value={form.status} onChange={handleChange} required fullWidth>
            <MenuItem value="draft">Черновик</MenuItem>
            <MenuItem value="published">Опубликовано</MenuItem>
            <MenuItem value="archived">Архив</MenuItem>
          </TextField>
          <Stack direction="row" spacing={2} justifyContent="flex-end">
            <Button type="submit" variant="contained" disabled={isSaving}>
              {isSaving ? 'Сохраняем…' : 'Сохранить изменения'}
            </Button>
          </Stack>
        </Stack>
      )}
    </Box>
  );
};

export const AdminNewsEditForm = observer(AdminNewsEditFormComponent);
