import { createFileRoute, useNavigate, Outlet, useLocation } from '@tanstack/react-router'
import { useStores } from '../hooks/prominent-api-hooks'
import { p, div } from 'web-components'
import { AppLayout } from '../components/AppLayout'
import { Store, ArrowRight, Building2 } from 'lucide-react'

export const Route = createFileRoute('/stores')({ component: StoresPage })

export const ASSETS_BASE_URL = 'http://localhost:4000/assets'

function StoresPage() {
  const navigate = useNavigate()
  const location = useLocation()
  const { data: storesData, isLoading, error } = useStores()
  const stores = storesData?.stores || []
  
  // Check if we're on the exact /stores path (not a child like /stores/123)
  const isExactStoresPath = location.pathname === '/stores'

  if (isLoading) {
    return (
      <AppLayout>
        <div className="flex min-h-screen flex-col items-center justify-center bg-slate-50">
          <div className="flex h-20 w-20 items-center justify-center">
            <Building2 className="h-12 w-12 text-brand-200" />
          </div>
          <p className="mt-4 text-[10px] font-black uppercase tracking-widest text-slate-400">
            Opening Marketplace...
          </p>
        </div>
      </AppLayout>
    )
  }

  if (error) {
    return (
      <AppLayout>
        <div className="flex min-h-screen flex-col items-center justify-center bg-slate-50 p-10">
          <div className="mb-6 flex h-20 w-20 items-center justify-center rounded-full bg-rose-50">
            <svg className="h-8 w-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <p className="font-bold mb-2 text-center text-xl text-slate-900">
            Store Fetch Failed
          </p>
          <p className="mb-8 text-center font-medium leading-5 text-slate-500">
            We couldn't reach our vendor network.
          </p>
          <button
            onClick={() => window.location.reload()}
            className="rounded-2xl bg-brand-600 px-8 py-3 text-xs font-black uppercase tracking-widest text-white shadow-lg shadow-brand-200"
          >
            Retry
          </button>
        </div>
      </AppLayout>
    )
  }

  return (
    <AppLayout>
      <div className="min-h-screen bg-slate-50 pb-32">
        {isExactStoresPath ? (
          <>
            <div className="px-3 pt-6">
              {/* Header */}
              <div className="mb-4 flex items-center">
                <div className="mr-3 h-6 w-1 rounded-full bg-gradient-to-b from-brand-500 to-brand-700" />
                <div>
                  <p className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400">
                    Our Outlets
                  </p>
                  <p className="font-bold text-3xl tracking-tight text-slate-900">
                    Our Stores
                  </p>
                </div>
              </div>
              <p className="pr-4 text-sm font-medium leading-5 text-slate-500">
                Experience the finest selection of premium meat, poultry, fresh fruits, vegetables, and dairy directly from our own stores.
              </p>
            </div>

            {/* Store Cards */}
            <div className="px-3 pt-4">
              {stores.map((store: any) => (
                <StoreCard key={store.id} store={store} />
              ))}
            </div>

            {stores.length === 0 && (
              <div className="flex flex-1 flex-col items-center justify-center py-20">
                <div className="mb-6 flex h-24 w-24 items-center justify-center rounded-full bg-white shadow-sm">
                  <Building2 className="h-12 w-12 text-slate-400" />
                </div>
                <p className="font-bold text-center text-xl tracking-tight text-slate-900">
                  No Stores Available
                </p>
              </div>
            )}
          </>
        ) : (
          /* Render child routes (e.g., store detail) when not on exact /stores path */
          <Outlet />
        )}
      </div>
    </AppLayout>
  )
}

interface StoreCardProps {
  store: any
}

function StoreCard({ store }: StoreCardProps) {
  const navigate = useNavigate()
    const sampleProducts = store.sampleProducts || []
    const remainingCount = store.productCount - sampleProducts.length
    const isMeatStore = store.name?.toLowerCase().includes('meat')

    const navigateToStore = () => {
      navigate({
        to: '/stores/$storeId',
        params: { storeId: String(store.id) },
      })
    }

    return (
      <div className="mb-4 overflow-hidden rounded-3xl border border-slate-200 bg-white shadow-lg shadow-slate-200">
        {/* Meat Store Images - Show at top if store name contains 'meat' */}

        {/* Top Header Section */}
        <div onClick={navigateToStore} className="cursor-pointer p-4 pb-0">
          <div className="mb-4 flex items-center">
            <div className="h-12 w-12 rounded-xl border border-slate-200 bg-slate-50 p-0.5 shadow-sm">
              <div className="relative h-full w-full overflow-hidden rounded-[10px]">
                {store.signedImageUrl || store.imageUrl ? (
                  <img
                    src={store.signedImageUrl || store.imageUrl}
                    alt={store.name}
                    className="h-full w-full object-cover"
                  />
                ) : (
                  <div className="flex h-full w-full items-center justify-center">
                    <Store className="h-5 w-5 text-slate-400" />
                  </div>
                )}
              </div>
            </div>

            <div className="ml-3 flex-1">
              <p className="font-bold text-lg text-slate-900">
                {store.name}
              </p>
            </div>

            <div className="flex items-center justify-center rounded-xl border border-brand-100 bg-brand-50 px-2.5 py-1.5">
              <p className="font-bold text-sm text-brand-700">
                {store.productCount}
              </p>
              <p className="ml-1 text-[8px] font-black uppercase tracking-tighter text-brand-600">
                Items
              </p>
            </div>
          </div>
        </div>

        {/* Horizontal Scrollable Product Collection */}
        {sampleProducts.length > 0 && (
          <div className="mb-5">
            <div className="flex gap-3 overflow-x-auto px-4 pb-2 scrollbar-hide">
              {sampleProducts.map((product: any) => (
                <div
                  key={product.id}
                  onClick={navigateToStore}
                  className="w-24 shrink-0 cursor-pointer items-center"
                >
                  <div className="mb-2 h-24 w-24 rounded-2xl border border-slate-200 bg-slate-50 p-1 shadow-sm">
                    <img
                      src={product.signedImageUrl || product.images?.[0]}
                      alt={product.name}
                      className="h-full w-full rounded-xl object-cover"
                    />
                  </div>
                  <p
                    className="font-bold text-center text-[10px] leading-tight text-slate-900"
                  >
                    {product.name}
                  </p>
                </div>
              ))}

              {remainingCount > 0 && (
                <div className="flex shrink-0 flex-col items-center justify-center">
                  <div
                    onClick={navigateToStore}
                    className="flex h-24 w-24 cursor-pointer flex-col items-center justify-center rounded-2xl bg-slate-900 shadow-md"
                  >
                    <p className="font-bold text-base text-white">
                      +{remainingCount}
                    </p>
                    <p className="text-[8px] font-black uppercase tracking-widest text-white/60">
                      Discover
                    </p>
                    <ArrowRight className="mt-1 h-4 w-4 text-white" />
                  </div>
                  <div className="h-8" />
                </div>
              )}
            </div>
          </div>
        )}

        {/* Explore Store Button */}
        <div className="px-4 pb-4">
          <div
            onClick={navigateToStore}
            className="flex flex-row items-center justify-center rounded-[18px] bg-brand-600 py-3 shadow-lg shadow-brand-200"
          >
            <p className="font-bold mr-2 text-sm uppercase tracking-wider text-white">
              Explore Store
            </p>
            <ArrowRight className="h-4 w-4 text-white" />
          </div>
        </div>
      </div>
    )
  }

