import React, { ReactNode } from 'react';
import { classNames, classNamesTailwind } from '../utils/theme';
import { Location } from './LocationFinder';
import { zeroPad } from './LocationFinderLocation';

interface LocationFinderSelectedLocationProps {
    onBackClick(): void;
    className?: string;
    classNameBack?: string;
    classNameImage?: string;
    classNameOpeningHoursLabel?: string;
    location?: Location;
    backLabel?: string;
    renderBack?: ({ onClick }: { onClick: () => void }) => ReactNode;
    renderImage?: ({ image }: { image?: string }) => ReactNode;
    renderDirections?: ({ link }: { link: string }) => ReactNode;
    renderContent?: ({ location }: { location: Location }) => ReactNode;
}

const getFullDayName = (day: number, locale: string = 'nl', region = 'NL'): string => {
    const date = new Date();
    date.setDate(date.getDate() + day);
    return date.toLocaleString(`${locale}-${region}`, { weekday: 'long' });
};

const LocationFinderSelectedLocation = ({
    className,
    classNameBack,
    classNameImage,
    classNameOpeningHoursLabel,
    renderBack,
    onBackClick,
    renderImage,
    renderDirections,
    renderContent,
    location,
    backLabel
}: LocationFinderSelectedLocationProps) => {
    if (!location) {
        return <div className={classNames('px-4', className)} />;
    }

    const openingHours = location.openingHours?.days;
    const image = location.image && Boolean(location.image.length) ? location.image[0] : undefined;
    const maxSlots = openingHours ? Object.values(openingHours).reduce((a, c) => (c.slots.length > a ? c.slots.length : a), 0) : 0;

    return (
        <div className={classNames('px-4', className)}>
            {renderBack ? (
                renderBack({ onClick: onBackClick })
            ) : (
                <button className={classNameBack} onClick={onBackClick}>
                    {backLabel || 'Terug'}
                </button>
            )}
            {renderImage
                ? renderImage({ image })
                : image && (
                      <img
                          className={classNamesTailwind('aspect-[4/2] object-cover object-center w-full rounded', classNameImage)}
                          src={image}
                      />
                  )}
            {renderContent && renderContent({ location })}
            {openingHours && Boolean(Object.keys(openingHours).length) && (
                <>
                    <span className={classNamesTailwind('font-bold text-indigo-600 block mt-4', classNameOpeningHoursLabel)}>
                        Openingstijden
                    </span>
                    <table className="min-w-full divide-y divide-gray-300">
                        <thead>
                            <tr>
                                <th scope="col" className="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-0">
                                    <span className="sr-only">Dag</span>
                                </th>
                                {Array.from(Array(maxSlots).keys()).map((index) => (
                                    <th key={index} scope="col" className="py-3.5 px-3 text-left text-sm font-semibold text-gray-900">
                                        <span className="sr-only">Tijd</span>
                                    </th>
                                ))}
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-200">
                            {Object.entries(openingHours)
                                .sort(([a], [b]) => (a as unknown as number) - (b as unknown as number))
                                .map(([key, value]) => (
                                    <tr key={key}>
                                        <td className="text-sm text-gray-500 px-2 py-2 capitalize">
                                            {getFullDayName(key as unknown as number)}
                                        </td>
                                        {Array.from(Array(maxSlots).keys()).map((index) => {
                                            const slot = value.slots[index];

                                            if (!slot) {
                                                return <td key={index} className="text-sm text-gray-500 px-2 py-2" />;
                                            }

                                            return (
                                                <td key={index} className="text-sm text-gray-500 px-2 py-2">
                                                    <span className="">
                                                        <span>
                                                            {zeroPad(slot.from.hours)}:{zeroPad(slot.from.minutes)}
                                                        </span>
                                                        <span> - </span>
                                                        <span>
                                                            {zeroPad(slot.to.hours)}:{zeroPad(slot.to.minutes)} uur
                                                        </span>
                                                    </span>
                                                </td>
                                            );
                                        })}
                                    </tr>
                                ))}
                        </tbody>
                    </table>
                </>
            )}
            {renderDirections &&
                renderDirections({ link: `https://www.google.com/maps/dir/${location.position.lat},${location.position.lng}` })}
        </div>
    );
};

export default LocationFinderSelectedLocation;
