import { useState, useMemo } from 'react';
import { Card, Pagination, Chip } from '@idds/react';
import {
  articles,
  categoryOptions,
  type ArticleCategory,
} from '../data/articlesData';
import ArticleDetail from './ArticleDetail';

export default function Articles() {
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(12); // Fixed 12 items per page
  const [selectedCategory, setSelectedCategory] =
    useState<ArticleCategory>('Semua');
  const [selectedArticleId, setSelectedArticleId] = useState<string | null>(
    null,
  );

  // Filter articles by category
  const filteredArticles = useMemo(() => {
    if (selectedCategory === 'Semua') {
      return articles;
    }
    return articles.filter((article) => article.category === selectedCategory);
  }, [selectedCategory]);

  // Calculate pagination
  const totalPages = Math.ceil(filteredArticles.length / pageSize);
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const currentArticles = useMemo(
    () => filteredArticles.slice(startIndex, endIndex),
    [filteredArticles, startIndex, endIndex],
  );

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleCategoryChange = (category: string) => {
    setSelectedCategory(category as ArticleCategory);
    setCurrentPage(1); // Reset to first page when category changes
  };

  const handlePageSizeChange = (newPageSize: number) => {
    setPageSize(newPageSize);
    setCurrentPage(1); // Reset to first page when page size changes
  };

  const handleArticleClick = (articleId: string) => {
    setSelectedArticleId(articleId);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleBack = () => {
    setSelectedArticleId(null);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  if (selectedArticleId) {
    return <ArticleDetail articleId={selectedArticleId} onBack={handleBack} />;
  }

  return (
    <div className="pb-8">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-xl md:text-2xl font-semibold text-content-primary">
          Artikel
        </h1>
        <p className="text-sm md:text-base text-content-secondary mb-6">
          Kelola dan jelajahi artikel sebagai sumber informasi resmi INAgov.
        </p>

        {/* Category Filter */}
        <div className="mb-6">
          <Chip
            options={categoryOptions}
            selected={selectedCategory}
            onSelect={handleCategoryChange}
            showCustomization={false}
            variant="outline"
            size="medium"
          />
        </div>
      </div>

      {/* Articles Grid - 3 columns on desktop */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 sm:gap-10 mb-6 md:mb-8 justify-items-center sm:justify-items-start">
        {currentArticles.map((article) => (
          <div
            key={article.id}
            onClick={() => handleArticleClick(article.id)}
            className="cursor-pointer w-full h-[330px] [&_.ina-card]:w-full [&_.ina-card]:h-full"
          >
            <Card
              variant="basic"
              mediaPosition="top"
              title={
                <span className="text-base md:text-lg font-semibold text-content-secondary line-clamp-1">
                  {article.title}
                </span>
              }
              description={
                <span className="text-sm md:text-base text-content-secondary line-clamp-2">
                  {article.excerpt}
                </span>
              }
              mediaSrc={article.mediaSrc}
              mediaAlt={article.title}
              clickable={true}
              hoverable={true}
            />
          </div>
        ))}
      </div>

      {/* Pagination */}
      {totalPages > 0 && (
        <div className="mt-6 md:mt-8">
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            pageSize={pageSize}
            pageSizeOptions={[12]}
            onPageChange={handlePageChange}
            onPageSizeChange={handlePageSizeChange}
            fullWidth={true}
          />
        </div>
      )}
    </div>
  );
}
