import React, { useState, useEffect, useRef } from 'react';

import { CertEditor } from '../Editors/CertEditor'

const isValidImage = (file) => {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
  if (allowedTypes.includes(file.type)) return true;

  const ext = file.name.split('.').pop().toLowerCase();
  return ['jpg', 'jpeg', 'png'].includes(ext);
};

export function StocksForm({ initStocks, onChange }) {
  const [ initialStocks, setInitialStocks ] = useState([]);
  const [ stocks, setStocks ] = useState([]);
  
  const startDateInputRef = useRef(null);
  const endDateInputRef = useRef(null);

  useEffect(() => {
    // console.log(initStocks)
    // console.log(initStocks[0]?.startDate)
    // console.log(typeof initStocks[0]?.startDate)
    const portfolioWithPictureUrl = initStocks.map((init) => {
      if ( init.picture ) return ({ ...init, picture: `https://api.sovamed.ru/uploads/${init.picture}`})
      return { ...init }
    }).map(init => {
      const dateStart = new Date(init.startDate);

      const year = dateStart.getFullYear();
      const month = String(dateStart.getMonth() + 1).padStart(2, '0'); // Month is 0-indexed
      const day = String(dateStart.getDate()).padStart(2, '0');
      const hours = String(dateStart.getHours()).padStart(2, '0');
      const minutes = String(dateStart.getMinutes()).padStart(2, '0');
      const datetimeLocalValue = `${year}-${month}-${day}T${hours}:${minutes}`;

      const dateEnd = new Date(init.endDate);

      const year1 = dateEnd.getFullYear();
      const month1 = String(dateEnd.getMonth() + 1).padStart(2, '0'); // Month is 0-indexed
      const day1 = String(dateEnd.getDate()).padStart(2, '0');
      const hours1 = String(dateEnd.getHours()).padStart(2, '0');
      const minutes1 = String(dateEnd.getMinutes()).padStart(2, '0');
      const datetimeLocalValue1 = `${year1}-${month1}-${day1}T${hours1}:${minutes1}`;

      return ({ ...init, startDate: datetimeLocalValue, endDate: datetimeLocalValue1 });
    })
    setInitialStocks([...portfolioWithPictureUrl])
    setStocks([...portfolioWithPictureUrl])
  }, [initStocks])

    useEffect(() => {
    if (typeof onChange === 'function') {
      onChange(stocks);
    }
  }, [stocks, onChange]);

  const updateField = (idx, field, value) => {
    setStocks(prev =>
      prev.map((cert, i) =>
        i === idx
          ? { ...cert, [field]: value }
          : cert
      )
    );
  };

  const replaceImage = (e, idx) => {
    const file = e.target.files[0];
    if (!file) return;
    if (!isValidImage(file)) {
      return window.alert('Изображения должны быть только формата JPG, JPEG или PNG');
    }
    const url = window.URL.createObjectURL(file);
    setStocks(prev =>
      prev.map((cert, i) =>
        i === idx
          ? { ...cert, picture: url, _file: file }
          : cert
      )
    );
    // console.log('==================')
    // console.log(file)
  };

  const addCertificate = () => {
    setStocks(prev => [
      ...prev,
      { name: '', description: '', picture: '', type: 'portfolio', active: false }
    ]);
  };

  const deleteCertificate = idx => {
    setStocks(prev => prev.filter((_, i) => i !== idx));
  };

  return (
    <>
      {stocks.map((cert, idx) => (
        <div className="card mb-3 p-3" key={idx}>
          <div className="form-group" style={{ pointerEvents: 'none' }}>
            <label>Название</label>
            <input
              className="form-control"
              value={cert.name}
              onChange={e => updateField(idx, 'name', e.target.value)}
              // readOnly={true}
            />
          </div>

          <div className="form-group" style={{ pointerEvents: 'none' }}>
            <label>Анонс</label>
            <CertEditor
              content={cert.anons}
              setContent={newVal => updateField(idx, 'anons', newVal)}
              readOnly={true}
            />
          </div>
          <div className="form-group" style={{ pointerEvents: 'none' }}>
            <label>Описание</label>
            <CertEditor
              content={cert.content}
              setContent={newVal => updateField(idx, 'contnet', newVal)}
              readOnly={true}
            />
          </div>
          <div>

      <div className='d-flex justify-content-between' style={{ gap: '1rem' }}>
        <div className='form-group d-flex flex-column'>

          <div className="form-group"  style={{ pointerEvents: 'none' }}>
        <label>Начало акции:</label>
        <input
          type="datetime-local"
          ref={startDateInputRef}
          className="form-control"
          value={cert.startDate}
          onClick={() => {
            if (startDateInputRef.current?.showPicker) {
              startDateInputRef.current.showPicker();
            }
          }}
          onChange={e => updateField(idx, 'startDate', e.target.value)}
        />
      </div>

      <div className="form-group"  style={{ pointerEvents: 'none' }}>
        <label>Окончание акции:</label>
        <input
          type="datetime-local"
          ref={endDateInputRef}
          className="form-control"
          value={cert.endDate}
          onClick={() => {
            if (endDateInputRef.current?.showPicker) {
              endDateInputRef.current.showPicker();
            }
          }}
          onChange={e => updateField(idx, 'endDate', e.target.value)}
        />
      </div>
      <label>
        *Время указывается по МСК
      </label>

        </div>

      <div className="form-group d-flex flex-column align-items-center" style={{ gap: '1rem' }}>
            {cert.picture && (
              <img
                src={cert.picture}
                alt="Портфолио"
                style={{ width: '10rem', height: '10rem', objectFit: 'cover', borderRadius: '4px' }}
                onError={e => e.currentTarget.src = '/placeholder.png'}
              />
            )}
          </div>
          </div>

          </div>

          <div className='d-flex justify-content-start'>
            <button
            className="btn btn-danger"
            onClick={() => deleteCertificate(idx)}
          >
            Удалить
          </button>
          </div>
        </div>
      ))} 
    </>
  );
}
