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 { ServiceCategoryForm } from './service-category-form.tsx';
import {
  createServiceCategoryFormValues,
  mapCategoryFormToUpdatePayload,
  type ServiceCategoryFormValues,
} from './service-category-form.helpers.ts';

export const AdminServiceCategoryEditForm: React.FC = () => {
  const navigate = useNavigate();
  const { categoryId } = useParams<{ categoryId: string }>();
  const { adminServiceCategories } = useStore();

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

  const currentCategory = useMemo(() => {
    if (!categoryId) {
      return null;
    }
    return adminServiceCategories.getById(categoryId) ?? null;
  }, [adminServiceCategories, categoryId]);

  useEffect(() => {
    if (adminServiceCategories.isLoading || adminServiceCategories.list.length > 0 || !categoryId || currentCategory) {
      return;
    }

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

    void load();
  }, [adminServiceCategories, categoryId, currentCategory]);

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

  const handleSubmit = async (values: ServiceCategoryFormValues) => {
    if (!categoryId) {
      setFormError('Не указан идентификатор категории.');
      return;
    }

    setFormError(null);
    setFormSuccess(null);
    setIsSubmitting(true);

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

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

  if (isFetching && !currentCategory) {
    return (
      <Stack spacing={2} alignItems="center">
        <CircularProgress size={32} />
        <Typography>Загружаем категорию...</Typography>
      </Stack>
    );
  }

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

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

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

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