"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { VideoCard, type VideoCardData } from "@/components/video-card";
import { Avatar, EmptyState, FeedSkeleton } from "@/components/ui";
import { api } from "@/lib/api-client";
import { formatCount } from "@/lib/format";

type Results = {
  query: string;
  videos: (VideoCardData & { channelName: string; channelHandle: string; channelAvatar: string | null })[];
  shorts: { id: string; title: string; thumbnailUrl: string | null; views: number; channelName: string; channelHandle: string }[];
  channels: { id: string; name: string; handle: string; avatarUrl: string | null; description: string | null; subscriberCount: number; videoCount: number; subscribed: boolean }[];
  playlists: { id: string; title: string; thumbnailUrl: string | null; itemCount: number; ownerName: string | null }[];
  live: { id: string; title: string; thumbnailUrl: string | null; currentViewers: number; channelName: string; channelHandle: string }[];
  history: { query: string }[];
  trending: string[];
};

const TYPES = [
  ["all", "All"],
  ["videos", "Videos"],
  ["shorts", "Shorts"],
  ["channels", "Channels"],
  ["playlists", "Playlists"],
  ["live", "Live"],
] as const;

export function SearchResults({
  query,
  filters,
  signedIn,
}: {
  query: string;
  filters: { type?: string; sort?: string; duration?: string; uploadDate?: string };
  signedIn: boolean;
}) {
  const [type, setType] = useState(filters.type ?? "all");
  const [sort, setSort] = useState(filters.sort ?? "relevance");
  const [duration, setDuration] = useState(filters.duration ?? "any");
  const [uploadDate, setUploadDate] = useState(filters.uploadDate ?? "any");
  const [data, setData] = useState<Results | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!query) return;
    setLoading(true);
    const params = new URLSearchParams({ q: query, type, sort, duration, uploadDate });
    void api<Results>(`/api/search?${params.toString()}`)
      .then(setData)
      .catch(() => setData(null))
      .finally(() => setLoading(false));
  }, [query, type, sort, duration, uploadDate]);

  if (!query) {
    return (
      <div className="px-4 py-8">
        <EmptyState icon="🔍" title="Search PlayTube" hint="Find videos, channels, shorts, playlists and live streams." />
      </div>
    );
  }

  return (
    <div className="px-4 py-4">
      <div className="no-scrollbar mb-4 flex gap-2 overflow-x-auto border-b border-line pb-3">
        {TYPES.map(([value, label]) => (
          <button
            key={value}
            onClick={() => setType(value)}
            className={`shrink-0 rounded-lg px-3 py-1.5 text-sm font-medium ${type === value ? "bg-fg text-bg" : "bg-chip"}`}
          >
            {label}
          </button>
        ))}
      </div>

      <details className="mb-4 rounded-xl bg-surface p-3 text-sm">
        <summary className="cursor-pointer font-semibold">Filters</summary>
        <div className="mt-3 grid gap-3 sm:grid-cols-3">
          <label className="space-y-1">
            <span className="text-xs font-semibold uppercase text-muted">Sort by</span>
            <select value={sort} onChange={(event) => setSort(event.target.value)} className="w-full rounded-lg border border-line bg-bg px-2 py-1.5">
              <option value="relevance">Relevance</option>
              <option value="date">Upload date</option>
              <option value="views">View count</option>
              <option value="rating">Rating</option>
            </select>
          </label>
          <label className="space-y-1">
            <span className="text-xs font-semibold uppercase text-muted">Duration</span>
            <select value={duration} onChange={(event) => setDuration(event.target.value)} className="w-full rounded-lg border border-line bg-bg px-2 py-1.5">
              <option value="any">Any</option>
              <option value="short">Under 4 minutes</option>
              <option value="medium">4 – 20 minutes</option>
              <option value="long">Over 20 minutes</option>
            </select>
          </label>
          <label className="space-y-1">
            <span className="text-xs font-semibold uppercase text-muted">Uploaded</span>
            <select value={uploadDate} onChange={(event) => setUploadDate(event.target.value)} className="w-full rounded-lg border border-line bg-bg px-2 py-1.5">
              <option value="any">Any time</option>
              <option value="hour">Last hour</option>
              <option value="today">Today</option>
              <option value="week">This week</option>
              <option value="month">This month</option>
              <option value="year">This year</option>
            </select>
          </label>
        </div>
      </details>

      {loading && !data ? <FeedSkeleton count={6} /> : null}

      {data ? (
        <div className="space-y-8">
          {data.channels?.length ? (
            <section className="space-y-4">
              {data.channels.map((channel) => (
                <div key={channel.id} className="flex items-center gap-4 rounded-xl p-2 hover:bg-surface">
                  <Link href={`/channel/${channel.handle}`}>
                    <Avatar name={channel.name} src={channel.avatarUrl} size={72} />
                  </Link>
                  <div className="min-w-0 flex-1">
                    <Link href={`/channel/${channel.handle}`} className="font-semibold">
                      {channel.name}
                    </Link>
                    <p className="text-xs text-muted">
                      @{channel.handle} · {formatCount(channel.subscriberCount)} subscribers · {channel.videoCount} videos
                    </p>
                    <p className="line-clamp-1 text-xs text-muted">{channel.description}</p>
                  </div>
                  {signedIn && !channel.subscribed ? (
                    <button
                      onClick={() => void api(`/api/channels/${channel.handle}`, { method: "POST" })}
                      className="rounded-full bg-brand px-4 py-1.5 text-sm font-semibold text-white"
                    >
                      Subscribe
                    </button>
                  ) : null}
                </div>
              ))}
            </section>
          ) : null}

          {data.live?.length ? (
            <section className="space-y-3">
              <h2 className="text-sm font-bold uppercase tracking-wide text-muted">Live now</h2>
              {data.live.map((stream) => (
                <Link key={stream.id} href={`/live/${stream.id}`} className="flex gap-3 rounded-xl p-2 hover:bg-surface">
                  <div className="aspect-video w-40 shrink-0 overflow-hidden rounded-lg bg-surface">
                    {stream.thumbnailUrl ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img src={stream.thumbnailUrl} alt="" className="h-full w-full object-cover" />
                    ) : null}
                  </div>
                  <div>
                    <p className="line-clamp-2 text-sm font-semibold">{stream.title}</p>
                    <p className="text-xs text-muted">{stream.channelName} · 🔴 {formatCount(stream.currentViewers)} watching</p>
                  </div>
                </Link>
              ))}
            </section>
          ) : null}

          {data.videos?.length ? (
            <section className="space-y-4">
              {data.videos.map((video) => (
                <div key={video.id} className="sm:hidden">
                  <VideoCard video={video} />
                </div>
              ))}
              <div className="hidden space-y-4 sm:block">
                {data.videos.map((video) => (
                  <VideoCard key={video.id} video={video} layout="row" />
                ))}
              </div>
            </section>
          ) : null}

          {data.shorts?.length ? (
            <section className="space-y-3">
              <h2 className="text-sm font-bold uppercase tracking-wide text-muted">Shorts</h2>
              <div className="no-scrollbar flex gap-3 overflow-x-auto">
                {data.shorts.map((short) => (
                  <Link key={short.id} href="/shorts" className="w-32 shrink-0">
                    <div className="aspect-[9/16] overflow-hidden rounded-xl bg-surface">
                      {short.thumbnailUrl ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img src={short.thumbnailUrl} alt="" className="h-full w-full object-cover" />
                      ) : null}
                    </div>
                    <p className="line-clamp-2 mt-2 text-xs font-medium">{short.title}</p>
                    <p className="text-[11px] text-muted">{formatCount(short.views)} views</p>
                  </Link>
                ))}
              </div>
            </section>
          ) : null}

          {data.playlists?.length ? (
            <section className="space-y-3">
              <h2 className="text-sm font-bold uppercase tracking-wide text-muted">Playlists</h2>
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                {data.playlists.map((playlist) => (
                  <Link key={playlist.id} href={`/playlist/${playlist.id}`} className="group">
                    <div className="aspect-video overflow-hidden rounded-xl bg-surface">
                      {playlist.thumbnailUrl ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img src={playlist.thumbnailUrl} alt="" className="h-full w-full object-cover" />
                      ) : (
                        <div className="grid h-full place-items-center text-3xl">📁</div>
                      )}
                    </div>
                    <p className="mt-2 line-clamp-2 text-sm font-semibold">{playlist.title}</p>
                    <p className="text-xs text-muted">{playlist.itemCount} videos · {playlist.ownerName ?? "Playlist"}</p>
                  </Link>
                ))}
              </div>
            </section>
          ) : null}

          {!loading &&
          !data.videos?.length &&
          !data.channels?.length &&
          !data.shorts?.length &&
          !data.playlists?.length &&
          !data.live?.length ? (
            <EmptyState icon="🔍" title="No results found" hint={`Nothing matched “${query}”. Try different keywords.`} />
          ) : null}
        </div>
      ) : null}
    </div>
  );
}
