import { useEffect, useMemo, useState } from 'react';

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 {
  defaultServiceCategoryFormValues,
  type ServiceCategoryFormValues,
} from './service-category-form.helpers.ts';

type FieldErrors = Partial<Record<keyof ServiceCategoryFormValues, string>>;

export interface ServiceCategoryFormProps {
  initialValues?: ServiceCategoryFormValues;
  submitLabel: string;
  onSubmit: (values: ServiceCategoryFormValues) => Promise<void>;
  onCancel: () => void;
  isSubmitting: boolean;
}

export const ServiceCategoryForm: React.FC<ServiceCategoryFormProps> = ({
  initialValues,
  submitLabel,
  onSubmit,
  onCancel,
  isSubmitting,
}) => {
  const [form, setForm] = useState<ServiceCategoryFormValues>(initialValues ?? defaultServiceCategoryFormValues);
  const [errors, setErrors] = useState<FieldErrors>({});

  const initialKey = useMemo(() => JSON.stringify(initialValues ?? defaultServiceCategoryFormValues), [initialValues]);

  useEffect(() => {
    if (initialValues) {
      setForm(initialValues);
    } else {
      setForm(defaultServiceCategoryFormValues);
    }
  }, [initialKey, initialValues]);

  const validate = () => {
    const next: FieldErrors = {};
    if (!form.name.trim()) {
      next.name = 'Введите название категории';
    }
    if (!form.slug.trim()) {
      next.slug = 'Введите slug категории';
    }
    setErrors(next);
    return Object.keys(next).length === 0;
  };

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target;
    setForm((prev) => ({
      ...prev,
      [name]: value,
    }));
    if (errors[name as keyof ServiceCategoryFormValues]) {
      setErrors((prev) => ({
        ...prev,
        [name]: undefined,
      }));
    }
  };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!validate()) {
      return;
    }
    await onSubmit(form);
  };

  return (
    <Box component="form" onSubmit={handleSubmit} sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <TextField
        label="Название"
        name="name"
        value={form.name}
        onChange={handleChange}
        required
        error={Boolean(errors.name)}
        helperText={errors.name}
        fullWidth
      />
      <TextField
        label="Slug"
        name="slug"
        value={form.slug}
        onChange={handleChange}
        required
        error={Boolean(errors.slug)}
        helperText={errors.slug ?? 'Используется в URL категории'}
        fullWidth
      />
      <Stack direction="row" spacing={2} justifyContent="flex-end" flexWrap="wrap">
        <Button variant="outlined" color="inherit" onClick={onCancel} disabled={isSubmitting}>
          Отмена
        </Button>
        <Button type="submit" variant="contained" disabled={isSubmitting}>
          {isSubmitting ? 'Сохраняем…' : submitLabel}
        </Button>
      </Stack>
    </Box>
  );
};
