import { 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 Typography from '@mui/material/Typography';
import { useNavigate } from 'react-router-dom';

import { adminApi } from '../../../../api';
import { ApiError } from '../../../../api/httpClient.ts';
import { useStore } from '../../../../shared/hooks/useStore.ts';
import { ServiceCategoryForm } from './service-category-form.tsx';
import {
  defaultServiceCategoryFormValues,
  mapCategoryFormToCreatePayload,
  type ServiceCategoryFormValues,
} from './service-category-form.helpers.ts';

export const AdminServiceCategoryCreateForm: React.FC = () => {
  const navigate = useNavigate();
  const { adminServiceCategories } = useStore();
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleSubmit = async (values: ServiceCategoryFormValues) => {
    setError(null);
    setSuccess(null);
    setIsSubmitting(true);

    try {
      const payload = mapCategoryFormToCreatePayload(values);
      await adminApi.createServiceCategory(payload);
      await adminServiceCategories.fetch();
      setSuccess('Категория создана.');
      navigate('/admin/dashboard/categories', { replace: true });
    } catch (err) {
      const message = err instanceof ApiError ? err.message : 'Не удалось создать категорию. Попробуйте позже.';
      setError(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <Stack direction={{ xs: 'column', md: 'row' }} spacing={2} justifyContent="space-between" alignItems={{ xs: 'flex-start', md: 'center' }}>
        <div>
          <Typography variant="h5">Новая категория</Typography>
          <Typography color="text.secondary">Введите название и slug категории.</Typography>
        </div>
        <Button variant="outlined" size="small" onClick={() => navigate(-1)}>
          Назад
        </Button>
      </Stack>

      {error && <Alert severity="error">{error}</Alert>}
      {success && <Alert severity="success">{success}</Alert>}

      <ServiceCategoryForm
        initialValues={defaultServiceCategoryFormValues}
        submitLabel="Создать категорию"
        onSubmit={handleSubmit}
        onCancel={() => navigate('/admin/dashboard/categories')}
        isSubmitting={isSubmitting}
      />
    </Box>
  );
};
