'use client';

/**
 * FAQ 목록 컴포넌트
 *
 * 디자인 스펙:
 * - 페이지 타이틀: FAQ
 * - 페이지 설명: FAQ를 확인합니다.
 * - 탭: 전체, 카테고리 (필터링)
 * - 검색창
 * - 아코디언 형태 FAQ 목록 (Q. 질문 / A. 답변)
 */

import { useState, useMemo, useEffect } from 'react';
import { HelpCircle, ChevronDown, Search } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { PageLayout } from '@/components/organisms/PageLayout';
import { cn } from '@/lib/utils';
import { type FAQ, FAQ_CATEGORIES, transformPostToFAQ } from './types';
import { getPosts } from '../shared/actions';

export function FAQList() {
  // ===== 상태 관리 =====
  const [faqs, setFaqs] = useState<FAQ[]>([]);
  const [, setIsLoading] = useState(true);
  const [, setError] = useState<string | null>(null);

  // ===== API 데이터 로드 =====
  useEffect(() => {
    async function fetchFaqs() {
      setIsLoading(true);
      setError(null);

      const result = await getPosts('faq', { per_page: 100 });

      if (result.success && result.data) {
        const transformed = result.data.data.map(transformPostToFAQ);
        setFaqs(transformed);
      } else {
        setError(result.error || 'FAQ를 불러오는데 실패했습니다.');
      }

      setIsLoading(false);
    }

    fetchFaqs();
  }, []);
  const [searchValue, setSearchValue] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [expandedId, setExpandedId] = useState<string | null>(null);

  // ===== 필터링된 데이터 =====
  const filteredData = useMemo(() => {
    let result = [...faqs];

    // 카테고리 필터
    if (selectedCategory !== 'all') {
      result = result.filter((item) => item.category === selectedCategory);
    }

    // 검색 필터
    if (searchValue) {
      const searchLower = searchValue.toLowerCase();
      result = result.filter(
        (item) =>
          item.question.toLowerCase().includes(searchLower) ||
          item.answer.toLowerCase().includes(searchLower)
      );
    }

    return result;
  }, [faqs, searchValue, selectedCategory]);

  // ===== 핸들러 =====
  const handleToggle = (id: string) => {
    setExpandedId((prev) => (prev === id ? null : id));
  };

  return (
    <PageLayout>
      <div className="space-y-6">
        {/* 헤더 */}
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
            <HelpCircle className="h-5 w-5 text-primary" />
          </div>
          <div>
            <h1 className="text-2xl font-bold">FAQ</h1>
            <p className="text-sm text-muted-foreground">FAQ를 확인합니다.</p>
          </div>
        </div>

        {/* 탭 */}
        <Tabs value={selectedCategory} onValueChange={setSelectedCategory}>
          <TabsList className="flex-wrap h-auto gap-1">
            {FAQ_CATEGORIES.map((category) => (
              <TabsTrigger
                key={category.id}
                value={category.id}
                className="px-4 py-2"
              >
                {category.name}
              </TabsTrigger>
            ))}
          </TabsList>
        </Tabs>

        {/* 검색창 */}
        <div className="relative max-w-md">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="검색어를 입력하세요"
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            className="pl-10"
          />
        </div>

        {/* FAQ 목록 (아코디언) */}
        <div className="space-y-2">
          {filteredData.length === 0 ? (
            <div className="py-12 text-center text-muted-foreground">
              검색 결과가 없습니다.
            </div>
          ) : (
            filteredData.map((faq) => (
              <div
                key={faq.id}
                className="border rounded-lg overflow-hidden"
              >
                {/* 질문 (헤더) */}
                <button
                  onClick={() => handleToggle(faq.id)}
                  className={cn(
                    'w-full flex items-center justify-between p-4 text-left hover:bg-muted/50 transition-colors',
                    expandedId === faq.id && 'bg-muted/50'
                  )}
                >
                  <div className="flex items-start gap-3">
                    <span className="text-primary font-bold shrink-0">Q.</span>
                    <span className="font-medium">{faq.question}</span>
                  </div>
                  <ChevronDown
                    className={cn(
                      'h-5 w-5 text-muted-foreground transition-transform shrink-0',
                      expandedId === faq.id && 'rotate-180'
                    )}
                  />
                </button>

                {/* 답변 (본문) */}
                {expandedId === faq.id && (
                  <div className="p-4 pt-0 border-t bg-muted/30">
                    <div className="flex items-start gap-3 pt-4">
                      <span className="text-blue-600 font-bold shrink-0">A.</span>
                      <p className="text-muted-foreground leading-relaxed">
                        {faq.answer}
                      </p>
                    </div>
                  </div>
                )}
              </div>
            ))
          )}
        </div>
      </div>
    </PageLayout>
  );
}

export default FAQList;