import { PhotoWithFallback, 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 description = location?.description_markdown?.replace(/[#*\[\]()]/g, '').trim() || '';
  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>
      <div className="mx-auto max-w-container px-4 md:px-8">
        {/* Top Section: Description and Photo */}
        <div className="grid grid-cols-1 gap-12 lg:grid-cols-2 lg:gap-16 mb-16">
          <div className="flex flex-col justify-center">
            <h2 className="font-display text-4xl font-normal leading-tight text-fg-primary md:text-5xl">
              {location.name}
            </h2>
            
            {location.city && location.state && (
              <p className="mt-4 text-xs font-body uppercase tracking-widest" style={{ color: 'var(--color-text-brand-secondary)' }}>
                {location.city}, {location.state}
              </p>
            )}
            
            {description && (
              <p className="mt-6 font-display text-lg leading-relaxed text-tertiary whitespace-pre-line">
                {description}
              </p>
            )}
          </div>
          
          <div className="w-full h-64 md:h-96 overflow-hidden">
            <PhotoWithFallback
              item={location}
              fallbackId={location.id}
              className="w-full h-full object-cover"
            />
          </div>
        </div>

        {/* Bottom Section: Contact Info and Map */}
        <div className="grid grid-cols-1 gap-12 lg:grid-cols-2 lg:gap-16">
          {/* Contact Information */}
          <div className="space-y-8">
            {location.address_line_1 && (
              <div>
                <p className="text-xs font-body uppercase tracking-widest mb-2" style={{ color: 'var(--color-text-brand-secondary)' }}>
                  ADDRESS
                </p>
                <a 
                  href={`https://maps.google.com/?q=${encodeURIComponent(fullAddress)}`}
                  className="font-body text-base underline underline-offset-4 hover:no-underline transition-colors"
                  style={{ color: 'var(--color-text-brand-accent)' }}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  {location.address_line_1}
                  {location.address_line_2 && <><br />{location.address_line_2}</>}
                  <br />{location.city}, {location.state} {location.zip_code}
                </a>
              </div>
            )}

            {location.phone && (
              <div>
                <p className="text-xs font-body uppercase tracking-widest mb-2" style={{ color: 'var(--color-text-brand-secondary)' }}>
                  PHONE
                </p>
                <a 
                  href={`tel:${location.phone}`}
                  className="font-body text-base underline underline-offset-4 hover:no-underline transition-colors"
                  style={{ color: 'var(--color-text-brand-accent)' }}
                >
                  {location.phone}
                </a>
              </div>
            )}

            {location.email && (
              <div>
                <p className="text-xs font-body uppercase tracking-widest mb-2" style={{ color: 'var(--color-text-brand-secondary)' }}>
                  EMAIL
                </p>
                <a 
                  href={`mailto:${location.email}`}
                  className="font-body text-base underline underline-offset-4 hover:no-underline transition-colors"
                  style={{ color: 'var(--color-text-brand-accent)' }}
                >
                  {location.email}
                </a>
              </div>
            )}

            {businessHours.length > 0 && (
              <div>
                <p className="text-xs font-body uppercase tracking-widest mb-2" style={{ color: 'var(--color-text-brand-secondary)' }}>
                  HOURS
                </p>
                <div className="font-body text-base text-tertiary space-y-1">
                  {businessHours.map(({ day, hours }) => (
                    <div key={day} className="flex justify-between gap-4">
                      <span className="font-medium">{day}:</span>
                      <span className="whitespace-pre-line">{hours}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {fullAddress && (
            <div className="w-full h-96 overflow-hidden">
              <GoogleMap
                address={fullAddress}
                locationName={location.name}
                className="h-full w-full"
              />
            </div>
          )}
        </div>
      </div>
    </section>
  );
};

import { registerThemeVariant } from '../../lib/component-registry';
registerThemeVariant('location-details-section', 'aman', LocationDetailsSection);
