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

import { adminApi } from '../../../../api';
import { ApiError } from '../../../../api/httpClient.ts';
import { useStore } from '../../../../shared/hooks/useStore.ts';
import { ServiceForm } from './service-form.tsx';
import { createServiceFormValues, mapServiceFormToUpdatePayload, type ServiceFormValues } from './service-form.helpers.ts';

export const AdminServiceEditForm: React.FC = () => {
  const navigate = useNavigate();
  const { services } = useStore();
  const { serviceId } = useParams<{ serviceId: string }>();

  const [fetchError, setFetchError] = useState<string | null>(null);
  const [isFetching, setIsFetching] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const [formSuccess, setFormSuccess] = useState<string | null>(null);

  const currentService = useMemo(() => {
    if (!serviceId) {
      return null;
    }
    return services.getById(serviceId) ?? services.getBySlug(serviceId) ?? null;
  }, [serviceId, services]);

  useEffect(() => {
    if (!serviceId || currentService) {
      return;
    }

    const load = async () => {
      setIsFetching(true);
      setFetchError(null);
      try {
        await services.fetchBySlugAdmin(serviceId);
      } catch (err) {
        const message =
          err instanceof ApiError ? err.message : 'Не удалось загрузить услугу для редактирования. Попробуйте позже.';
        setFetchError(message);
      } finally {
        setIsFetching(false);
      }
    };

    void load();
  }, [currentService, serviceId, services]);

  const initialValues = useMemo(() => {
    if (!currentService) {
      return createServiceFormValues();
    }
    return createServiceFormValues(currentService.toJSON());
  }, [currentService]);

  const handleSubmit = async (values: ServiceFormValues) => {
    if (!serviceId) {
      setFormError('Не удалось определить идентификатор услуги.');
      return;
    }
    setFormError(null);
    setFormSuccess(null);
    setIsSubmitting(true);

    try {
      const payload = mapServiceFormToUpdatePayload(values);
      await adminApi.updateService(serviceId, payload);
      setFormSuccess('Изменения сохранены.');
      await services.fetchBySlugAdmin(serviceId);
      navigate('/admin/dashboard/services');
    } catch (err) {
      const message = err instanceof ApiError ? err.message : 'Не удалось сохранить изменения. Попробуйте позже.';
      setFormError(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!serviceId) {
    return (
      <Alert severity="error">
        Не указан идентификатор услуги. Вернитесь к списку и попробуйте снова.
      </Alert>
    );
  }

  if (isFetching && !currentService) {
    return (
      <Stack spacing={2} alignItems="center">
        <CircularProgress size={32} />
        <Typography>Загружаем данные услуги...</Typography>
      </Stack>
    );
  }

  if (fetchError && !currentService) {
    return (
      <Stack spacing={2}>
        <Alert severity="error">{fetchError}</Alert>
        <Button variant="outlined" onClick={() => navigate('/admin/dashboard/services')}>
          Вернуться к списку
        </Button>
      </Stack>
    );
  }

  if (!currentService) {
    return (
      <Alert severity="warning">
        Услуга не найдена. Возможно, она была удалена. Вернитесь к списку и попробуйте снова.
      </Alert>
    );
  }

  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">{currentService.title}</Typography>
        </div>
        <Button variant="outlined" size="small" onClick={() => navigate(-1)}>
          Назад
        </Button>
      </Stack>

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

      <ServiceForm
        mode="edit"
        initialValues={initialValues}
        submitLabel="Сохранить изменения"
        isSubmitting={isSubmitting}
        onSubmit={handleSubmit}
        onCancel={() => navigate('/admin/dashboard/services')}
      />
    </Box>
  );
};
