import {
  mdiBookmarkOutline,
  mdiCheckCircleOutline,
  mdiClockOutline,
  mdiFire,
  mdiMagnify,
  mdiMovieOpen,
  mdiOpenInNew,
  mdiPlayCircle,
  mdiStarOutline,
  mdiTelevisionClassic,
} from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import Link from 'next/link';
import React, { ReactElement, useCallback, useEffect, useMemo, useState } from 'react';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import NotificationBar from '../components/NotificationBar';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import LayoutAuthenticated from '../layouts/Authenticated';
import { useAppSelector } from '../stores/hooks';

type BannerType = 'success' | 'danger' | 'warning' | 'info';
type TitleType = 'all' | 'movie' | 'tv_show';
type WatchStatus = 'plan_to_watch' | 'watching' | 'watched' | 'on_hold' | 'dropped';

type TitleRecord = {
  id: string;
  title_type: 'movie' | 'tv_show';
  name: string;
  tagline?: string;
  overview?: string;
  release_date?: string;
  first_air_date?: string;
  runtime_minutes?: number;
  number_of_seasons?: number;
  average_rating?: number | string;
  popularity_score?: number | string;
  is_trending?: boolean;
};

type WatchlistRecord = {
  id: string;
  name: string;
  description?: string;
};

type WatchlistItemRecord = {
  id: string;
  status: WatchStatus;
  note?: string;
  watched_at?: string;
  title?: TitleRecord;
};

type TitleDetailRecord = TitleRecord & {
  cast: string[];
  crew: string[];
  genres: string[];
  videos: Array<{ id: string; name: string; video_url?: string; site?: string }>;
};

const watchStatusOptions: Array<{
  value: WatchStatus;
  label: string;
  tone: string;
}> = [
  { value: 'plan_to_watch', label: 'Plan to watch', tone: 'bg-slate-500/15 text-slate-200 border border-slate-400/20' },
  { value: 'watching', label: 'Watching', tone: 'bg-blue-500/15 text-blue-200 border border-blue-400/20' },
  { value: 'watched', label: 'Watched', tone: 'bg-emerald-500/15 text-emerald-200 border border-emerald-400/20' },
  { value: 'on_hold', label: 'On hold', tone: 'bg-amber-500/15 text-amber-100 border border-amber-400/20' },
  { value: 'dropped', label: 'Dropped', tone: 'bg-rose-500/15 text-rose-200 border border-rose-400/20' },
];

const typeFilters: Array<{ value: TitleType; label: string }> = [
  { value: 'all', label: 'All titles' },
  { value: 'movie', label: 'Movies' },
  { value: 'tv_show', label: 'TV shows' },
];

