'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import axios from 'axios';
import InternalPageTemplate from '@/components/InternalPageTemplate';
import { useAuthStore } from '@/store/authStore';
import { useTranslations } from 'next-intl';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';

interface SearchResult {
  price: string;
  currency: string;
  description: string;
}

interface Search {
  _id: string;
  url: string;
  geo: string[];
  currency: string;
  results: {
    provider: string;
    desktop: SearchResult;
    mobile: SearchResult;
    reserveUrl?: string;
  } | null;
  createdAt: string;
}

function providerLabel(provider: string): string {
  const map: Record<string, string> = {
    booking: 'Booking.com',
    airbnb: 'Airbnb',
    expedia: 'Expedia',
    hotels: 'Hotels.com',
    vrbo: 'VRBO',
    agoda: 'Agoda',
    trip: 'Trip.com',
    travelocity: 'Travelocity',
  };
  return map[provider] ?? provider.charAt(0).toUpperCase() + provider.slice(1);
}

function formatDate(iso: string): string {
  return new Date(iso).toLocaleString(undefined, {
    month: 'short', day: 'numeric', year: 'numeric',
    hour: '2-digit', minute: '2-digit',
  });
}

function truncateUrl(url: string, max = 60): string {
  try {
    const { hostname, pathname } = new URL(url);
    const short = hostname.replace('www.', '') + pathname;
    return short.length > max ? short.slice(0, max) + '…' : short;
  } catch {
    return url.length > max ? url.slice(0, max) + '…' : url;
  }
}

export default function SearchesPage() {
  const router = useRouter();
  const { token, isAuthenticated } = useAuthStore();
  const t = useTranslations('searches');
  const [searches, setSearches] = useState<Search[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!isAuthenticated) { router.push('/signin'); return; }

    axios
      .get(`${API_URL}/api/searches`, { headers: { Authorization: `Bearer ${token}` } })
      .then(r => setSearches(r.data.searches))
      .catch(() => setSearches([]))
      .finally(() => setLoading(false));
  }, [isAuthenticated, token, router]);

  if (!isAuthenticated) return null;

  return (
    <InternalPageTemplate>
      <div className="mb-12">
        <h1 className="text-4xl font-bold text-gray-900 mb-4">{t('heading')}</h1>
        <p className="text-gray-500 text-lg max-w-2xl leading-relaxed">
          {t('subheading')}
        </p>
      </div>

      {loading ? (
        <div className="flex items-center gap-3 text-gray-400 text-sm py-12">
          <svg className="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" />
          </svg>
          {t('loading')}
        </div>
      ) : searches.length === 0 ? (
        <div className="text-center py-20">
          <p className="text-gray-400 text-lg mb-2">{t('emptyHeading')}</p>
          <p className="text-gray-400 text-sm">{t('emptyBody')}</p>
        </div>
      ) : (
        <div className="flex flex-col gap-3">
          {searches.map(s => {
            const provider = s.results?.provider ?? 'unknown';
            const desktop = s.results?.desktop;
            const mobile = s.results?.mobile;
            const hasPrice = desktop?.price || mobile?.price;

            return (
              <div key={s._id} className="bg-gray-50 border border-gray-100 rounded-2xl px-6 py-4">
                <div className="flex items-start justify-between gap-4 flex-wrap">
                  {/* Left: URL + meta */}
                  <div className="flex flex-col gap-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-xs font-medium bg-purple-100 text-brand-purple px-2 py-0.5 rounded-full">
                        {providerLabel(provider)}
                      </span>
                      {s.geo.length > 0 && s.geo.map(g => (
                        <span key={g} className="text-xs bg-gray-100 text-gray-500 px-2 py-0.5 rounded-full">
                          {g}
                        </span>
                      ))}
                      {s.currency && (
                        <span className="text-xs bg-gray-100 text-gray-500 px-2 py-0.5 rounded-full">
                          {s.currency}
                        </span>
                      )}
                    </div>
                    <a
                      href={s.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-sm text-gray-700 hover:text-brand-purple transition-colors font-mono truncate max-w-[480px]"
                      title={s.url}
                    >
                      {truncateUrl(s.url)}
                    </a>
                    <span className="text-xs text-gray-400">{formatDate(s.createdAt)}</span>
                  </div>

                  {/* Right: prices */}
                  {hasPrice ? (
                    <div className="flex items-center gap-6 shrink-0">
                      {desktop?.price && (
                        <div className="text-right">
                          <p className="text-xs text-gray-400 mb-0.5">{t('desktopLabel')}</p>
                          <p className="text-lg font-semibold text-gray-900">
                            {desktop.currency} {desktop.price}
                          </p>
                          {desktop.description && (
                            <p className="text-xs text-gray-400 max-w-[180px] truncate">{desktop.description}</p>
                          )}
                        </div>
                      )}
                      {mobile?.price && (
                        <div className="text-right">
                          <p className="text-xs text-gray-400 mb-0.5">{t('mobileLabel')}</p>
                          <p className="text-lg font-semibold text-gray-900">
                            {mobile.currency} {mobile.price}
                          </p>
                          {mobile.description && (
                            <p className="text-xs text-gray-400 max-w-[180px] truncate">{mobile.description}</p>
                          )}
                        </div>
                      )}
                    </div>
                  ) : (
                    <span className="text-xs text-gray-400 shrink-0 self-center">{t('noPriceFound')}</span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </InternalPageTemplate>
  );
}
