import { useEffect, useState } from "react";
import { FaWhatsapp } from "react-icons/fa";
import { FiClock, FiInfo } from "react-icons/fi";
import { useParams } from 'react-router-dom';
import { GoogleMap, useJsApiLoader, Marker } from "@react-google-maps/api";

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

interface Orphanage {
  latitude: number;
  longitude: number;
  name: string;
  about: string;
  instructions: string;
  opening_hours: string;
  open_on_weekends: boolean;
  phone: string;
  images: Array<{
    id: number;
    url: string;
  }>;
}

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

  const { id } = useParams();
  const [orphanage, setOrphanage] = useState<Orphanage>();
  const [activeImageIndex, setActiveImageIndex] = useState(0);

  useEffect(() => {
    api.get(`orphanages/${id}`).then(response => {
      setOrphanage(response.data);
    });
  }, [id]);

  if (!orphanage || !isLoaded) {
    return <p>Carregando...</p>;
  }

  function formatPhoneNumberForWhatsApp(phoneNumber: string) {
    const digitsOnly = phoneNumber.replace(/\D/g, '');
    return `55${digitsOnly}`;
  }

  return (
    <div id="page-orphanage">
      <Sidebar />
      <main>
        <div className="orphanage-details">
          <img src={orphanage.images[activeImageIndex].url} alt={orphanage.name} />

          <div className="images">
            {orphanage.images.map((image, index) => (
              <button
                key={image.id}
                className={activeImageIndex === index ? 'active' : ''}
                type="button"
                onClick={() => setActiveImageIndex(index)}
              >
                <img src={image.url} alt={orphanage.name} />
              </button>
            ))}
          </div>

          <div className="orphanage-details-content">
            <h1>{orphanage.name}</h1>
            <p>{orphanage.about}</p>

            <div className="map-container">
               <GoogleMap
                  mapContainerStyle={{ width: '100%', height: 280, borderRadius: '20px' }}
                  center={{ lat: orphanage.latitude, lng: orphanage.longitude }}
                  zoom={16}
                  options={{
                    draggable: false,
                    zoomControl: false,
                    scrollwheel: false,
                    disableDoubleClickZoom: true,
                  }}
                >
                  <Marker
                    position={{ lat: orphanage.latitude, lng: orphanage.longitude }}
                    icon={{
                      url: mapMarkerImg,
                      scaledSize: new window.google.maps.Size(58, 68),
                    }}
                  />
                </GoogleMap>
              <footer>
                <a
                  target="_blank"
                  rel="noopener noreferrer"
                  href={`https://www.google.com/maps/dir/?api=1&destination=$...${orphanage.latitude},${orphanage.longitude}`}
                >
                  Ver rotas no Google Maps
                </a>
              </footer>
            </div>

            <hr />

            <h2>Instruções para visita</h2>
            <p>{orphanage.instructions}</p>

            <div className="open-details">
              <div className="hour">
                <FiClock size={32} color="#15B6D6" />
                Segunda à Sexta <br />
                {orphanage.opening_hours}
              </div>
              {orphanage.open_on_weekends ? (
                <div className="open-on-weekends">
                  <FiInfo size={32} color="#39CC83" />
                  Atendemos <br />
                  fim de semana
                </div>
              ) : (
                <div className="open-on-weekends dont-open">
                  <FiInfo size={32} color="#FF669D" />
                  Não atendemos <br />
                  fim de semana
                </div>
              )}
            </div>

            <a 
              href={`https://wa.me/${formatPhoneNumberForWhatsApp(orphanage.phone)}`}
              target="_blank"
              rel="noopener noreferrer"
              style={{ textDecoration: 'none' }}
            >
              <button className="contact-button">
                <FaWhatsapp size={20} color="#FFF" />
                Entrar em contato
              </button>
              
            </a>
          </div>
        </div>
      </main>
    </div>
  );
}