import { useState } from 'react';
import { Link } from 'react-router-dom';
import { heroImageChain, visualAssets } from '../assets/visualAssets';
import { useRecipes } from '../hooks/useRecipes';
import { useTags } from '../hooks/useTags';
import { RecipeCard } from '../components/RecipeCard';
import { MissionControlPanel } from '../components/MissionControlPanel';
import type { HarnessStatus } from '../types/recipe';
import { radius } from '../theme';

const emptyStatus: HarnessStatus = {
  running: false,
  version: '-',
  uptime: 0,
};

const featureHighlights = [
  {
    title: 'Organize with tags',
    copy: 'Group your meals by cuisine, prep style, or dietary preference so finding dinner is instant.',
    icon: '/assets/category/icon-dinner.svg',
  },
  {
    title: 'Capture from the web',
    copy: 'Import recipe links and keep your best discoveries in one place instead of scattered bookmarks.',
    icon: '/assets/category/icon-lunch.svg',
  },
  {
    title: 'Cook with confidence',
    copy: 'Use clear recipe cards and streamlined actions while planning, prepping, and cooking.',
    icon: '/assets/category/icon-breakfast.svg',
  },
] as const;

export function RecipeListPage() {
  const [searchTerm, setSearchTerm] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedTagId, setSelectedTagId] = useState<number | null>(null);
  const [heroCandidateIndex, setHeroCandidateIndex] = useState(0);

  const heroCandidates = heroImageChain();
  const heroSrc = heroCandidates[Math.min(heroCandidateIndex, heroCandidates.length - 1)];

  const { recipes, loading, error, hasMore, loadMore } = useRecipes({
    search: searchQuery,
    limit: 20,
    tagId: selectedTagId,
  });

  const { tags, loading: tagsLoading } = useTags();

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setSearchQuery(searchTerm);
  };

  const handleClearSearch = () => {
    setSearchTerm('');
    setSearchQuery('');
  };

  const handleClearFilters = () => {
    setSearchTerm('');
    setSearchQuery('');
    setSelectedTagId(null);
  };

  const filteredRecipes = recipes;
  const hasActiveFilters = Boolean(searchQuery) || selectedTagId !== null;

  return (
    <div className="mx-auto max-w-6xl pb-8">
      <MissionControlPanel status={emptyStatus} />

      <section
        className="relative mt-6 overflow-hidden border border-slate-200/80 bg-white/90 p-0 shadow-card"
        style={{ borderRadius: radius.xl }}
      >
        <div className="grid grid-cols-1 lg:grid-cols-2">
          <div className="flex flex-col justify-center gap-4 px-6 py-8 md:px-10 md:py-12">
            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-orange-500 md:text-sm">Your kitchen companion</p>
            <h1 className="text-3xl font-extrabold leading-tight text-slate-900 md:text-5xl">Plan meals faster and keep every favorite recipe organized</h1>
            <p className="max-w-lg text-sm text-slate-600 md:text-base">
              Build your personal cookbook with better structure, quick tag filters, and easy capture from web links.
            </p>
            <div className="flex flex-wrap gap-3 pt-1">
              <Link
                to="/recipe/new"
                className="inline-flex min-h-11 items-center gap-2 rounded-lg bg-blue-600 px-5 py-2.5 font-semibold text-white shadow transition-all duration-200 hover:-translate-y-0.5 hover:bg-blue-700 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
                style={{ borderRadius: radius.md }}
              >
                <span aria-hidden="true">✨</span>
                Start a Recipe
              </Link>
              <a
                href="#recipes-grid"
                className="inline-flex min-h-11 items-center gap-2 rounded-lg border border-slate-200 bg-white px-5 py-2.5 font-semibold text-slate-700 transition-all duration-200 hover:-translate-y-0.5 hover:bg-slate-50 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
                style={{ borderRadius: radius.md }}
              >
                <span aria-hidden="true">📚</span>
                Browse Library
              </a>
            </div>
          </div>
          <div className="relative min-h-[260px] bg-slate-100 md:min-h-[320px] lg:min-h-full">
            <img
              src={heroSrc}
              alt={visualAssets.hero.alt}
              className="h-full w-full object-cover"
              onError={() => {
                if (heroCandidateIndex < heroCandidates.length - 1) {
                  setHeroCandidateIndex((current) => current + 1);
                }
              }}
            />
            <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-slate-900/45 via-slate-900/15 to-transparent" />
            <div className="absolute bottom-4 left-4 rounded-full bg-white/90 px-4 py-1.5 text-sm font-semibold text-slate-800 shadow">
              {filteredRecipes.length} saved recipes
            </div>
          </div>
        </div>
      </section>

      <section className="mt-6 grid grid-cols-1 gap-4 md:grid-cols-3">
        {featureHighlights.map((feature) => (
          <article
            key={feature.title}
            className="rounded-xl border border-slate-200/80 bg-white/85 p-4 shadow-card"
            style={{ borderRadius: radius.lg }}
          >
            <img src={feature.icon} alt="" aria-hidden="true" className="h-10 w-10" />
            <h2 className="mt-3 text-lg font-bold text-slate-900">{feature.title}</h2>
            <p className="mt-1 text-sm text-slate-600">{feature.copy}</p>
          </article>
        ))}
      </section>

      <section
        className="mb-10 mt-7 flex flex-col gap-4 rounded-xl border border-slate-200/80 bg-white/90 px-5 py-6 shadow-card md:px-6"
        style={{ borderRadius: radius.lg, boxShadow: '0 2px 8px 0 rgba(28,30,34,0.07)' }}
      >
        <div className="flex flex-col justify-between gap-4 md:flex-row md:items-end">
          <div>
            <h2 className="mb-0 text-2xl font-extrabold text-gray-900">Recipe Library</h2>
            <p className="mt-1 text-sm text-gray-500">Search, filter, and jump back into your most-used meals</p>
          </div>
        </div>

        <form onSubmit={handleSearch} className="mt-3 flex flex-col items-stretch gap-3 md:mt-0 md:flex-row">
          <div className="relative flex-1">
            <input
              type="text"
              placeholder="Search recipes by title, ingredients, or tags..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-base focus:border-transparent focus:ring-2 focus:ring-blue-500"
              style={{ borderRadius: radius.md, minHeight: 44 }}
            />
            {!!searchQuery && (
              <button
                type="button"
                onClick={handleClearSearch}
                className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-gray-400 transition-colors hover:text-gray-600 focus-visible:ring-2 focus-visible:ring-blue-500"
                aria-label="Clear search"
              >
                ✕
              </button>
            )}
          </div>
          <button
            type="submit"
            className="min-h-11 rounded-lg border border-gray-200 bg-gray-100 px-6 py-2 font-semibold text-gray-700 transition-all duration-200 hover:-translate-y-0.5 hover:bg-gray-200 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
            style={{ borderRadius: radius.md }}
          >
            Search
          </button>
        </form>

        {!tagsLoading && tags.length > 0 && (
          <div className="mt-0 flex flex-wrap items-center gap-2 md:mt-2">
            <span className="mr-1 text-sm font-medium text-gray-700">Filter by tag:</span>
            <button
              onClick={() => setSelectedTagId(null)}
              className={
                selectedTagId === null
                  ? 'rounded-full bg-blue-600 px-3 py-1.5 text-sm font-semibold text-white shadow outline-none transition-all duration-150 hover:-translate-y-0.5 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2'
                  : 'rounded-full bg-gray-100 px-3 py-1.5 text-sm font-medium text-gray-700 outline-none transition-all duration-150 hover:-translate-y-0.5 hover:bg-gray-200 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2'
              }
              style={{ borderRadius: radius.full }}
            >
              All Recipes
            </button>
            {tags.map((tag) => (
              <button
                key={tag.id}
                onClick={() => setSelectedTagId(tag.id)}
                className={
                  selectedTagId === tag.id
                    ? 'rounded-full px-3 py-1.5 text-sm font-semibold text-white shadow outline-none transition-all duration-150 hover:-translate-y-0.5 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2'
                    : 'rounded-full bg-gray-100 px-3 py-1.5 text-sm font-medium text-gray-700 outline-none transition-all duration-150 hover:-translate-y-0.5 hover:bg-gray-200 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2'
                }
                style={{ backgroundColor: selectedTagId === tag.id ? tag.color : '', borderRadius: radius.full }}
              >
                {tag.name}
              </button>
            ))}
          </div>
        )}

        {hasActiveFilters && (
          <div className="mt-2 flex items-center gap-3 text-sm">
            <span className="text-gray-600">Active filters:</span>
            {searchQuery && <span className="rounded bg-blue-50 px-2 py-1 text-blue-700">Search: "{searchQuery}"</span>}
            {selectedTagId !== null && (
              <span className="rounded bg-blue-50 px-2 py-1 text-blue-700">Tag: {tags.find((t) => t.id === selectedTagId)?.name}</span>
            )}
            <button onClick={handleClearFilters} className="rounded-sm font-medium text-blue-600 transition-colors hover:text-blue-700 focus-visible:ring-2 focus-visible:ring-blue-500">
              Clear all filters
            </button>
          </div>
        )}
      </section>

      {error && (
        <div className="my-6 rounded-lg border border-red-200 bg-red-50 p-4 text-center">
          <p className="text-red-800">
            <strong>Error:</strong> {error}
          </p>
        </div>
      )}

      {loading && recipes.length === 0 && (
        <div className="mx-auto my-8 max-w-4xl rounded-xl border border-slate-200/80 bg-white/80 p-8 text-center shadow-card" style={{ borderRadius: radius.lg }}>
          <div className="mb-4 text-5xl" aria-hidden="true">🍽️</div>
          <p className="text-lg font-semibold text-slate-700">Warming up your recipe shelf...</p>
          <div className="mx-auto mt-5 h-2 w-56 overflow-hidden rounded-full bg-slate-200">
            <div className="h-full w-1/2 animate-pulse rounded-full bg-blue-500" />
          </div>
        </div>
      )}

      {!loading && !error && filteredRecipes.length === 0 && (
        <div
          className="mx-auto flex max-w-xl flex-col items-center gap-2 rounded-xl border border-dashed border-orange-200 bg-gradient-to-br from-white to-orange-50 p-14 text-center shadow-card"
          style={{ borderRadius: radius.lg }}
        >
          <img src="/assets/empty-state/no-recipes.svg" alt="" aria-hidden="true" className="mb-2 h-28 w-28" />
          <h3 className="mb-2 text-xl font-bold text-gray-800">{searchQuery ? 'No recipes found' : 'No recipes yet'}</h3>
          <p className="mb-4 text-gray-600">{searchQuery ? 'Try another keyword or clear filters.' : 'Start your cookbook with a first delicious recipe.'}</p>
          {!searchQuery && (
            <Link
              to="/recipe/new"
              className="inline-flex min-h-11 items-center gap-2 rounded-lg bg-blue-600 px-6 py-3 font-semibold text-white shadow transition-all duration-200 hover:-translate-y-0.5 hover:bg-blue-700 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
              style={{ borderRadius: radius.md }}
            >
              <span aria-hidden="true">🍳</span>
              Add Your First Recipe
            </Link>
          )}
        </div>
      )}

      {filteredRecipes.length > 0 && (
        <>
          <div id="recipes-grid" className="mt-8 grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-3">
            {filteredRecipes.map((recipe) => (
              <RecipeCard key={recipe.id} recipe={recipe} tags={recipe.tags} />
            ))}
          </div>
          {hasMore && (
            <div className="mt-8 text-center">
              <button
                onClick={loadMore}
                disabled={loading}
                className="rounded-lg border bg-gray-100 px-6 py-3 font-medium text-gray-700 transition-all duration-200 hover:-translate-y-0.5 hover:bg-gray-200 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                style={{ borderRadius: radius.md }}
              >
                {loading ? 'Loading...' : 'Load More'}
              </button>
            </div>
          )}
          <div className="mt-7 text-center text-sm text-gray-500">
            Showing {filteredRecipes.length} recipe{filteredRecipes.length !== 1 ? 's' : ''}
          </div>
        </>
      )}
    </div>
  );
}
