import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { useCreateDiseaseMutation } from '/src/api/apiDisease';
import { selectRegions } from '../store/slice/regionSlice';
import { TextEditor } from '../components/Editors/TextEditor';
import { LoadingComponent } from '../components/Placeholders/LoadingComponent';
import { ErrorComponent } from '../components/Placeholders/ErrorComponent';
import { NotFindElement } from '../components/Placeholders/NotFindElement';
import { EditElementForm } from '../components/Forms/EditElementForm';
import Modal from '../components/Modals/Modal';

export function AddDiseasePage() {
  
  const navigate = useNavigate();
  const navigateBack = () => navigate(`/disease`);
  const regions = useSelector(selectRegions);
  const [createDisease] = useCreateDiseaseMutation();
  const [isModalSuccess, setModalSuccess] = useState(false);
  const [errors, setErrors] = useState({ name: '', alias: '', regionId: '' });
  const [form, setForm] = useState({
    name: '',
    active: false,
    regionId: '',
    alias: '',
    previewPicture: '',
    hidePicture: false,
    readTime: '',
    diseasesName: '',
    diseasesOtherName: '',
    symptom: '',
    staff: '',
    bibliography: '',
    tagsImportant: '',
    tags: '',
    linkServices: '',
    staffList: '',
    staffPost: '',
    staffPostExclude: '',
    linkFaq: '',
    staffCheck: '',
  });
  const [anons, setAnons] = useState('');
  const [content, setContent] = useState('');

  

  const handleChange = (key) => (e) => {
    const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
    setForm((f) => ({ ...f, [key]: value }));
    if (key === 'name' || key === 'alias' || key === 'regionId') setErrors((err) => ({ ...err, [key]: '' }));
  };

  

  const handleSave = async () => {
    const newErrors = { name: '', alias: '', regionId: '' };
    let hasError = false;
    if (!String(form.name ?? '').trim()) { newErrors.name = 'Название не может быть пустым'; hasError = true; }
    if (!String(form.alias ?? '').trim()) { newErrors.alias = 'Alias не может быть пустым'; hasError = true; }
    if (form.regionId === '' || form.regionId == null) { newErrors.regionId = 'Укажите регион'; hasError = true; }
    if (hasError) { setErrors(newErrors); window.alert('Пожалуйста исправьте ошибки в форме.'); return; }
    const data = { anons, content };
    try {
      data.name = form.name === '' ? null : form.name;
      data.active = Boolean(form.active);
      data.regionId = form.regionId === '' ? null : Number(form.regionId);
      data.alias = form.alias === '' ? null : form.alias;
      data.previewPicture = form.previewPicture === '' ? null : form.previewPicture;
      data.hidePicture = Boolean(form.hidePicture);
      data.readTime = form.readTime === '' ? null : form.readTime;
      data.diseasesName = form.diseasesName === '' ? null : form.diseasesName;
      data.diseasesOtherName = form.diseasesOtherName === '' ? null : form.diseasesOtherName;
      data.symptom = form.symptom === '' ? null : form.symptom;
      data.staff = form.staff === '' ? null : form.staff;
      data.bibliography = form.bibliography === '' ? null : form.bibliography;
      data.tagsImportant = !form.tagsImportant || !String(form.tagsImportant).trim() ? null : JSON.parse(form.tagsImportant);
      data.tags = !form.tags || !String(form.tags).trim() ? null : JSON.parse(form.tags);
      data.linkServices = !form.linkServices || !String(form.linkServices).trim() ? null : JSON.parse(form.linkServices);
      data.staffList = !form.staffList || !String(form.staffList).trim() ? null : JSON.parse(form.staffList);
      data.staffPost = !form.staffPost || !String(form.staffPost).trim() ? null : JSON.parse(form.staffPost);
      data.staffPostExclude = !form.staffPostExclude || !String(form.staffPostExclude).trim() ? null : JSON.parse(form.staffPostExclude);
      data.linkFaq = !form.linkFaq || !String(form.linkFaq).trim() ? null : JSON.parse(form.linkFaq);
      data.staffCheck = !form.staffCheck || !String(form.staffCheck).trim() ? null : JSON.parse(form.staffCheck);
    } catch (e) { window.alert('Пожалуйста исправьте ошибки в форме.'); return; }
    try {
      const response = await createDisease({ data }).unwrap();
      setModalSuccess(true);
      window.setTimeout(() => { navigate(`/disease/edit/${response.id}`); window.location.reload(); }, 2000);
    } catch (err) {
      console.error('Ошибка сохранения:', err);
    }
  };

  

  return (
    <EditElementForm navigateBack={navigateBack} header={`Добавление: заболевание`} handleSave={handleSave} handleDelete={() => {}} isAddSpecialist={true}>
      <div className="form-group"><label>Название</label><input type="text" className="form-control" value={form.name} onChange={handleChange('name')} />
        {errors.name && <small className="text-danger">{errors.name}</small>}</div>
      <div className="form-group form-check"><input type="checkbox" className="form-check-input" id="active" checked={Boolean(form.active)} onChange={handleChange('active')} /><label className="form-check-label" htmlFor="active">Активно</label></div>
      <div className="form-group"><label>Регион</label><select className="form-control" value={form.regionId === '' || form.regionId == null ? '' : String(form.regionId)} onChange={handleChange('regionId')}><option value="">—</option>{Object.entries(regions).map(([rid, name]) => (<option key={rid} value={rid}>{name}</option>))}</select>
        {errors.regionId && <small className="text-danger">{errors.regionId}</small>}</div>
      <div className="form-group"><label>Alias</label><input type="text" className="form-control" value={form.alias} onChange={handleChange('alias')} />
        {errors.alias && <small className="text-danger">{errors.alias}</small>}</div>
      <div className="form-group"><label>Анонс</label><TextEditor content={anons} setContent={setAnons} /></div>
      <div className="form-group"><label>Контент</label><TextEditor content={content} setContent={setContent} /></div>
      <div className="form-group"><label>previewPicture</label><input type="text" className="form-control" value={form.previewPicture} onChange={handleChange('previewPicture')} /></div>
      <div className="form-group form-check"><input type="checkbox" className="form-check-input" id="hidePicture" checked={Boolean(form.hidePicture)} onChange={handleChange('hidePicture')} /><label className="form-check-label" htmlFor="hidePicture">hidePicture</label></div>
      <div className="form-group"><label>readTime</label><input type="text" className="form-control" value={form.readTime} onChange={handleChange('readTime')} /></div>
      <div className="form-group"><label>diseasesName</label><input type="text" className="form-control" value={form.diseasesName} onChange={handleChange('diseasesName')} /></div>
      <div className="form-group"><label>diseasesOtherName</label><input type="text" className="form-control" value={form.diseasesOtherName} onChange={handleChange('diseasesOtherName')} /></div>
      <div className="form-group"><label>symptom</label><input type="text" className="form-control" value={form.symptom} onChange={handleChange('symptom')} /></div>
      <div className="form-group"><label>staff</label><input type="text" className="form-control" value={form.staff} onChange={handleChange('staff')} /></div>
      <div className="form-group"><label>bibliography</label><input type="text" className="form-control" value={form.bibliography} onChange={handleChange('bibliography')} /></div>
      <div className="form-group"><label>tagsImportant (JSON)</label><textarea className="form-control font-monospace" rows={4} value={form.tagsImportant} onChange={handleChange('tagsImportant')} /></div>
      <div className="form-group"><label>tags (JSON)</label><textarea className="form-control font-monospace" rows={4} value={form.tags} onChange={handleChange('tags')} /></div>
      <div className="form-group"><label>linkServices (JSON)</label><textarea className="form-control font-monospace" rows={4} value={form.linkServices} onChange={handleChange('linkServices')} /></div>
      <div className="form-group"><label>staffList (JSON)</label><textarea className="form-control font-monospace" rows={4} value={form.staffList} onChange={handleChange('staffList')} /></div>
      <div className="form-group"><label>staffPost (JSON)</label><textarea className="form-control font-monospace" rows={4} value={form.staffPost} onChange={handleChange('staffPost')} /></div>
      <div className="form-group"><label>staffPostExclude (JSON)</label><textarea className="form-control font-monospace" rows={4} value={form.staffPostExclude} onChange={handleChange('staffPostExclude')} /></div>
      <div className="form-group"><label>linkFaq (JSON)</label><textarea className="form-control font-monospace" rows={4} value={form.linkFaq} onChange={handleChange('linkFaq')} /></div>
      <div className="form-group"><label>staffCheck (JSON)</label><textarea className="form-control font-monospace" rows={4} value={form.staffCheck} onChange={handleChange('staffCheck')} /></div>
      <Modal isOpen={isModalSuccess} title="Изменения внесены" hasButtons={false}><p className="mb-1">Изменения успешно внесены.</p></Modal>
    </EditElementForm>
  );
}
