// Import ========================================================================================================================
import App from '@/layouts/aia/app-layout';
import Button from '@/components/button';
import PageMeta from '@/components/aia/page-meta';
import EventCard from '@/components/aia/event-card';
import SearchBar from '@/components/aia/search-bar';
import { useState, useEffect } from 'react';
import { router } from '@inertiajs/react';

type Post = {
  id: number;
  title: string;
  slug: string;
  excerpt: string;
  content: string;
  image_url: string;
  post_type: string;
  status: string;
  published_at: string;
  date: string;
  time?: string;
  address?: string;
  description?: string;
  link?: string;
  categories: Array<{
    id: number;
    name: string;
    slug: string;
  }>;
};

type NewsProps = {
  posts: Post[];
  pagination: {
    total: number;
    per_page: number;
    current_page: number;
    last_page: number;
    from: number;
    to: number;
  };
  filters: {
    search: string;
    type: string;
  };
};

export default function News({ posts, pagination, filters }: NewsProps) {
  const [newsFilterType, setNewsFilterType] = useState<string>(
    filters.type === 'all' ? 'All' : filters.type.charAt(0).toUpperCase() + filters.type.slice(1)
  );
  const [searchData, setSearchData] = useState<string>(filters.search || '');
  const [allPosts, setAllPosts] = useState<Post[]>(posts);
  const [isLoadingMore, setIsLoadingMore] = useState(false);

  // 當 posts 變更時更新 allPosts（搜索/篩選時重置，加載更多時累加）
  useEffect(() => {
    if (isLoadingMore) {
      // 加載更多：累加文章
      setAllPosts(prev => [...prev, ...posts]);
      setIsLoadingMore(false);
    } else {
      // 搜索/篩選：重置文章
      setAllPosts(posts);
    }
  }, [posts]);

  // 將 Post 數據轉換為 EventCard 格式
  const eventCards = allPosts.map((post: Post) => {
    const detailRoute = post.post_type === 'event' ? 'event.show' : 'news.show';
    return {
      eventCardTitle: post.title,
      eventCardType: post.post_type,
      eventCardDate: post.date,
      eventCardLocation: post.address || '',
      eventCardImage: post.image_url,
      eventCardLink: route(detailRoute, { post: post.slug }),
      eventCardLinkText: "for more information",
    };
  });

  // 處理篩選類型變更
  useEffect(() => {
    const typeParam = newsFilterType === 'All' ? 'all' : newsFilterType.toLowerCase();
    setIsLoadingMore(false);
    router.get(route('news'), {
      type: typeParam,
      search: searchData,
    }, {
      preserveState: true,
      preserveScroll: true,
    });
  }, [newsFilterType]);

  // 處理搜尋變更
  useEffect(() => {
    const timer = setTimeout(() => {
      const typeParam = newsFilterType === 'All' ? 'all' : newsFilterType.toLowerCase();
      setIsLoadingMore(false);
      router.get(route('news'), {
        type: typeParam,
        search: searchData,
      }, {
        preserveState: true,
        preserveScroll: true,
      });
    }, 500); // 500ms 延遲防抖

    return () => clearTimeout(timer);
  }, [searchData]);

  // 載入更多
  const loadMore = () => {
    const typeParam = newsFilterType === 'All' ? 'all' : newsFilterType.toLowerCase();
    setIsLoadingMore(true);
    router.get(route('news'), {
      type: typeParam,
      search: searchData,
      page: pagination.current_page + 1,
    }, {
      preserveState: true,
      preserveScroll: true,
      only: ['posts', 'pagination'],
    });
  };


  return (
    <App
      pageMeta={
        <PageMeta
          title="News"
          tabClicked={newsFilterType}
          onTabClick={setNewsFilterType}
          tabType="button"
          searchBar={
            <SearchBar
              newsFilterType={newsFilterType}
              searchData={searchData}
              setSearchData={setSearchData}
              resultNum={pagination.total}
            />
          }
          tabs={[
            { name: 'All', href: '#' },
            { name: 'News', href: '#' },
            { name: 'Event', href: '#' },
          ]}
        />
      }
      mainClass='pageContent'
    >
      <div className='container'>
        <div className='grid grid-cols-1 gap-24 md:grid-cols-2 md:gap-20 lg:grid-cols-4'>
          {eventCards.map((card, index) => (
            <EventCard
              key={index}
              darkBackground={false}
              eventCardTitle={card.eventCardTitle}
              eventCardType={card.eventCardType}
              eventCardDate={card.eventCardDate}
              eventCardLocation={card.eventCardLocation}
              eventCardImage={card.eventCardImage}
              eventCardLink={card.eventCardLink}
              eventCardLinkText={card.eventCardLinkText}
            />
          ))}
        </div>
        {pagination.current_page < pagination.last_page && (
          <div className='w-full flex justify-center pt-32'>
            <Button
              type="button button--ghost"
              as="button"
              disabled={false}
              buttonType="button"
              label="Show more"
              onClick={loadMore}
            />
          </div>
        )}
      </div>
    </App>
  );
}
