'use client';

import { Plane, MapPin } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import Link from 'next/link';
import Image from 'next/image';
import { cn } from '@/lib/utils';
import DataFetchError from '@/components/DataFetchError';
import TravelStepper from '@/components/TravelStepper';

const FETCH_TIMEOUT_MS = 15000;

interface TrendItem {
  id: string;
  name: string;
  image: string;
  description?: string;
}

interface InspirationItem {
  title: string;
  summary: string;
  image?: string;
  url?: string;
}

const Page = () => {
  const [trending, setTrending] = useState<{ items?: TrendItem[] } | null>(null);
  const [inspiration, setInspiration] = useState<{ items?: InspirationItem[] } | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [stepperOpen, setStepperOpen] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    setError(null);
    try {
      const [trRes, inRes] = await Promise.all([
        fetch('/api/v1/travel/trending', { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }),
        fetch('/api/v1/travel/inspiration', { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }),
      ]);
      const trData = await trRes.json().catch(() => ({}));
      const inData = await inRes.json().catch(() => ({}));
      setTrending(trData);
      setInspiration(inData);
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'Error';
      const isTimeout = msg.includes('timeout') || (err as Error)?.name === 'AbortError';
      setError(isTimeout ? 'Request timed out. Try again.' : msg);
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

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

  const trendItems = trending?.items ?? [];
  const inspItems = inspiration?.items ?? [];

  return (
    <div className="flex flex-col pt-10 pb-28 lg:pb-8 px-4 max-w-5xl mx-auto w-full">
      <div className="flex items-center justify-between gap-3 border-b border-light-200/20 dark:border-dark-200/20 pb-6">
        <div className="flex items-center gap-3">
          <Plane size={40} className="text-[#EA580C]" />
          <h1 className="text-4xl font-normal">Travel</h1>
        </div>
        <button
          onClick={() => setStepperOpen(true)}
          className={cn(
            'flex items-center gap-2 px-4 py-2 rounded-xl font-medium',
            'bg-[#EA580C] text-white hover:opacity-90 transition'
          )}
        >
          <MapPin size={18} />
          Plan a trip
        </button>
      </div>

      {stepperOpen && <TravelStepper onClose={() => setStepperOpen(false)} />}

      {error ? (
        <DataFetchError message={error} onRetry={fetchData} />
      ) : loading ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-6">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <div
              key={i}
              className="rounded-2xl overflow-hidden bg-light-secondary dark:bg-dark-secondary animate-pulse"
            >
              <div className="aspect-video bg-light-200 dark:bg-dark-200" />
              <div className="p-4">
                <div className="h-5 w-3/4 bg-light-200 dark:bg-dark-200 rounded mb-2" />
                <div className="h-4 w-1/2 bg-light-200 dark:bg-dark-200 rounded" />
              </div>
            </div>
          ))}
        </div>
      ) : (
        <>
          {trendItems.length > 0 && (
            <section className="mt-6">
              <h2 className="text-xl font-medium mb-4">Trending Destinations</h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                {trendItems.map((item) => (
                  <Link
                    key={item.id}
                    href={`/?q=${encodeURIComponent(`travel to ${item.name}`)}&answerMode=travel`}
                    className="rounded-2xl overflow-hidden bg-light-secondary dark:bg-dark-secondary shadow-sm border border-light-200/20 dark:border-dark-200/20 hover:opacity-90 transition"
                  >
                    <div className="relative aspect-video">
                      <Image
                        src={item.image || 'https://placehold.co/400x225/e5e7eb/6b7280?text='}
                        alt={item.name}
                        fill
                        className="object-cover"
                        sizes="(max-width: 640px) 100vw, 33vw"
                        unoptimized={item.image?.includes('placehold')}
                      />
                    </div>
                    <div className="p-4">
                      <h3 className="font-medium">{item.name}</h3>
                      {item.description && (
                        <p className="text-sm text-black/60 dark:text-white/60 mt-1 line-clamp-2">
                          {item.description}
                        </p>
                      )}
                    </div>
                  </Link>
                ))}
              </div>
            </section>
          )}

          {inspItems.length > 0 && (
            <section className="mt-10">
              <h2 className="text-xl font-medium mb-4">Inspiration</h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {inspItems.map((item, i) => (
                  <div
                    key={i}
                    className={cn(
                      'rounded-2xl p-4 bg-light-secondary dark:bg-dark-secondary',
                      'border border-light-200/20 dark:border-dark-200/20'
                    )}
                  >
                    <h3 className="font-medium">{item.title}</h3>
                    {item.summary && (
                      <p className="text-sm text-black/60 dark:text-white/60 mt-2 line-clamp-2">
                        {item.summary}
                      </p>
                    )}
                    {item.url && (
                      <a
                        href={item.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-sm text-[#EA580C] mt-2 inline-block hover:underline"
                      >
                        Read more →
                      </a>
                    )}
                  </div>
                ))}
              </div>
            </section>
          )}

          {!loading && trendItems.length === 0 && inspItems.length === 0 && (
            <div className="mt-6 p-6 rounded-2xl bg-light-secondary dark:bg-dark-secondary text-center text-black/60 dark:text-white/60">
              <p>Travel content will appear here when travel-svc is running.</p>
              <p className="text-sm mt-2">Enable travel-svc in deploy.config.yaml</p>
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default Page;
