import React from 'react';
import { Mail01, MarkerPin02, Phone, Clock } from '@untitledui/icons';
import { Button } from '../elements';
import { FeaturedIcon, GoogleMap } from '../elements';
import type { Location } from '../../types/api/location';

interface LocationDetailsSectionProps {
    location?: Location | null;
}

// Parse business hours - handle both string and object formats
const parseBusinessHours = (hours: string | Record<string, { open: string; close: string }> | undefined): Array<{ day: string; hours: string }> => {
    if (!hours) return [];
    
    if (typeof hours === 'object' && !Array.isArray(hours)) {
        const dayNames: Record<string, string> = {
            monday: 'Monday',
            tuesday: 'Tuesday',
            wednesday: 'Wednesday',
            thursday: 'Thursday',
            friday: 'Friday',
            saturday: 'Saturday',
            sunday: 'Sunday',
        };
        
        return Object.entries(hours)
            .filter(([, value]) => value && typeof value === 'object' && value.open && value.close)
            .map(([day, value]) => ({
                day: dayNames[day.toLowerCase()] || day.charAt(0).toUpperCase() + day.slice(1),
                hours: `${value.open}-${value.close}`,
            }));
    }
    
    if (typeof hours === 'string') {
        const entries = hours.split(',').map(entry => {
            const parts = entry.trim().split(':');
            if (parts.length === 2) {
                return { day: parts[0].trim(), hours: parts[1].trim() };
            }
            return null;
        }).filter(Boolean) as Array<{ day: string; hours: string }>;
        
        return entries.length > 0 ? entries : [{ day: 'Hours', hours }];
    }
    
    return [];
};

export const LocationDetailsSection = ({
    location,
}: LocationDetailsSectionProps) => {
    if (!location) return null;

    const label = "Contact us";
    const title = "Get in touch";
    const subtitle = location.description_markdown?.replace(/[#*\[\]()]/g, '').trim() || '';
    const emailLabel = "Email";
    const emailDescription = "Our friendly team is here to help.";
    const officeLabel = "Address";
    const officeDescription = "Visit or get directions.";
    const phoneLabel = "Phone";
    const phoneDescription = "Reach us on the phone.";
    const backgroundColor = "bg-primary";
    const className = "";
    const showMap = true;
    const fullAddress = `${location.address_line_1}${location.address_line_2 ? `, ${location.address_line_2}` : ''}, ${location.city}, ${location.state} ${location.zip_code}`.trim();
    
    const businessHours = location.business_hours ? parseBusinessHours(location.business_hours) : [];

    return (
        <section className={`${backgroundColor} py-16 md:py-24 ${className}`}>
            <div className="mx-auto w-full max-w-container px-4 md:px-8">
                <div className="flex w-full max-w-3xl flex-col">
                    {label && (
                        <span className="text-sm font-semibold text-brand-secondary md:text-md">
                            {label}
                        </span>
                    )}
                    {title && (
                        <h2 className="mt-3 text-display-sm font-semibold text-primary md:text-display-md">
                            {title}
                        </h2>
                    )}
                    {subtitle && (
                        <p className="mt-4 text-lg text-tertiary md:mt-5 md:text-xl">
                            {subtitle}
                        </p>
                    )}
                </div>

                <div className="mt-12 grid grid-cols-1 items-start gap-12 md:mt-16 md:gap-16 lg:grid-cols-3">
                    <ul className="col-span-1 grid w-full grid-cols-1 gap-x-8 gap-y-10 md:grid-cols-2 lg:grid-cols-1 lg:gap-y-12">
                        {location.address_line_1 && (
                            <li className="flex max-w-sm flex-col items-start gap-4 lg:flex-row">
                                <FeaturedIcon className="hidden md:flex" size="lg" icon={MarkerPin02} color="brand" theme="light" />
                                <FeaturedIcon className="md:hidden" size="md" icon={MarkerPin02} color="brand" theme="light" />
                                <div className="lg:pt-2.5">
                                    <h3 className="text-lg font-semibold text-primary">
                                        {officeLabel}
                                    </h3>
                                    <p className="mt-1 text-md text-tertiary">
                                        {officeDescription}
                                    </p>
                                    <Button 
                                        href={`https://maps.google.com/?q=${encodeURIComponent(fullAddress)}`}
                                        color="link-color" 
                                        size="lg" 
                                        className="mt-4 whitespace-pre lg:mt-5"
                                    >
                                        {location.address_line_1}{location.address_line_2 ? `\n${location.address_line_2}` : ''}
                                        {`\n${location.city}, ${location.state} ${location.zip_code}`}
                                    </Button>
                                </div>
                            </li>
                        )}
                        
                        {location.phone && (
                            <li className="flex max-w-sm flex-col items-start gap-4 lg:flex-row">
                                <FeaturedIcon className="hidden md:flex" size="lg" icon={Phone} color="brand" theme="light" />
                                <FeaturedIcon className="md:hidden" size="md" icon={Phone} color="brand" theme="light" />
                                <div className="lg:pt-2.5">
                                    <h3 className="text-lg font-semibold text-primary">
                                        {phoneLabel}
                                    </h3>
                                    <p className="mt-1 text-md text-tertiary">
                                        {phoneDescription}
                                    </p>
                                    <Button href={`tel:${location.phone}`} color="link-color" size="lg" className="mt-4 lg:mt-5">
                                        {location.phone}
                                    </Button>
                                </div>
                            </li>
                        )}
                        
                        {location.email && (
                            <li className="flex max-w-sm flex-col items-start gap-4 lg:flex-row">
                                <FeaturedIcon className="hidden md:flex" size="lg" icon={Mail01} color="brand" theme="light" />
                                <FeaturedIcon className="md:hidden" size="md" icon={Mail01} color="brand" theme="light" />
                                <div className="lg:pt-2.5">
                                    <h3 className="text-lg font-semibold text-primary">
                                        {emailLabel}
                                    </h3>
                                    <p className="mt-1 text-md text-tertiary">
                                        {emailDescription}
                                    </p>
                                    <Button href={`mailto:${location.email}`} color="link-color" size="lg" className="mt-4 lg:mt-5">
                                        {location.email}
                                    </Button>
                                </div>
                            </li>
                        )}

                        {businessHours.length > 0 && (
                            <li className="flex max-w-sm flex-col items-start gap-4 lg:flex-row">
                                <FeaturedIcon className="hidden md:flex" size="lg" icon={Clock} color="brand" theme="light" />
                                <FeaturedIcon className="md:hidden" size="md" icon={Clock} color="brand" theme="light" />
                                <div className="lg:pt-2.5">
                                    <h3 className="text-lg font-semibold text-primary">
                                        Business Hours
                                    </h3>
                                    <div className="mt-1 flex flex-col gap-2 text-md text-tertiary">
                                        {businessHours.map(({ day, hours }) => (
                                            <div key={day} className="flex justify-between gap-4">
                                                <span className="font-medium capitalize">{day}:</span>
                                                <span>{hours}</span>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </li>
                        )}
                    </ul>

                    {showMap && fullAddress && (
                        <div className="col-span-2 h-60 w-full border-none lg:h-full">
                            <GoogleMap
                                address={fullAddress}
                                locationName={location.name}
                                className="h-full"
                            />
                        </div>
                    )}
                </div>
            </div>
        </section>
    );
};
