import React, { useState, useEffect } from 'react';
import Layout from "../../../components/layout";
import { Carousel } from 'react-responsive-carousel';
import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader
import { GetServerSideProps } from 'next';
import { Location, UserRole } from "@prisma/client";
import axiosServer from '../../../src/axiosServer';

const ViewLocationPage: React.FC<ViewLocationPageProps> = ({ location }) => {
    const [activeTab, setActiveTab] = useState('mainLocation');
    const [activeImage, setActiveImage] = useState(0);

    const [images, setImages] = useState([]);
    const [mainLocationImageCount, setMainLocationImageCount] = useState(0);

    useEffect(() => {
        const mainLocationImages = [location.picture1, location.picture2, location.picture3].filter(Boolean);

        const backupLocationImages = location.backupLocationImages?.filter(Boolean) ?? [];
        setImages([...mainLocationImages, ...backupLocationImages]);
        setMainLocationImageCount(mainLocationImages.length);
    }, [location.picture1, location.picture2, location.picture3, location.backupLocationImages]);

    const handleTabChange = (tab: string) => {
        setActiveTab(tab);
        //show the proper image in the carousel
        if (tab === 'backupLocation') {
            setActiveImage(mainLocationImageCount);
        } else {
            setActiveImage(0);
        }
    };

    const handleCarouselChange = (index) => {
        // Switch to backupLocation tab if the current carousel image index is from the backup location
        if (index >= mainLocationImageCount) {
            setActiveTab('backupLocation');
        } else {
            setActiveTab('mainLocation');
        }
        setActiveImage(index);
    };

    return (
        <Layout>
            <div className="view-location-page max-w-4xl mx-auto my-8">
                {/* Tabs */}
                <div className="tabs flex border-b">
                    {/* Main Location Tab */}
                    <button
                        className={`tab flex-1 text-lg py-2 px-4 ${activeTab === 'mainLocation' ? 'border-b-4 border-blue-500 text-blue-600 font-semibold' : 'text-gray-600 hover:text-blue-500'}`}
                        onClick={() => handleTabChange('mainLocation')}
                    >
                        {location.name}
                    </button>
                    {/* Backup Location Tab */}
                    <button
                        className={`tab flex-1 text-lg py-2 px-4 ${activeTab === 'backupLocation' ? 'border-b-4 border-blue-500 text-blue-600 font-semibold' : 'text-gray-600 hover:text-blue-500'}`}
                        onClick={() => handleTabChange('backupLocation')}
                    >
                        При лошо време: <strong>{location.backupLocationName}</strong>
                    </button>
                </div>

                {/* Carousel */}
                {images.length > 0 && (
                    <Carousel showArrows={true}
                        autoPlay={false}
                        infiniteLoop={true}
                        showThumbs={false}
                        onChange={handleCarouselChange}
                        selectedItem={activeImage}
                    >
                        {images.map((src, index) => (
                            <div key={index}>
                                <img src={src} alt={`Slide ${index + 1}`} />
                            </div>
                        ))}
                    </Carousel>
                )}

                {/* Tab Content */}
                {(location.content || location.backupLocationContent) && (
                    <div className="tab-content mt-4">
                        {activeTab === 'mainLocation' && (
                            <div className="p-4 bg-white shadow rounded-lg" dangerouslySetInnerHTML={{ __html: location.content }} />
                        )}
                        {activeTab === 'backupLocation' && location.backupLocationContent && (
                            <div className="p-4 bg-white shadow rounded-lg" dangerouslySetInnerHTML={{ __html: location.backupLocationContent }} />
                        )}
                    </div>
                )}
            </div>
        </Layout>
    );
};

export const getServerSideProps: GetServerSideProps = async (context) => {
    const axios = await axiosServer(context);

    const { data: location } = await axios.get(
        `${process.env.PUBLIC_URL}/api/data/locations/${context.params.id}`
    );
    if (location.backupLocationId !== null) {
        const { data: backupLocation } = await axios.get(
            process.env.PUBLIC_URL + "/api/data/locations/" + location.backupLocationId
        );
        location.backupLocationName = backupLocation.name;
        location.backupLocationContent = backupLocation ? backupLocation.content : "";
        location.backupLocationImages = backupLocation ? [backupLocation.picture1, backupLocation.picture2, backupLocation.picture3].filter(Boolean) : [];
    }

    context.res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate");

    return {
        props: {
            location: location,
        },
    };
};

export default ViewLocationPage;
