import React, { useState, FormEvent, ChangeEvent } from "react";
import { useNavigate } from "react-router-dom";
import { FiPlus } from "react-icons/fi";
import { GoogleMap, useJsApiLoader, Marker } from '@react-google-maps/api';
import { toast } from 'react-toastify';

import mapMarkerImg from '../images/map_marker.svg';
import '../styles/create-orphanage.css';
import Sidebar from "../components/Sidebar";
import api from "../services/api";

export default function CreateOrphanage() {
  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: process.env.REACT_APP_MAPS_API_KEY!
  });

  const navigate = useNavigate();

  const [position, setPosition] = useState({ lat: 0, lng: 0 });
  const [name, setName] = useState('');
  const [about, setAbout] = useState('');
  const [instructions, setInstructions] = useState('');
  const [opening_hours, setOpeningHours] = useState('');
  const [open_on_weekends, setOpenOnWeekends] = useState(true);
  const [phone, setPhone] = useState('');
  const [images, setImages] = useState<File[]>([]);
  const [previewImages, setPreviewImages] = useState<string[]>([]);

  function handleMapClick(event: google.maps.MapMouseEvent) {
    const { latLng } = event;
    if (latLng) {
      setPosition({
        lat: latLng.lat(),
        lng: latLng.lng(),
      });
    }
  }

  function handleSelectImages(event: ChangeEvent<HTMLInputElement>) {
    if (!event.target.files) {
      return;
    }
    const selectedImages = Array.from(event.target.files);
    setImages(selectedImages);

    const selectedImagesPreview = selectedImages.map(image => {
      return URL.createObjectURL(image);
    });

    setPreviewImages(selectedImagesPreview);
  }

  async function handleSubmit(event: FormEvent) {
    event.preventDefault();

    if (!name.trim()) {
      toast.error('O campo "Nome" é obrigatório.');
      return;
    }
    if (!about.trim()) {
      toast.error('O campo "Sobre" é obrigatório.');
      return;
    }
    if (!opening_hours.trim()) {
      toast.error('O campo "Horário de funcionamento" é obrigatório.');
      return;
    }
    if (position.lat === 0) {
      toast.error('Por favor, selecione a localização do orfanato no mapa.');
      return;
    }
    if (images.length === 0) {
      toast.error('Por favor, adicione pelo menos uma foto do orfanato.');
      return;
    }
    if (!phone.trim()) {
      toast.error('O campo "Número de Whatsapp" é obrigatório.');
      return;
    }

    const { lat, lng } = position;

    const data = new FormData();
    data.append('name', name);
    data.append('about', about);
    data.append('latitude', String(lat));
    data.append('longitude', String(lng));
    data.append('instructions', instructions);
    data.append('opening_hours', opening_hours);
    data.append('open_on_weekends', String(open_on_weekends));
    data.append('phone', phone);

    images.forEach(image => {
      data.append('images', image);
    });

    try {
      await api.post('orphanages', data);
      toast.success('Cadastro realizado com sucesso!');
      navigate('/app');
    } catch (error) {
      toast.error('Erro ao realizar o cadastro. Tente novamente.');
      console.error('Failed to create orphanage:', error);
    }
  }

  if (!isLoaded) {
    return <div>Loading Map...</div>;
  }

  return (
    <div id="page-create-orphanage">
      <Sidebar />
      <main>
        <form onSubmit={handleSubmit} className="create-orphanage-form">
          <fieldset>
            <legend>Dados</legend>

            <GoogleMap
              mapContainerStyle={{ width: '100%', height: 280 }}
              center={{ lat: -23.9550537, lng: -46.3204442 }}
              zoom={12}
              onClick={handleMapClick}
            >
              {position.lat !== 0 && (
                <Marker
                  position={{ lat: position.lat, lng: position.lng }}
                  icon={{
                    url: mapMarkerImg,
                    scaledSize: new window.google.maps.Size(58, 68),
                  }}
                />
              )}
            </GoogleMap>

            <div className="input-block">
              <label htmlFor="name">Nome</label>
              <input id="name" value={name} maxLength={50} onChange={e => setName(e.target.value)} />
            </div>

            <div className="input-block">
              <label htmlFor="about">Sobre <span>Máximo de 300 caracteres</span></label>
              <textarea id="about" maxLength={300} value={about} onChange={e => setAbout(e.target.value)} />
            </div>

            <div className="input-block">
              <label htmlFor="phone">Número de Whatsapp</label>
              <input
                  id="phone"
                  value={phone}
                  onChange={e => setPhone(e.target.value)}
              />
            </div>

            <div className="input-block">
              <label htmlFor="images">Fotos</label>
              <div className="images-container">
                {previewImages.map(image => (
                  <img key={image} src={image} alt={name}/>
                ))}
                <label htmlFor="image[]" className="new-image">
                  <FiPlus size={24} color="#15b6d6" />
                </label>
              </div>
              <input multiple onChange={handleSelectImages} type="file" id="image[]" />
            </div>
          </fieldset>

          <fieldset>
            <legend>Visitação</legend>
            <div className="input-block">
              <label htmlFor="instructions">Instruções</label>
              <textarea id="instructions" maxLength={300} value={instructions} onChange={e => setInstructions(e.target.value)} />
            </div>

            <div className="input-block">
              <label htmlFor="opening_hours">Horário de funcionamento</label>
              <input id="opening_hours" maxLength={20} value={opening_hours} onChange={e => setOpeningHours(e.target.value)} />
            </div>

            <div className="input-block">
              <label htmlFor="open_on_weekends">Atende fim de semana</label>
              <div className="button-select">
                <button
                  type="button"
                  className={open_on_weekends ? 'active' : ''}
                  onClick={() => setOpenOnWeekends(true)}
                >
                  Sim
                </button>
                <button
                  type="button"
                  className={!open_on_weekends ? 'active' : ''}
                  onClick={() => setOpenOnWeekends(false)}
                >
                  Não
                </button>
              </div>
            </div>
          </fieldset>

          <button className="confirm-button" type="submit">
            Confirmar
          </button>
        </form>
      </main>
    </div>
  );
}