'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import { locations } from '@/data/locations';
import { useLanguage } from '@/context/LanguageContext';

export default function LocationsPage() {
  const [selectedCity, setSelectedCity] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedLocation, setSelectedLocation] = useState<typeof locations[0] | null>(null);
  const [userLocation, setUserLocation] = useState<{ lat: number; lng: number } | null>(null);
  const [isLocating, setIsLocating] = useState(false);
  const { t } = useLanguage();

  // Get unique cities sorted
  const cities = [...new Set(locations.map((loc) => loc.city))].sort();

  // Filter locations based on city and search query
  const filteredLocations = locations.filter((location) => {
    const matchCity = !selectedCity || location.city === selectedCity;
    const matchSearch =
      location.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      location.city.toLowerCase().includes(searchQuery.toLowerCase()) ||
      location.address.toLowerCase().includes(searchQuery.toLowerCase());
    return matchCity && matchSearch;
  });

  // Geolocation handler
  const handleUseMyLocation = () => {
    if (!navigator.geolocation) {
      alert('Browser Anda tidak mendukung geolocation');
      return;
    }

    setIsLocating(true);
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        setUserLocation({ lat: latitude, lng: longitude });

        // Find nearest location
        let nearest = locations[0];
        let minDistance = Infinity;

        locations.forEach((loc) => {
          const distance = Math.sqrt(
            Math.pow((loc.latitude - latitude), 2) + Math.pow((loc.longitude - longitude), 2)
          );
          if (distance < minDistance) {
            minDistance = distance;
            nearest = loc;
          }
        });

        setSelectedLocation(nearest);
        setIsLocating(false);
      },
      (error) => {
        setIsLocating(false);
        alert('Tidak dapat mengakses lokasi Anda. Pastikan izin lokasi diaktifkan.');
      },
      { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
    );
  };

  // Generate Google Maps embed URL
  const getMapEmbedUrl = () => {
    if (selectedLocation) {
      return `https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY&q=${encodeURIComponent(selectedLocation.address + ', ' + selectedLocation.city)}`;
    }
    // Default: show Jakarta
    return 'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d126748.56385602954!2d106.758835848187506!3d-6.229386676623066!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x2e69f3e945e34b9d%3A0x5371bf0fdad786a2!2sJakarta!5e0!3m2!1sen!2sid!4v1688000000000!5m2!1sen!2sid';
  };

  return (
    <main className="min-h-screen bg-ivory">
      <Navbar />

      {/* Hero Section - Same style as Promo page */}
      <section className="relative py-16 md:py-24 bg-espresso overflow-hidden">
        <div className="container-custom text-center text-white relative z-10">
          <h1 className="font-cormorant text-4xl md:text-6xl font-bold mb-4 uppercase text-white">
            {t('locations.page.title')}
          </h1>
          <p className="text-ivory/80 max-w-2xl mx-auto text-lg">
            {t('locations.page.subtitle')}
          </p>
          {/* Breadcrumb - Same as Promo page */}
          <nav className="mt-4 text-xs tracking-widest uppercase text-white">
            <Link href="/" className="hover:text-gold transition text-white">
              {t('breadcrumb.home')}
            </Link>
            <span className="mx-2 text-white">/</span>
            <span className="text-white/60">{t('breadcrumb.locations')}</span>
          </nav>
        </div>
      </section>

      {/* Search & Filter Bar */}
      <section className="sticky top-16 z-40 bg-white border-b border-blush py-4 shadow-sm">
        <div className="container-custom">
          <div className="flex flex-col md:flex-row gap-3">
            {/* Search Input */}
            <div className="flex-1 relative">
              <input
                type="text"
                placeholder={t('locations.search.placeholder')}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full px-4 py-3 pl-10 rounded-lg border border-blush bg-ivory text-espresso text-sm focus:outline-none focus:border-gold focus:ring-2 focus:ring-gold/20"
              />
              <svg className="absolute left-3 top-3.5 w-4 h-4 text-grey" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
            </div>

            {/* Use My Location Button */}
            <button
              onClick={handleUseMyLocation}
              disabled={isLocating}
              className="px-6 py-3 bg-gold text-white text-sm font-semibold rounded-lg hover:bg-gold-dark transition flex items-center justify-center gap-2 disabled:opacity-50"
            >
              {isLocating ? (
                <>
                  <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  <span>{t('locations.searching')}</span>
                </>
              ) : (
                <>
                  <svg className="w-4 h-4" 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>
                  <span>{t('locations.use-my-location')}</span>
                </>
              )}
            </button>
          </div>

          {/* City Filter Pills */}
          <div className="flex flex-wrap gap-2 mt-4">
            <button
              onClick={() => setSelectedCity('')}
              className={`px-4 py-2 rounded-full text-xs uppercase tracking-wider font-semibold transition ${
                !selectedCity ? 'bg-gold text-white' : 'border border-gold text-gold hover:bg-gold hover:text-white'
              }`}
            >
              {t('locations.filter.all')}
            </button>
            {cities.map((city) => (
              <button
                key={city}
                onClick={() => setSelectedCity(city)}
                className={`px-4 py-2 rounded-full text-xs uppercase tracking-wider font-semibold transition ${
                  selectedCity === city ? 'bg-gold text-white' : 'border border-gold text-gold hover:bg-gold hover:text-white'
                }`}
              >
                {city}
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* Map + Locations Grid */}
      <section className="py-12">
        <div className="container-custom">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">

            {/* Map Section */}
            <div className="lg:col-span-1 order-1 lg:order-2">
              <div className="sticky top-32 bg-white rounded-lg overflow-hidden border border-blush shadow-lg">
                <div className="bg-espresso text-white p-3 text-sm font-semibold flex items-center justify-between">
                  <span>🗺️ {t('locations.map.title')}</span>
                  {selectedLocation && (
                    <button
                      onClick={() => setSelectedLocation(null)}
                      className="text-xs text-white/70 hover:text-white"
                    >
                      <span>{t('locations.clear-map')}</span>
                    </button>
                  )}
                </div>
                <div className="aspect-square lg:aspect-auto lg:h-[500px] bg-ivory">
                  {selectedLocation ? (
                    <iframe
                      width="100%"
                      height="100%"
                      style={{ border: 0 }}
                      allowFullScreen
                      loading="lazy"
                      referrerPolicy="no-referrer-when-downgrade"
                      src={`https://maps.google.com/maps?q=${selectedLocation.latitude},${selectedLocation.longitude}&output=embed`}
                    />
                  ) : (
                    <div className="w-full h-full bg-blush flex items-center justify-center text-center p-6">
                      <div>
                        <div className="text-4xl mb-3">🗺️</div>
                        <p className="text-grey-dark text-sm mb-1">{t('locations.map.placeholder')}</p>
                        <p className="text-grey text-xs">{t('locations.map.subtitle')}</p>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Locations List */}
            <div className="lg:col-span-2 order-2 lg:order-1">
              <div className="space-y-4">
                {filteredLocations.length > 0 ? (
                  filteredLocations.map((location) => (
                    <div
                      key={location.id}
                      onClick={() => setSelectedLocation(location)}
                      className={`bg-white rounded-lg border overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-lg ${
                        selectedLocation?.id === location.id ? 'border-gold ring-2 ring-gold/20' : 'border-blush'
                      }`}
                    >
                      <div className="p-6">
                        {/* Header: Name + Type Badges */}
                        <div className="flex flex-wrap items-start justify-between gap-3 mb-4">
                          <h3 className="font-cormorant text-xl md:text-2xl font-bold text-espresso">
                            {location.name}
                          </h3>
                          <div className="flex flex-wrap gap-2">
                            {location.type.map((type) => (
                              <span
                                key={type}
                                className={`text-xs px-3 py-1 rounded-full font-semibold ${
                                  type === 'Premiere'
                                    ? 'bg-gold text-white'
                                    : 'bg-blush text-espresso'
                                }`}
                              >
                                {type}
                              </span>
                            ))}
                          </div>
                        </div>

                        {/* Details Grid */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                          {/* Address */}
                          <div className="flex items-start gap-3">
                            <div className="text-gold mt-1">
                              <svg className="w-5 h-5" 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>
                            </div>
                            <div>
                              <p className="text-xs text-grey mb-1">{t('locations.address')}</p>
                              <p className="text-sm text-espresso">{location.address}</p>
                              <p className="text-sm text-gold font-medium">{location.city}</p>
                            </div>
                          </div>

                          {/* Operating Hours */}
                          <div className="flex items-start gap-3">
                            <div className="text-gold mt-1">
                              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                              </svg>
                            </div>
                            <div>
                              <p className="text-xs text-grey mb-1">{t('locations.operating-hours')}</p>
                              <p className="text-sm text-espresso">{location.operatingHours}</p>
                            </div>
                          </div>

                          {/* Phone */}
                          <div className="flex items-start gap-3">
                            <div className="text-gold mt-1">
                              <svg className="w-5 h-5" 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>
                            </div>
                            <div>
              <p className="text-xs text-grey mb-1">{t('locations.phone')}</p>
                              <a href={`tel:${location.phone}`} className="text-sm text-gold hover:underline">{location.phone}</a>
                            </div>
                          </div>

                          {/* WhatsApp */}
                          <div className="flex items-start gap-3">
                            <div className="text-gold mt-1">
                              <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.373-.273.299-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.884 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
                            </div>
                            <div>
              <p className="text-xs text-grey mb-1">{t('locations.whatsapp')}</p>
                              <a
                                href={`https://wa.me/62${location.whatsapp.replace(/[^0-9]/g, '')}`}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-sm text-gold hover:underline"
                              >
                                {location.whatsapp}
                              </a>
                            </div>
                          </div>
                        </div>

                        {/* Action Buttons */}
                        <div className="flex gap-3 pt-4 border-t border-blush">
                          <Link
                            href="/online-booking"
                            className="flex-1 py-2.5 bg-gold text-white text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold-dark transition text-center"
                          >
                            📅 {t('locations.booking')}
                          </Link>
                          <a
                            href={`https://maps.google.com/?q=${location.latitude},${location.longitude}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex-1 py-2.5 border border-gold text-gold text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold hover:text-white transition text-center"
                          >
                            {t('locations.directions')}
                          </a>
                          <a
                            href={`https://wa.me/62${location.whatsapp.replace(/[^0-9]/g, '')}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="py-2.5 px-4 border border-gold text-gold text-xs uppercase tracking-widest font-semibold rounded-lg hover:bg-gold hover:text-white transition text-center"
                          >
                            💬
                          </a>
                        </div>
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="text-center py-12 bg-white rounded-lg border border-blush">
                    <div className="text-5xl mb-4">🔍</div>
                    <p className="text-grey-dark text-lg mb-2">{t('locations.no-results')}</p>
                    <p className="text-grey text-sm">{t('locations.try-again')}</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </main>
  );
}
