"use client";

import { useEffect, useState } from "react";
import { apiCall } from "@/utils/callApi";
import { MapPin, Phone, Clock, Navigation, ExternalLink } from "lucide-react";

interface Store {
  _id: string;
  name: string;
  brand: string;
  address: string;
  phone: string;
  openTime: string;
  closeTime: string;
  isActive: boolean;
  lat?: number;
  lng?: number;
  createdAt: string;
  updatedAt: string;
  mapUrl?: string;
}

export default function StorePage() {
  const [stores, setStores] = useState<Store[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedStore, setSelectedStore] = useState<Store | null>(null);
  const [searchTerm, setSearchTerm] = useState("");

  useEffect(() => {
    fetchStores();
  }, []);

  const fetchStores = async () => {
    try {
      setLoading(true);
      const response = await apiCall<any>("/clientapi/store");
      // console.log("Store API Response:", response);
      
      if (response?.data?.success && response?.data?.data) {
        const storesWithMaps = response.data.data.map((store: Store) => ({
          ...store,
          mapUrl: getGoogleMapsEmbedUrl(store.address)
        }));
        setStores(storesWithMaps);
        if (storesWithMaps.length > 0) {
          setSelectedStore(storesWithMaps[0]);
        }
      }
    } catch (error) {
      console.error("Error fetching stores:", error);
    } finally {
      setLoading(false);
    }
  };

  // Generate Google Maps embed URL without API key
  const getGoogleMapsEmbedUrl = (address: string) => {
    const encodedAddress = encodeURIComponent(address);
    // Using directions embed format
    return `https://www.google.com/maps/embed/v1/place?key=YOUR_GOOGLE_MAPS_API_KEY&q=${encodedAddress}`;
  };

  // Alternative: Use static iframe with direct Google Maps URL (no API key needed for basic embed)
  const getDirectMapUrl = (address: string) => {
    const encodedAddress = encodeURIComponent(address);
    // This uses the standard Google Maps embed without API key
    return `https://www.google.com/maps?q=${encodedAddress}&output=embed`;
  };

  // Format time to 12-hour format
  const formatTime = (time: string) => {
    if (!time) return "N/A";
    const [hours, minutes] = time.split(":");
    const hour = parseInt(hours);
    const ampm = hour >= 12 ? "PM" : "AM";
    const hour12 = hour % 12 || 12;
    return `${hour12}:${minutes} ${ampm}`;
  };

  // Get store status
  const getStoreStatus = (openTime: string, closeTime: string) => {
    const now = new Date();
    const currentHours = now.getHours();
    const currentMinutes = now.getMinutes();
    
    const [openHour, openMinute] = openTime.split(":").map(Number);
    const [closeHour, closeMinute] = closeTime.split(":").map(Number);
    
    const currentTotal = currentHours * 60 + currentMinutes;
    const openTotal = openHour * 60 + openMinute;
    const closeTotal = closeHour * 60 + closeMinute;
    
    const isOpen = currentTotal >= openTotal && currentTotal <= closeTotal;
    
    return {
      isOpen,
      statusText: isOpen ? "Open Now" : "Closed",
      statusColor: isOpen ? "text-[#DDA16B] border-[#DDA16B] bg-white" : "text-red-600 bg-red-50 border-red-200"
    };
  };

  const openInGoogleMaps = (address: string) => {
    const encodedAddress = encodeURIComponent(address);
    const url = `https://www.google.com/maps/dir/?api=1&destination=${encodedAddress}&travelmode=driving`;
    window.open(url, "_blank");
  };

  // Filter stores based on search
  const filteredStores = stores.filter(store =>
    store.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    store.address.toLowerCase().includes(searchTerm.toLowerCase())
  );

  if (loading) {
    return (
      <div className="min-h-screen bg-slate-50">
        <div className="container mx-auto px-3 py-6 md:py-10">
          <div className="space-y-6 animate-pulse">
            {/* <div className="bg-white rounded-xl p-6 shadow-sm">
              <div className="h-4 bg-gray-200 rounded w-3/4 mb-6"></div>
              <div className="h-8 bg-gray-200 rounded w-1/3 mb-4"></div>
              <div className="grid gap-4 md:grid-cols-[1fr_auto]">
                <div className="h-10 bg-gray-200 rounded"></div>
                <div className="h-10 bg-gray-200 rounded"></div>
              </div>
            </div> */}

            <div className="grid lg:grid-cols-3 gap-6">
              <div className="lg:col-span-2 space-y-4">
                <div className="bg-white rounded-xl p-4 shadow-sm">
                  <div className="h-6 bg-gray-200 rounded w-1/3 mb-4"></div>
                  <div className="bg-gray-200 rounded h-96"></div>
                </div>

                <div className="grid sm:grid-cols-2 gap-4">
                  <div className="bg-white rounded-xl p-4 shadow-sm">
                    <div className="h-5 bg-gray-200 rounded w-3/4 mb-3"></div>
                    <div className="h-4 bg-gray-200 rounded w-2/3"></div>
                  </div>
                  <div className="bg-white rounded-xl p-4 shadow-sm">
                    <div className="h-5 bg-gray-200 rounded w-3/4 mb-3"></div>
                    <div className="h-4 bg-gray-200 rounded w-2/3"></div>
                  </div>
                </div>
              </div>
               <div className="lg:col-span-1 space-y-4">
                <div className="bg-white rounded-xl p-4 shadow-sm space-y-4">
                  <div className="h-6 bg-gray-200 rounded w-1/2"></div>
                  {[1, 2, 3].map((i) => (
                    <div key={i} className="rounded-xl border border-slate-200 p-4">
                      <div className="h-5 bg-gray-200 rounded w-3/4 mb-3"></div>
                      <div className="h-4 bg-gray-200 rounded w-full mb-2"></div>
                      <div className="h-4 bg-gray-200 rounded w-5/6 mb-3"></div>
                      <div className="h-8 bg-gray-200 rounded w-full"></div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen">
      {/* Breadcrumb */}
      <section className="breadcrumbcontainer">
        <div className="container mx-auto px-3">
          <ol className="breadcrumb flex items-center gap-2 text-sm">
            <li><a href="/">Home</a></li>
            <li className="active">Stores</li>
          </ol>
        </div>
      </section>
      <section className="storepage py-8 md:py-12 pt-4 md:pt-6">
        <div className="container px-3">
          <div className="section-heading text-center">
            <h1 className="mb-2">Our Stores</h1>
            <p className="mb-0">
              Visit our physical stores to experience our collections in person. Find the nearest store location below.
            </p>
          </div>

          <div className="flex flex-wrap md:flex-row-reverse justify-center -mx-3 xl:-mx-4 2xl:-mx-6 md:pt-5">
            {/* Store Listings */}
            <div className="2xl:w-5/12 xl:w-5/12 lg:w-5/12 md:w-4/12 sm:w-full w-full px-3 xl:px-4 2xl:px-6 mb-4 mb-lg-0">
              <div className="bg-white p-3 md:p-5 2xl:p-6 space-y-4 store-box-outer">
                <div className="w-full">
                  <h3 className="md:text-xl 2xl:text-xl text-[#201E1C] font-normal mb-3">Search nearby Store</h3>
                  <div className="relative">
                    <input
                      type="text"
                      placeholder="Search by store name or location..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="w-full px-4 py-2 pl-4 pr-4 border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                    />
                    {/* <Navigation className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} /> */}
                  </div>
                </div>
                <h3 className="md:text-xl 2xl:text-xl text-[#201E1C] font-normal">
                  {filteredStores.length} Store{filteredStores.length !== 1 ? "s" : ""} Found
                </h3>
                
                {filteredStores.length === 0 ? (
                  <div className="bg-white rounded-xl p-8 text-center shadow">
                    <p className="text-gray-500">No stores found matching your search.</p>
                  </div>
                ) : (
                  filteredStores.map((store) => {
                    const status = getStoreStatus(store.openTime, store.closeTime);
                    return (
                      <div
                        key={store._id}
                        onClick={() => setSelectedStore(store)}
                        className={`bg-[#FFFBF2] p-3 md:p-4 2xl:p-5 transition-all cursor-pointer border ${
                          selectedStore?._id === store._id
                            ? "border-[rgba(var(--primary),0.50)]"
                            : "border-[#FFFBF2] hover:border-[rgba(var(--primary),0.50)]"
                        }`}
                      >
                        <div className="flex justify-start gap-2 items-center mb-3">
                          <h4 className="text-sm sm:text-lg lg:text-base 2xl:text-lg font-medium text-[var(--theme-paragraph)] capitalize">{store.name}</h4>
                          <span className={`px-2 lg:px-3 py-1 whitespace-nowrap rounded-full text-[10px] lg:text-[12] 2xl:text-sm font-semibold border ${status.statusColor}`}>
                            {status.statusText}
                          </span>
                        </div>
                        
                        <div className="flex flex-wrap -mx-2 text-sm text-gray-600">
                          <div className="w-full mb-3 px-2">
                            <div className="flex items-start gap-2">
                              <div className="min-w-7 h-7 md:min-w-8 md:h-8 bg-[rgba(var(--primary),1)] rounded-full inline-flex items-center justify-center">
                                <MapPin size={16} className="text-white mt-0.5 flex-shrink-0" />
                              </div>
                              <p className="flex-1 text-xs sm:text-sm lg:text-sm 2xl:text-base self-center">{store.address}</p>
                            </div>
                          </div>
                          <div className="xxl:w-6/12 xl:w-6/12 lg:w-6/12 md:w-1/3 sm:w-6/12 w-6/12 mb-3 px-2">
                            <div className="flex items-center gap-2">
                              <div className="min-w-7 h-7 md:min-w-8 md:h-8 bg-[rgba(var(--primary),1)] rounded-full inline-flex items-center justify-center">
                                <Phone size={16} className="text-white" />
                              </div>
                              <a href={`tel:${store.phone}`} className="hover:text-primary text-xs sm:text-sm lg:text-sm 2xl:text-base">
                                {store.phone}
                              </a>
                            </div>
                          </div>
                          <div className="xxl:w-6/12 xl:w-6/12 lg:w-6/12 md:w-1/3 sm:w-6/12 w-6/12 mb-3 px-2">
                            <div className="flex items-center gap-2">
                              <div className="min-w-7 h-7 md:min-w-8 md:h-8 bg-[rgba(var(--primary),1)] rounded-full inline-flex items-center justify-center">
                                <Clock size={16} className="text-white" />
                              </div>
                              <span className="text-xs sm:text-sm lg:text-sm 2xl:text-base">
                                {formatTime(store.openTime)} - {formatTime(store.closeTime)}
                              </span>
                            </div>
                          </div>
                        </div>
                        
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            openInGoogleMaps(store.address);
                          }}
                          className="mt-3 theme-btn w-full !font-medium !tracking-[0] !capitalize"
                        >
                          Get Directions
                        </button>
                      </div>
                    );
                  })
                )}
              </div>
            </div>
            {/* Map Section - Using iframe without API key */}
            <div className="2xl:w-7/12 xl:w-7/12 lg:w-7/12 md:w-8/12 sm:w-full w-full px-3 xl:px-4 2xl:px-6 mb-4 mb-lg-0">
              <div className="bg-white p-4 md:p-5 2xl:p-6 overflow-hidden sticky top-[75px] lg:top-[85px] xl:top-[95px] 2xl:top-[105px]">
                <div className="border-0">
                  <div className="flex justify-between items-center gap-3 mb-4">
                    <div>
                      <h3 className="text-sm md:text-lg lg:text-lg 2xl:text-xl font-bold text-gray-800">
                        {selectedStore ? selectedStore.name : "Store Location"}
                      </h3>
                      {selectedStore && (
                        <p className="text-xs md:text-sm lg:text-base 2xl:text-lg text-[var(--theme-paragraph)] font-medium">
                          {selectedStore.address}
                        </p>
                      )}
                    </div>
                    {selectedStore && (
                      <button
                        onClick={() => openInGoogleMaps(selectedStore.address)}
                        className="flex items-center text-nowrap gap-2 text-xs md:text-sm 2xl:text-base group text-[rgba(var(--primary),1)] hover:text-[rgba(var(--secondary),1)] transition self-end mb-[3px] transition duration-300" 
                      >
                        <span className="border-b border-[rgba(var(--primary),0.70)] group-hover:border-[rgba(var(--secondary),1)] transition duration-300">Open in Maps</span>
                        <ExternalLink size={16} />
                      </button>
                    )}
                  </div>
                </div>
                
                {/* Google Maps Iframe - No API key required */}
                {selectedStore && (
                  <div className="w-full h-96">
                    <iframe
                      src={getDirectMapUrl(selectedStore.address)}
                      width="100%"
                      height="100%"
                      style={{ border: 0 }}
                      allowFullScreen
                      loading="lazy"
                      referrerPolicy="no-referrer-when-downgrade"
                      title={`Map showing location of ${selectedStore.name}`}
                    />
                  </div>
                )}
                
                {/* Store Details Footer */}
                {selectedStore && (
                  <div className="pt-4">
                    <div className="grid sm:grid-cols-2 gap-4">
                      <div>
                        <h4 className="text-sm sm:text-sm lg:text-base 2xl:text-lg font-semibold text-gray-700">Opening Hours</h4>
                        <p className="text-xs sm:text-sm lg:text-base 2xl:text-lg text-[var(--theme-paragraph)]">
                          Monday - Sunday: {formatTime(selectedStore.openTime)} - {formatTime(selectedStore.closeTime)}
                        </p>
                      </div>
                      <div>
                        <h4 className="sm:text-sm lg:text-base 2xl:text-lg font-semibold text-gray-700">Contact</h4>
                        <p className="text-xs sm:text-sm lg:text-base 2xl:text-lg text-[var(--theme-paragraph)]">
                          Phone: <a href={`tel:${selectedStore.phone}`} className="text-[var(--theme-paragraph)] hover:text-[rgba(var(--primary),1)] transition duration-300]">{selectedStore.phone}</a>
                        </p>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Store List Summary */}
          {/* {!loading && stores.length > 0 && (
            <div className="mt-8 p-4 bg-primary/10 rounded-lg">
              <h3 className="text-lg font-semibold text-gray-800 mb-2">Store Locations</h3>
              <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
                {stores.map((store) => (
                  <button
                    key={store._id}
                    onClick={() => setSelectedStore(store)}
                    className="text-left text-sm text-gray-600 hover:text-primary transition"
                  >
                    • {store.name} - {store.address.split(",")[0]}
                  </button>
                ))}
              </div>
            </div>
          )} */}

          {/* No stores message */}
          {!loading && stores.length === 0 && (
            <div className="text-center py-12">
              <MapPin size={64} className="mx-auto text-gray-300 mb-4" />
              <h3 className="text-xl font-semibold text-gray-700 mb-2">No Stores Found</h3>
              <p className="text-gray-500">We couldn't find any stores at the moment. Please check back later.</p>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}