const formatDate = (value?: string) => {
  if (!value) return 'TBA';

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return 'TBA';

  return new Intl.DateTimeFormat('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  }).format(date);
};

const getReleaseLabel = (title: TitleRecord) => {
  return title.title_type === 'tv_show' ? formatDate(title.first_air_date) : formatDate(title.release_date);
};

const getTypeLabel = (titleType: TitleRecord['title_type']) => {
  return titleType === 'tv_show' ? 'TV Show' : 'Movie';
};

const getTypeIcon = (titleType: TitleRecord['title_type']) => {
  return titleType === 'tv_show' ? mdiTelevisionClassic : mdiMovieOpen;
};

export default function WatchHub() {
  const { currentUser } = useAppSelector((state) => state.auth);

  const [catalog, setCatalog] = useState<TitleRecord[]>([]);
  const [catalogLoading, setCatalogLoading] = useState(false);
  const [catalogQuery, setCatalogQuery] = useState('');
  const [catalogType, setCatalogType] = useState<TitleType>('all');

  const [watchlists, setWatchlists] = useState<WatchlistRecord[]>([]);
  const [selectedWatchlistId, setSelectedWatchlistId] = useState('');
  const [watchlistsLoading, setWatchlistsLoading] = useState(false);
  const [watchlistItems, setWatchlistItems] = useState<WatchlistItemRecord[]>([]);
  const [watchlistItemsLoading, setWatchlistItemsLoading] = useState(false);

  const [highlightTrending, setHighlightTrending] = useState<TitleRecord[]>([]);
  const [highlightRecommended, setHighlightRecommended] = useState<TitleRecord[]>([]);

  const [selectedTitleSummary, setSelectedTitleSummary] = useState<TitleRecord | null>(null);
  const [selectedTitleDetails, setSelectedTitleDetails] = useState<TitleDetailRecord | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);

  const [watchlistForm, setWatchlistForm] = useState({
    name: 'My First Watchlist',
    description: 'Everything I want to watch next.',
  });
  const [createLoading, setCreateLoading] = useState(false);
  const [actionTitleId, setActionTitleId] = useState('');
  const [itemActionId, setItemActionId] = useState('');
  const [banner, setBanner] = useState<{ type: BannerType; message: string } | null>(null);

  const selectedWatchlist = useMemo(
    () => watchlists.find((watchlist) => watchlist.id === selectedWatchlistId) || null,
    [selectedWatchlistId, watchlists],
  );

  const loadCatalog = useCallback(async () => {
    setCatalogLoading(true);

    try {
      const response = await axios.get('/titles', {
        params: {
          page: 0,
          limit: 18,
          ...(catalogQuery ? { name: catalogQuery } : {}),
          ...(catalogType !== 'all' ? { title_type: catalogType } : {}),
        },
      });

      setCatalog(Array.isArray(response.data.rows) ? response.data.rows : []);
    } catch (error) {
      console.error('Failed to load title catalog:', error);
      setBanner({
        type: 'danger',
        message: 'We could not load the title catalog right now. Please refresh and try again.',
      });
    } finally {
      setCatalogLoading(false);
    }
  }, [catalogQuery, catalogType]);

  const loadHighlights = useCallback(async () => {
    try {
      const [trendingResponse, recommendedResponse] = await Promise.all([
        axios.get('/titles', {
          params: {
            page: 0,
            limit: 6,
            is_trending: true,
          },
        }),
        axios.get('/titles', {
          params: {
            page: 0,
            limit: 6,
            field: 'average_rating',
            sort: 'desc',
          },
        }),
      ]);

      setHighlightTrending(Array.isArray(trendingResponse.data.rows) ? trendingResponse.data.rows : []);
      setHighlightRecommended(
        Array.isArray(recommendedResponse.data.rows) ? recommendedResponse.data.rows : [],
      );
    } catch (error) {
      console.error('Failed to load highlight rails:', error);
    }
  }, []);

  const loadWatchlists = useCallback(
    async (preferredWatchlistId?: string) => {
      if (!currentUser?.id) return;

      setWatchlistsLoading(true);

      try {
        const response = await axios.get('/watchlists', {
          params: {
            page: 0,
            limit: 50,
            user: currentUser.id,
          },
        });

        const rows = Array.isArray(response.data.rows) ? response.data.rows : [];
        setWatchlists(rows);

        const nextSelectedId =
          preferredWatchlistId ||
          rows.find((watchlist: WatchlistRecord) => watchlist.id === selectedWatchlistId)?.id ||
          rows[0]?.id ||
          '';

        setSelectedWatchlistId(nextSelectedId);
      } catch (error) {
        console.error('Failed to load watchlists:', error);
        setBanner({
          type: 'danger',
          message: 'Your watchlists could not be loaded. Please try again in a moment.',
        });
      } finally {
        setWatchlistsLoading(false);
      }
    },
    [currentUser?.id, selectedWatchlistId],
  );

  const loadWatchlistItems = useCallback(async (watchlistId: string) => {
    if (!watchlistId) {
      setWatchlistItems([]);
      return;
    }

    setWatchlistItemsLoading(true);

    try {
      const response = await axios.get('/watchlist_items', {
        params: {
          page: 0,
          limit: 100,
          watchlist: watchlistId,
        },
      });

      setWatchlistItems(Array.isArray(response.data.rows) ? response.data.rows : []);
    } catch (error) {
      console.error('Failed to load watchlist items:', error);
      setBanner({
        type: 'danger',
        message: 'We could not load the selected watchlist. Please try again.',
      });
    } finally {
      setWatchlistItemsLoading(false);
    }
  }, []);

  useEffect(() => {
    if (!currentUser?.id) return;

    loadWatchlists();
    loadHighlights();
  }, [currentUser?.id, loadHighlights, loadWatchlists]);

  useEffect(() => {
    if (!currentUser?.id) return;

    const timeoutId = window.setTimeout(() => {
      loadCatalog();
    }, 250);

    return () => window.clearTimeout(timeoutId);
  }, [currentUser?.id, loadCatalog]);

  useEffect(() => {
    if (!selectedWatchlistId) {
      setWatchlistItems([]);
      return;
    }

    loadWatchlistItems(selectedWatchlistId);
  }, [loadWatchlistItems, selectedWatchlistId]);

  useEffect(() => {
    if (!selectedTitleSummary?.id) {
      setSelectedTitleDetails(null);
      return;
    }

    let isMounted = true;

    const loadTitleDetails = async () => {
      setDetailLoading(true);

      try {
        const [titleResponse, genresResponse, castResponse, crewResponse, videosResponse] = await Promise.all([
          axios.get(`/titles/${selectedTitleSummary.id}`),
          axios.get('/title_genres', {
            params: {
              page: 0,
              limit: 20,
              title: selectedTitleSummary.id,
            },
          }),
          axios.get('/title_cast', {
            params: {
              page: 0,
              limit: 8,
              title: selectedTitleSummary.id,
            },
          }),
          axios.get('/title_crew', {
            params: {
              page: 0,
              limit: 6,
              title: selectedTitleSummary.id,
            },
          }),
          axios.get('/videos', {
            params: {
              page: 0,
              limit: 6,
              title: selectedTitleSummary.id,
            },
          }),
        ]);

        if (!isMounted) return;

        setSelectedTitleDetails({
          ...titleResponse.data,
          genres: (genresResponse.data.rows || [])
            .map((row: { genre?: { name?: string } }) => row.genre?.name)
            .filter(Boolean),
          cast: (castResponse.data.rows || [])
            .map((row: { person?: { name?: string } }) => row.person?.name)
            .filter(Boolean),
          crew: (crewResponse.data.rows || [])
            .map((row: { person?: { name?: string; firstName?: string } }) => row.person?.name || row.person?.firstName)
            .filter(Boolean),
          videos: (videosResponse.data.rows || []).map(
            (row: { id: string; name: string; video_url?: string; site?: string }) => ({
              id: row.id,
              name: row.name,
              video_url: row.video_url,
              site: row.site,
            }),
          ),
        });
      } catch (error) {
        console.error('Failed to load title details:', error);
        if (isMounted) {
          setBanner({
            type: 'danger',
            message: 'The title details could not be loaded. Please choose another title.',
          });
        }
      } finally {
        if (isMounted) {
          setDetailLoading(false);
        }
      }
    };

    loadTitleDetails();

    return () => {
      isMounted = false;
    };
  }, [selectedTitleSummary?.id]);

  const handleCreateWatchlist = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!currentUser?.id) return;

    if (!watchlistForm.name.trim()) {
      setBanner({ type: 'warning', message: 'Give your watchlist a name before creating it.' });
      return;
    }

    setCreateLoading(true);

    try {
      await axios.post('/watchlists', {
        data: {
          name: watchlistForm.name.trim(),
          description: watchlistForm.description.trim(),
          visibility: 'private',
          is_public: false,
          user: currentUser.id,
        },
      });

      await loadWatchlists();
      setBanner({
        type: 'success',
        message: `“${watchlistForm.name.trim()}” is ready. Add a title to start your watch journey.`,
      });
    } catch (error) {
      console.error('Failed to create watchlist:', error);
      setBanner({
        type: 'danger',
        message: 'We could not create your watchlist. Please try again.',
      });
    } finally {
      setCreateLoading(false);
    }
  };

  const handleAddToWatchlist = async (title: TitleRecord) => {
    if (!selectedWatchlistId) {
      setBanner({
        type: 'warning',
        message: 'Create or select a watchlist before saving a title.',
      });
      return;
    }

    const existingItem = watchlistItems.find((item) => item.title?.id === title.id);
    if (existingItem) {
      setSelectedTitleSummary(existingItem.title || title);
      setBanner({
        type: 'info',
        message: `${title.name} is already in your watchlist. Update its status from the list on the right.`,
      });
      return;
    }

    setActionTitleId(title.id);

    try {
      await axios.post('/watchlist_items', {
        data: {
          watchlist: selectedWatchlistId,
          title: title.id,
          status: 'plan_to_watch',
          sort_order: watchlistItems.length + 1,
          added_at: new Date().toISOString(),
        },
      });

      await loadWatchlistItems(selectedWatchlistId);
      setSelectedTitleSummary(title);
      setBanner({
        type: 'success',
        message: `${title.name} was saved to ${selectedWatchlist?.name || 'your watchlist'}.`,
      });
    } catch (error) {
      console.error('Failed to add item to watchlist:', error);
      setBanner({
        type: 'danger',
        message: 'We could not save this title to your watchlist. Please try again.',
      });
    } finally {
      setActionTitleId('');
    }
  };

  const handleStatusChange = async (item: WatchlistItemRecord, status: WatchStatus) => {
    setItemActionId(item.id);

    try {
      await axios.put(`/watchlist_items/${item.id}`, {
        id: item.id,
        data: {
          status,
          watched_at: status === 'watched' ? new Date().toISOString() : null,
        },
      });

      await loadWatchlistItems(selectedWatchlistId);
      setBanner({
        type: 'success',
        message: `${item.title?.name || 'Title'} is now marked as ${watchStatusOptions.find((option) => option.value === status)?.label.toLowerCase()}.`,
      });
    } catch (error) {
      console.error('Failed to update watchlist item status:', error);
      setBanner({
        type: 'danger',
        message: 'We could not update this watch status. Please try again.',
      });
    } finally {
      setItemActionId('');
    }
  };

  const handleRemoveItem = async (item: WatchlistItemRecord) => {
    setItemActionId(item.id);

    try {
      await axios.delete(`/watchlist_items/${item.id}`);
      await loadWatchlistItems(selectedWatchlistId);

      if (selectedTitleSummary?.id === item.title?.id) {
        setSelectedTitleSummary(null);
      }

      setBanner({
        type: 'success',
        message: `${item.title?.name || 'Title'} was removed from this watchlist.`,
      });
    } catch (error) {
      console.error('Failed to remove watchlist item:', error);
      setBanner({
        type: 'danger',
        message: 'We could not remove this title. Please try again.',
      });
    } finally {
      setItemActionId('');
    }
  };

  const watchStats = useMemo(() => {
    return watchStatusOptions.map((option) => ({
      ...option,
      total: watchlistItems.filter((item) => item.status === option.value).length,
    }));
  }, [watchlistItems]);

  const selectedTitleAlreadySaved = useMemo(() => {
    if (!selectedTitleSummary?.id) return false;

    return watchlistItems.some((item) => item.title?.id === selectedTitleSummary.id);
  }, [selectedTitleSummary?.id, watchlistItems]);

  return (
    <>
      <Head>
        <title>{getPageTitle('Watch Hub')}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton icon={mdiPlayCircle} title='Watch Hub' main>
          <BaseButton href='/titles/titles-list' color='whiteDark' label='Full catalog' />
        </SectionTitleLineWithButton>

        {banner && (
          <NotificationBar color={banner.type === 'danger' ? 'danger' : banner.type === 'warning' ? 'warning' : banner.type === 'success' ? 'success' : 'info'}>
            {banner.message}
          </NotificationBar>
        )}

        <div className='mb-6 overflow-hidden rounded-3xl border border-white/10 bg-[#09090f] text-white shadow-2xl shadow-black/40'>
          <div className='grid gap-0 lg:grid-cols-[1.45fr_0.95fr]'>
            <div className='relative overflow-hidden px-6 py-8 sm:px-8 lg:px-10'>
              <div className='absolute inset-0 bg-[radial-gradient(circle_at_top_left,_rgba(99,102,241,0.28),_transparent_40%),radial-gradient(circle_at_bottom_right,_rgba(244,63,94,0.22),_transparent_34%)]' />
              <div className='relative'>
                <span className='mb-4 inline-flex items-center rounded-full border border-white/10 bg-white/5 px-4 py-1 text-xs font-semibold uppercase tracking-[0.22em] text-slate-200'>
                  Modern cinematic workflow
                </span>
                <h2 className='max-w-2xl text-3xl font-semibold leading-tight sm:text-4xl'>
                  Browse trending titles, save what matters, and turn scattered picks into a watch plan.
                </h2>
                <p className='mt-4 max-w-2xl text-sm leading-7 text-slate-300 sm:text-base'>
                  This first slice gives you a real consumer flow: discover a title, add it to your personal watchlist,
                  track its status, and inspect the details that help you decide what to watch next.
                </p>

                <div className='mt-6 flex flex-wrap gap-3'>
                  <Link
                    href='/watchlists/watchlists-list'
                    className='inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm font-medium text-white transition hover:bg-white/10'
                  >
                    Manage watchlists
                    <BaseIcon path={mdiOpenInNew} size={16} />
                  </Link>
                  <Link
                    href='/watchlist_items/watchlist_items-list'
                    className='inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm font-medium text-white transition hover:bg-white/10'
                  >
                    View saved items
                    <BaseIcon path={mdiOpenInNew} size={16} />
                  </Link>
                </div>
              </div>
            </div>

            <div className='grid gap-4 border-t border-white/10 bg-black/30 p-6 sm:grid-cols-2 lg:grid-cols-1 lg:border-l lg:border-t-0'>
              {watchStats.map((stat) => (
                <div key={stat.value} className='rounded-2xl border border-white/10 bg-white/5 p-4'>
                  <div className='text-xs uppercase tracking-[0.18em] text-slate-400'>{stat.label}</div>
                  <div className='mt-3 flex items-end justify-between'>
                    <span className='text-3xl font-semibold text-white'>{stat.total}</span>
                    <span className={`rounded-full px-3 py-1 text-xs font-medium ${stat.tone}`}>status</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className='mb-6 grid gap-6 xl:grid-cols-12'>
          <div className='xl:col-span-7'>
            <CardBox className='border border-white/10 bg-[#11131c] text-white shadow-xl shadow-black/20'>
              <div className='mb-6 flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between'>
                <div>
                  <h3 className='text-xl font-semibold'>Discover titles</h3>
                  <p className='mt-2 text-sm text-slate-300'>
                    Search the seeded catalog, explore trending picks, and save a title into your next-up queue.
                  </p>
                </div>
                <div className='flex flex-wrap gap-2'>
                  {typeFilters.map((filter) => (
                    <button
                      key={filter.value}
                      type='button'
                      onClick={() => setCatalogType(filter.value)}
                      className={`rounded-full border px-4 py-2 text-sm transition ${
                        catalogType === filter.value
                          ? 'border-violet-400 bg-violet-500/15 text-white'
                          : 'border-white/10 bg-white/5 text-slate-300 hover:bg-white/10'
                      }`}
                    >
                      {filter.label}
                    </button>
                  ))}
                </div>
              </div>

              <div className='mb-6 flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3'>
                <BaseIcon path={mdiMagnify} className='text-slate-400' />
                <input
                  value={catalogQuery}
                  onChange={(event) => setCatalogQuery(event.target.value)}
                  placeholder='Search by title name or vibe...'
                  className='w-full border-0 bg-transparent text-sm text-white outline-none placeholder:text-slate-500'
                />
              </div>

              <div className='grid gap-3 md:grid-cols-2'>
                {catalogLoading &&
                  Array.from({ length: 4 }).map((_, index) => (
                    <div key={index} className='animate-pulse rounded-3xl border border-white/10 bg-white/5 p-5'>
                      <div className='h-4 w-20 rounded bg-white/10' />
                      <div className='mt-4 h-6 w-2/3 rounded bg-white/10' />
                      <div className='mt-3 h-16 rounded bg-white/10' />
                    </div>
                  ))}

                {!catalogLoading &&
                  catalog.map((title) => {
                    const isSaved = watchlistItems.some((item) => item.title?.id === title.id);

                    return (
                      <button
                        key={title.id}
                        type='button'
                        onClick={() => setSelectedTitleSummary(title)}
                        className='group overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(145deg,rgba(15,23,42,0.95),rgba(88,28,135,0.2))] p-5 text-left transition hover:-translate-y-1 hover:border-violet-400/40 hover:shadow-xl hover:shadow-violet-950/40'
                      >
                        <div className='flex items-start justify-between gap-3'>
                          <div>
                            <span className='inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs font-medium uppercase tracking-[0.18em] text-slate-300'>
                              <BaseIcon path={getTypeIcon(title.title_type)} size={14} />
                              {getTypeLabel(title.title_type)}
                            </span>
                            <h4 className='mt-4 text-xl font-semibold text-white'>{title.name}</h4>
                            <p className='mt-2 line-clamp-2 text-sm leading-6 text-slate-300'>
                              {title.tagline || title.overview || 'No synopsis yet — open the detail panel for more context.'}
                            </p>
                          </div>
                          {title.is_trending && (
                            <span className='inline-flex items-center gap-1 rounded-full bg-rose-500/15 px-3 py-1 text-xs font-medium text-rose-200'>
                              <BaseIcon path={mdiFire} size={14} />
                              Trending
                            </span>
                          )}
                        </div>

                        <div className='mt-5 grid grid-cols-3 gap-3 text-sm text-slate-300'>
                          <div className='rounded-2xl border border-white/10 bg-black/20 p-3'>
                            <div className='text-[11px] uppercase tracking-[0.18em] text-slate-500'>Release</div>
                            <div className='mt-2 font-medium text-white'>{getReleaseLabel(title)}</div>
                          </div>
                          <div className='rounded-2xl border border-white/10 bg-black/20 p-3'>
                            <div className='text-[11px] uppercase tracking-[0.18em] text-slate-500'>Rating</div>
                            <div className='mt-2 flex items-center gap-1 font-medium text-white'>
                              <BaseIcon path={mdiStarOutline} size={15} className='text-amber-300' />
                              {Number(title.average_rating || 0).toFixed(1)}
                            </div>
                          </div>
                          <div className='rounded-2xl border border-white/10 bg-black/20 p-3'>
                            <div className='text-[11px] uppercase tracking-[0.18em] text-slate-500'>Length</div>
                            <div className='mt-2 font-medium text-white'>
                              {title.title_type === 'tv_show'
                                ? `${title.number_of_seasons || 0} season${title.number_of_seasons === 1 ? '' : 's'}`
                                : `${title.runtime_minutes || 0} min`}
                            </div>
                          </div>
                        </div>

                        <div className='mt-5 flex flex-wrap items-center gap-3'>
                          <span
                            className={`rounded-full px-3 py-1 text-xs font-medium ${
                              isSaved
                                ? 'bg-emerald-500/15 text-emerald-200'
                                : 'bg-white/5 text-slate-300'
                            }`}
                          >
                            {isSaved ? 'Already saved' : 'Ready to save'}
                          </span>
                          <BaseButton
                            color={isSaved ? 'success' : 'info'}
                            small
                            icon={mdiBookmarkOutline}
                            label={isSaved ? 'Saved' : actionTitleId === title.id ? 'Saving...' : 'Add to watchlist'}
                            disabled={actionTitleId === title.id}
                            onClick={(event) => {
                              event.stopPropagation();
                              handleAddToWatchlist(title);
                            }}
                          />
                        </div>
                      </button>
                    );
                  })}
              </div>

              {!catalogLoading && !catalog.length && (
                <div className='rounded-3xl border border-dashed border-white/10 bg-black/20 px-6 py-10 text-center'>
                  <p className='text-lg font-medium text-white'>No titles matched your search.</p>
                  <p className='mt-2 text-sm text-slate-400'>Try a different keyword or switch back to all titles.</p>
                </div>
              )}
            </CardBox>

            <div className='mt-6 grid gap-6 lg:grid-cols-2'>
              <CardBox className='border border-white/10 bg-[#11131c] text-white'>
                <div className='mb-4 flex items-center justify-between'>
                  <div>
                    <h3 className='text-lg font-semibold'>Trending now</h3>
                    <p className='mt-1 text-sm text-slate-400'>Fast picks pulled from titles flagged as trending.</p>
                  </div>
                  <BaseIcon path={mdiFire} className='text-rose-300' />
                </div>
                <div className='space-y-3'>
                  {highlightTrending.map((title) => (
                    <button
                      key={title.id}
                      type='button'
                      onClick={() => setSelectedTitleSummary(title)}
                      className='flex w-full items-center justify-between rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-left transition hover:bg-white/5'
                    >
                      <div>
                        <div className='font-medium text-white'>{title.name}</div>
                        <div className='mt-1 text-xs uppercase tracking-[0.18em] text-slate-500'>
                          {getTypeLabel(title.title_type)}
                        </div>
                      </div>
                      <span className='text-sm text-slate-300'>{Number(title.popularity_score || 0).toFixed(0)}</span>
                    </button>
                  ))}
                  {!highlightTrending.length && <p className='text-sm text-slate-400'>Trending titles will appear here once loaded.</p>}
                </div>
              </CardBox>

              <CardBox className='border border-white/10 bg-[#11131c] text-white'>
                <div className='mb-4 flex items-center justify-between'>
                  <div>
                    <h3 className='text-lg font-semibold'>Recommended tonight</h3>
                    <p className='mt-1 text-sm text-slate-400'>Top-rated options for when you want a reliable pick.</p>
                  </div>
                  <BaseIcon path={mdiStarOutline} className='text-amber-300' />
                </div>
                <div className='space-y-3'>
                  {highlightRecommended.map((title) => (
                    <button
                      key={title.id}
                      type='button'
                      onClick={() => setSelectedTitleSummary(title)}
                      className='flex w-full items-center justify-between rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-left transition hover:bg-white/5'
                    >
                      <div>
                        <div className='font-medium text-white'>{title.name}</div>
                        <div className='mt-1 text-xs uppercase tracking-[0.18em] text-slate-500'>
                          {getTypeLabel(title.title_type)}
                        </div>
                      </div>
                      <span className='inline-flex items-center gap-1 text-sm text-white'>
                        <BaseIcon path={mdiStarOutline} size={14} className='text-amber-300' />
                        {Number(title.average_rating || 0).toFixed(1)}
                      </span>
                    </button>
                  ))}
                  {!highlightRecommended.length && <p className='text-sm text-slate-400'>Recommendations will appear here once loaded.</p>}
                </div>
              </CardBox>
            </div>
          </div>

          <div className='space-y-6 xl:col-span-5'>
            <CardBox className='border border-white/10 bg-[#11131c] text-white shadow-xl shadow-black/20'>
              <div className='mb-5 flex items-center justify-between'>
                <div>
                  <h3 className='text-xl font-semibold'>My watchlist</h3>
                  <p className='mt-2 text-sm text-slate-300'>Create a personal queue, then move titles from plan to watched.</p>
                </div>
                <BaseButton href='/watchlists/watchlists-new' color='whiteDark' label='Advanced form' small />
              </div>

              <form onSubmit={handleCreateWatchlist} className='rounded-3xl border border-white/10 bg-black/20 p-4'>
                <div className='grid gap-3'>
                  <div>
                    <label htmlFor='watchlist-name' className='mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-400'>
                      Watchlist name
                    </label>
                    <input
                      id='watchlist-name'
                      value={watchlistForm.name}
                      onChange={(event) => setWatchlistForm((current) => ({ ...current, name: event.target.value }))}
                      className='w-full rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white outline-none transition focus:border-violet-400'
                    />
                  </div>
                  <div>
                    <label htmlFor='watchlist-description' className='mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-400'>
                      Description
                    </label>
                    <textarea
                      id='watchlist-description'
                      rows={3}
                      value={watchlistForm.description}
                      onChange={(event) =>
                        setWatchlistForm((current) => ({ ...current, description: event.target.value }))
                      }
                      className='w-full rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white outline-none transition focus:border-violet-400'
                    />
                  </div>
                  <BaseButton
                    type='submit'
                    color='info'
                    icon={mdiBookmarkOutline}
                    label={createLoading ? 'Creating...' : 'Create watchlist'}
                    disabled={createLoading}
                    className='justify-center'
                  />
                </div>
              </form>

              <div className='mt-5'>
                <div className='mb-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-400'>Your watchlists</div>
                <div className='grid gap-3'>
                  {watchlistsLoading && <p className='text-sm text-slate-400'>Loading your watchlists...</p>}
                  {!watchlistsLoading && !watchlists.length && (
                    <div className='rounded-2xl border border-dashed border-white/10 bg-black/20 px-4 py-5 text-sm text-slate-400'>
                      You have not created a watchlist yet. Start with one above, then save your first title.
                    </div>
                  )}
                  {watchlists.map((watchlist) => (
                    <button
                      key={watchlist.id}
                      type='button'
                      onClick={() => setSelectedWatchlistId(watchlist.id)}
                      className={`rounded-2xl border px-4 py-3 text-left transition ${
                        selectedWatchlistId === watchlist.id
                          ? 'border-violet-400 bg-violet-500/10'
                          : 'border-white/10 bg-black/20 hover:bg-white/5'
                      }`}
                    >
                      <div className='font-medium text-white'>{watchlist.name}</div>
                      <div className='mt-1 text-sm text-slate-400'>{watchlist.description || 'No description yet.'}</div>
                    </button>
                  ))}
                </div>
              </div>

              <div className='mt-6 space-y-4'>
                <div className='flex items-center justify-between'>
                  <h4 className='text-lg font-semibold text-white'>Saved titles</h4>
                  {selectedWatchlist && (
                    <span className='rounded-full bg-white/5 px-3 py-1 text-xs font-medium text-slate-300'>
                      {selectedWatchlist.name}
                    </span>
                  )}
                </div>

                {watchlistItemsLoading && <p className='text-sm text-slate-400'>Loading titles in this watchlist...</p>}

                {!watchlistItemsLoading && selectedWatchlistId && !watchlistItems.length && (
                  <div className='rounded-2xl border border-dashed border-white/10 bg-black/20 px-4 py-6 text-sm text-slate-400'>
                    No saved titles yet. Add one from the discovery cards to start tracking progress.
                  </div>
                )}

                <div className='space-y-3'>
                  {watchlistItems.map((item) => {
                    const statusTone = watchStatusOptions.find((option) => option.value === item.status)?.tone || '';

                    return (
                      <div
                        key={item.id}
                        className='rounded-3xl border border-white/10 bg-black/20 p-4 transition hover:border-white/20'
                      >
                        <div className='flex items-start justify-between gap-3'>
                          <button type='button' onClick={() => setSelectedTitleSummary(item.title || null)} className='text-left'>
                            <div className='text-base font-semibold text-white'>{item.title?.name || 'Untitled'}</div>
                            <div className='mt-1 text-sm text-slate-400'>
                              {item.title ? getReleaseLabel(item.title) : 'No release date'}
                            </div>
                          </button>
                          <span className={`rounded-full px-3 py-1 text-xs font-medium ${statusTone}`}>
                            {watchStatusOptions.find((option) => option.value === item.status)?.label || 'Unknown'}
                          </span>
                        </div>

                        <div className='mt-4 flex flex-wrap gap-2'>
                          {watchStatusOptions.map((option) => (
                            <button
                              key={option.value}
                              type='button'
                              disabled={itemActionId === item.id}
                              onClick={() => handleStatusChange(item, option.value)}
                              className={`rounded-full px-3 py-1 text-xs font-medium transition ${
                                item.status === option.value
                                  ? option.tone
                                  : 'border border-white/10 bg-white/5 text-slate-300 hover:bg-white/10'
                              }`}
                            >
                              {option.label}
                            </button>
                          ))}
                        </div>

                        <div className='mt-4 flex items-center justify-between'>
                          <div className='text-xs uppercase tracking-[0.18em] text-slate-500'>
                            {item.watched_at ? `Finished ${formatDate(item.watched_at)}` : 'Not finished yet'}
                          </div>
                          <button
                            type='button'
                            disabled={itemActionId === item.id}
                            onClick={() => handleRemoveItem(item)}
                            className='text-sm font-medium text-rose-200 transition hover:text-rose-100'
                          >
                            {itemActionId === item.id ? 'Updating...' : 'Remove'}
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </CardBox>

            <CardBox className='border border-white/10 bg-[#11131c] text-white shadow-xl shadow-black/20'>
              <div className='mb-4 flex items-center justify-between'>
                <div>
                  <h3 className='text-xl font-semibold'>Title detail</h3>
                  <p className='mt-2 text-sm text-slate-300'>Select a title to inspect its synopsis, cast, genres, and trailer links.</p>
                </div>
                {selectedTitleSummary && (
                  <BaseButton
                    color={selectedTitleAlreadySaved ? 'success' : 'info'}
                    icon={selectedTitleAlreadySaved ? mdiCheckCircleOutline : mdiBookmarkOutline}
                    label={selectedTitleAlreadySaved ? 'Saved' : 'Save'}
                    disabled={selectedTitleAlreadySaved || actionTitleId === selectedTitleSummary.id}
                    onClick={() => handleAddToWatchlist(selectedTitleSummary)}
                  />
                )}
              </div>

              {!selectedTitleSummary && (
                <div className='rounded-3xl border border-dashed border-white/10 bg-black/20 px-5 py-10 text-center'>
                  <div className='mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-white/5'>
                    <BaseIcon path={mdiPlayCircle} className='text-violet-200' />
                  </div>
                  <p className='text-lg font-medium text-white'>Choose a title from the catalog.</p>
                  <p className='mt-2 text-sm text-slate-400'>We will show the key details here so you can decide whether it belongs in your queue.</p>
                </div>
              )}

              {selectedTitleSummary && detailLoading && (
                <div className='space-y-4'>
                  <div className='h-8 w-1/2 animate-pulse rounded bg-white/10' />
                  <div className='h-24 animate-pulse rounded bg-white/10' />
                  <div className='h-16 animate-pulse rounded bg-white/10' />
                </div>
              )}

              {selectedTitleDetails && !detailLoading && (
                <div>
                  <div className='rounded-3xl border border-white/10 bg-[linear-gradient(145deg,rgba(15,23,42,0.95),rgba(124,58,237,0.18))] p-5'>
                    <div className='flex items-start justify-between gap-4'>
                      <div>
                        <span className='inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs font-medium uppercase tracking-[0.18em] text-slate-300'>
                          <BaseIcon path={getTypeIcon(selectedTitleDetails.title_type)} size={14} />
                          {getTypeLabel(selectedTitleDetails.title_type)}
                        </span>
                        <h4 className='mt-4 text-2xl font-semibold text-white'>{selectedTitleDetails.name}</h4>
                        <p className='mt-2 text-sm text-violet-100'>{selectedTitleDetails.tagline || 'No tagline available yet.'}</p>
                      </div>
                      {selectedTitleDetails.is_trending && (
                        <span className='rounded-full bg-rose-500/15 px-3 py-1 text-xs font-medium text-rose-200'>Hot right now</span>
                      )}
                    </div>

                    <div className='mt-5 grid gap-3 sm:grid-cols-3'>
                      <div className='rounded-2xl border border-white/10 bg-black/20 p-3'>
                        <div className='text-[11px] uppercase tracking-[0.18em] text-slate-500'>Release</div>
                        <div className='mt-2 font-medium text-white'>{getReleaseLabel(selectedTitleDetails)}</div>
                      </div>
                      <div className='rounded-2xl border border-white/10 bg-black/20 p-3'>
                        <div className='text-[11px] uppercase tracking-[0.18em] text-slate-500'>Rating</div>
                        <div className='mt-2 font-medium text-white'>{Number(selectedTitleDetails.average_rating || 0).toFixed(1)}</div>
                      </div>
                      <div className='rounded-2xl border border-white/10 bg-black/20 p-3'>
                        <div className='text-[11px] uppercase tracking-[0.18em] text-slate-500'>Runtime</div>
                        <div className='mt-2 flex items-center gap-2 font-medium text-white'>
                          <BaseIcon path={mdiClockOutline} size={14} className='text-slate-400' />
                          {selectedTitleDetails.title_type === 'tv_show'
                            ? `${selectedTitleDetails.number_of_seasons || 0} seasons`
                            : `${selectedTitleDetails.runtime_minutes || 0} min`}
                        </div>
                      </div>
                    </div>
                  </div>

                  <div className='mt-5 space-y-5'>
                    <div>
                      <h5 className='text-sm font-semibold uppercase tracking-[0.18em] text-slate-400'>Overview</h5>
                      <p className='mt-3 text-sm leading-7 text-slate-300'>
                        {selectedTitleDetails.overview || 'No overview available yet.'}
                      </p>
                    </div>

                    <div className='grid gap-4 sm:grid-cols-2'>
                      <div>
                        <h5 className='text-sm font-semibold uppercase tracking-[0.18em] text-slate-400'>Genres</h5>
                        <div className='mt-3 flex flex-wrap gap-2'>
                          {selectedTitleDetails.genres.length ? (
                            selectedTitleDetails.genres.map((genre) => (
                              <span key={genre} className='rounded-full bg-white/5 px-3 py-1 text-sm text-slate-200'>
                                {genre}
                              </span>
                            ))
                          ) : (
                            <span className='text-sm text-slate-400'>No genres linked yet.</span>
                          )}
                        </div>
                      </div>
                      <div>
                        <h5 className='text-sm font-semibold uppercase tracking-[0.18em] text-slate-400'>Cast</h5>
                        <div className='mt-3 flex flex-wrap gap-2'>
                          {selectedTitleDetails.cast.length ? (
                            selectedTitleDetails.cast.map((person) => (
                              <span key={person} className='rounded-full bg-white/5 px-3 py-1 text-sm text-slate-200'>
                                {person}
                              </span>
                            ))
                          ) : (
                            <span className='text-sm text-slate-400'>No cast linked yet.</span>
                          )}
                        </div>
                      </div>
                    </div>

                    <div>
                      <h5 className='text-sm font-semibold uppercase tracking-[0.18em] text-slate-400'>Crew highlights</h5>
                      <div className='mt-3 flex flex-wrap gap-2'>
                        {selectedTitleDetails.crew.length ? (
                          selectedTitleDetails.crew.map((person) => (
                            <span key={person} className='rounded-full bg-white/5 px-3 py-1 text-sm text-slate-200'>
                              {person}
                            </span>
                          ))
                        ) : (
                          <span className='text-sm text-slate-400'>No crew members linked yet.</span>
                        )}
                      </div>
                    </div>

                    <div>
                      <h5 className='text-sm font-semibold uppercase tracking-[0.18em] text-slate-400'>Trailers & clips</h5>
                      <div className='mt-3 space-y-2'>
                        {selectedTitleDetails.videos.length ? (
                          selectedTitleDetails.videos.map((video) => (
                            <a
                              key={video.id}
                              href={video.video_url || '#'}
                              target='_blank'
                              rel='noreferrer'
                              className='flex items-center justify-between rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200 transition hover:bg-white/5'
                            >
                              <span>{video.name}</span>
                              <span className='text-xs uppercase tracking-[0.18em] text-slate-500'>{video.site || 'external'}</span>
                            </a>
                          ))
                        ) : (
                          <div className='rounded-2xl border border-dashed border-white/10 bg-black/20 px-4 py-4 text-sm text-slate-400'>
                            No trailer links have been added yet.
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </CardBox>
          </div>
        </div>
      </SectionMain>
    </>
  );
}

WatchHub.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};
