import React, { useState } from 'react';

import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
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 } from 'react-router-dom';

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

const defaultForm: AdminNewsCreatePayload = {
  title: '',
  slug: '',
  summary: '',
  content: '',
  imageUrl: '',
  status: 'draft',
};

export const AdminNewsCreateForm: React.FC = () => {
  const navigate = useNavigate();
  const { news } = useStore();
  const [form, setForm] = useState(defaultForm);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);

  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();
    setIsSaving(true);
    setError(null);
    setSuccess(null);

    const payload: AdminNewsCreatePayload = {
      title: form.title.trim(),
      slug: form.slug.trim(),
      summary: form.summary.trim(),
      content: form.content.trim(),
      imageUrl: form.imageUrl?.trim() || null,
      status: form.status,
    };

    try {
      await adminApi.createNews(payload);
      await news.fetchBySlug(payload.slug);
      setSuccess('Новость создана.');
      navigate(`/admin/dashboard/news`, { replace: true });
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message || 'Не удалось создать новость.');
      } else {
        setError('Не удалось создать новость.');
      }
    } finally {
      setIsSaving(false);
    }
  };

  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>

      {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} />
      <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>
    </Box>
  );
};
