import React from 'react';
import { ArrowRight } from '@untitledui/icons';
import { Button } from '../elements';
import type { Location } from '../../types/api/location';
import type { CompanyInformation } from '../../types/api/company-information';
import { resolveCtaUrls, isExternalCtaUrl } from '../../lib/cta-urls';

interface LocationGridProps {
    locations?: Location[] | null;
    companyInformation?: CompanyInformation | null;
    title?: string;
    subtitle?: string;
    /** Optional route override for the "Contact Us" CTA. When not set, uses primary CTA URL (booking or /contact) from company info. */
    primaryCtaHrefOverride?: string;
    backgroundColor?: string;
    className?: string;
}

// Simple icon components
const LocationIcon = ({ className }: { className?: string }) => (
    <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
    </svg>
);

const PhoneIcon = ({ className }: { className?: string }) => (
    <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
    </svg>
);

export const LocationGrid = ({
    locations: locationsData,
    companyInformation,
    title = "",
    subtitle = "",
    primaryCtaHrefOverride,
    backgroundColor = "bg-primary",
    className = "",
}: LocationGridProps) => {
    const locations = Array.isArray(locationsData) ? locationsData : [];
    const resolved = companyInformation ? resolveCtaUrls(companyInformation) : null;
    const primaryCtaHref = primaryCtaHrefOverride ?? resolved?.primaryHref ?? '/contact';
    
    return (
        <section className={`${backgroundColor} py-16 md:py-24 ${className}`}>
            <div className="mx-auto w-full max-w-container px-4 md:px-8">
                {(title || subtitle) && (
                    <div className="mx-auto mb-12 flex w-full max-w-3xl flex-col items-center text-center">
                        {title && (
                            <h2 className="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>
                )}

                {locations.length > 0 ? (
                    <ul className="grid grid-cols-1 gap-x-8 gap-y-10 sm:grid-cols-2 md:gap-y-12 lg:grid-cols-3">
                        {locations.map((location, index) => {
                            const fullAddress = `${location.address_line_1}${location.address_line_2 ? `, ${location.address_line_2}` : ''}, ${location.city}, ${location.state} ${location.zip_code}`.trim();
                            
                            return (
                                <li key={location.id || index} className="flex flex-col gap-6 rounded-2xl bg-secondary p-6 ring-1 ring-secondary_alt md:p-8">
                                    <div className="flex flex-col gap-4">
                                        <h3 className="text-lg font-semibold text-primary md:text-xl">{location.name}</h3>
                                        
                                        {fullAddress && (
                                            <div className="flex items-start gap-3">
                                                <div className="size-5 shrink-0 mt-0.5 text-fg-quaternary">
                                                    <LocationIcon className="w-full h-full" />
                                                </div>
                                                <span className="text-md text-tertiary">{fullAddress}</span>
                                            </div>
                                        )}
                                        
                                        {location.phone && (
                                            <div className="flex items-center gap-3">
                                                <div className="size-5 shrink-0 text-fg-quaternary">
                                                    <PhoneIcon className="w-full h-full" />
                                                </div>
                                                <a 
                                                    href={`tel:${location.phone}`}
                                                    className="text-md text-tertiary hover:text-primary transition-colors"
                                                >
                                                    {location.phone}
                                                </a>
                                            </div>
                                        )}
                                    </div>

                                    <div className="flex flex-col gap-3 mt-auto">
                                        <Button
                                            size="lg"
                                            href={`/locations/${location.slug}`}
                                            iconTrailing={ArrowRight}
                                        >
                                            View details
                                        </Button>
                                    </div>
                                </li>
                            );
                        })}
                    </ul>
                ) : (
                    <div className="text-center py-12">
                        <div className="text-gray-400 text-6xl mb-4">📍</div>
                        <h3 className="text-xl font-semibold text-primary mb-2">No Locations Available</h3>
                        <p className="text-gray-600 mb-4">We&apos;re working on adding our service locations.</p>
                        <Button href={primaryCtaHref} target={isExternalCtaUrl(primaryCtaHref) ? '_blank' : undefined} rel={isExternalCtaUrl(primaryCtaHref) ? 'noopener noreferrer' : undefined}>Contact Us</Button>
                    </div>
                )}
            </div>
        </section>
    );
};
