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 { ServiceForm } from './service-form.tsx';
import { createServiceFormValues, mapServiceFormToCreatePayload, type ServiceFormValues } from './service-form.helpers.ts';

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

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

    try {
      const payload = mapServiceFormToCreatePayload(values);
      await adminApi.createService(payload);
      setSuccess('Услуга успешно создана.');
      navigate('/admin/dashboard/services', { 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">Заполните данные и сохраните новую услугу.</Typography>
        </div>
        <Button variant="outlined" size="small" onClick={() => navigate(-1)}>
          Назад
        </Button>
      </Stack>

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

      <ServiceForm
        mode="create"
        initialValues={createServiceFormValues()}
        isSubmitting={isSubmitting}
        submitLabel="Создать услугу"
        onSubmit={handleSubmit}
        onCancel={() => navigate('/admin/dashboard/services')}
      />
    </Box>
  );
};
