import React, { useState, useMemo } from "react";
import { clsx } from "clsx";

interface FaqItem {
  id: string;
  question: string;
  answer: string;
  category: string;
  tags: string[];
  helpful?: number;
  notHelpful?: number;
  lastUpdated?: string;
  featured?: boolean;
}

interface PlusFaqProps {
  title?: string;
  description?: string;
  faqItems?: FaqItem[];
  categories?: string[];
  showSearch?: boolean;
  showCategories?: boolean;
  showVoting?: boolean;
  showLastUpdated?: boolean;
  showFeatured?: boolean;
  maxItemsPerCategory?: number;
  className?: string;
  theme?: {
    primaryColor?: string;
    secondaryColor?: string;
    accentColor?: string;
    fontFamily?: string;
  };
}

const defaultFaqItems: FaqItem[] = [
  {
    id: "1",
    question: "AgentC란 무엇인가요?",
    answer:
      "AgentC는 비즈니스 자동화와 고객 관리를 위한 종합적인 SaaS 플랫폼입니다. AI 기반 챗봇, 워크플로우 자동화, CRM, 분석 도구 등을 제공하여 비즈니스 효율성을 극대화합니다.",
    category: "기본 정보",
    tags: ["소개", "플랫폼", "기능"],
    helpful: 45,
    notHelpful: 3,
    lastUpdated: "2024-01-15",
    featured: true,
  },
  {
    id: "2",
    question: "무료 체험 기간은 얼마나 되나요?",
    answer:
      "모든 요금제에서 14-30일의 무료 체험을 제공합니다. 체험 기간 동안 모든 기능을 제한 없이 사용하실 수 있으며, 신용카드 등록 없이도 시작할 수 있습니다.",
    category: "요금제",
    tags: ["무료체험", "결제", "기간"],
    helpful: 38,
    notHelpful: 2,
    lastUpdated: "2024-01-10",
    featured: true,
  },
  {
    id: "3",
    question: "데이터는 안전하게 보호되나요?",
    answer:
      "네, 저희는 엔터프라이즈급 보안을 제공합니다. 모든 데이터는 AES-256으로 암호화되며, ISO 27001, SOC 2 Type II 인증을 획득했습니다. 또한 GDPR 및 국내 개인정보보호법을 완전히 준수합니다.",
    category: "보안",
    tags: ["보안", "암호화", "개인정보보호"],
    helpful: 52,
    notHelpful: 1,
    lastUpdated: "2024-01-08",
  },
  {
    id: "4",
    question: "API 연동이 가능한가요?",
    answer:
      "네, RESTful API와 GraphQL API를 모두 제공합니다. 개발자 친화적인 문서와 SDK를 제공하며, 웹훅을 통한 실시간 데이터 동기화도 지원합니다.",
    category: "기술",
    tags: ["API", "개발", "연동"],
    helpful: 29,
    notHelpful: 4,
    lastUpdated: "2024-01-12",
  },
  {
    id: "5",
    question: "팀원을 초대할 수 있나요?",
    answer:
      "Professional 이상 요금제에서 팀 협업 기능을 제공합니다. 역할 기반 권한 관리, 팀 대시보드, 실시간 협업 도구 등을 사용하실 수 있습니다.",
    category: "팀 관리",
    tags: ["팀", "협업", "권한"],
    helpful: 33,
    notHelpful: 2,
    lastUpdated: "2024-01-14",
  },
  {
    id: "6",
    question: "고객 지원은 어떻게 받을 수 있나요?",
    answer:
      "이메일, 라이브 채팅, 전화 지원을 제공합니다. Enterprise 고객에게는 전담 계정 매니저와 24/7 우선 지원을 제공합니다. 또한 상세한 문서와 튜토리얼을 온라인으로 제공합니다.",
    category: "고객 지원",
    tags: ["지원", "문의", "서비스"],
    helpful: 41,
    notHelpful: 1,
    lastUpdated: "2024-01-11",
  },
  {
    id: "7",
    question: "요금제 변경은 언제든 가능한가요?",
    answer:
      "네, 언제든지 요금제를 업그레이드하거나 다운그레이드할 수 있습니다. 업그레이드 시 즉시 적용되며, 다운그레이드는 다음 결제 주기부터 적용됩니다.",
    category: "요금제",
    tags: ["변경", "업그레이드", "다운그레이드"],
    helpful: 25,
    notHelpful: 3,
    lastUpdated: "2024-01-09",
  },
];

const defaultCategories = [
  "전체",
  "기본 정보",
  "요금제",
  "보안",
  "기술",
  "팀 관리",
  "고객 지원",
];

export function PlusFaq({
  title = "자주 묻는 질문",
  description = "궁금한 점들에 대한 답변을 확인해보세요.",
  faqItems = defaultFaqItems,
  categories = defaultCategories,
  showSearch = true,
  showCategories = true,
  showVoting = true,
  showLastUpdated = true,
  showFeatured = true,
  maxItemsPerCategory = 10,
  className,
  theme = {},
}: PlusFaqProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("전체");
  const [openItems, setOpenItems] = useState<Set<string>>(new Set());
  const [votes, setVotes] = useState<
    Record<string, { helpful: number; notHelpful: number }>
  >({});

  // Filter and search FAQ items
  const filteredItems = useMemo(() => {
    let items = faqItems;

    // Filter by category
    if (selectedCategory !== "전체") {
      items = items.filter((item) => item.category === selectedCategory);
    }

    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      items = items.filter(
        (item) =>
          item.question.toLowerCase().includes(query) ||
          item.answer.toLowerCase().includes(query) ||
          item.tags.some((tag) => tag.toLowerCase().includes(query))
      );
    }

    // Sort by featured first, then by helpful votes
    return items.sort((a, b) => {
      if (a.featured && !b.featured) return -1;
      if (!a.featured && b.featured) return 1;

      const aHelpful = (a.helpful || 0) + (votes[a.id]?.helpful || 0);
      const bHelpful = (b.helpful || 0) + (votes[b.id]?.helpful || 0);
      return bHelpful - aHelpful;
    });
  }, [faqItems, selectedCategory, searchQuery, votes]);

  const toggleItem = (itemId: string) => {
    const newOpenItems = new Set(openItems);
    if (newOpenItems.has(itemId)) {
      newOpenItems.delete(itemId);
    } else {
      newOpenItems.add(itemId);
    }
    setOpenItems(newOpenItems);
  };

  const handleVote = (itemId: string, type: "helpful" | "notHelpful") => {
    setVotes((prev) => ({
      ...prev,
      [itemId]: {
        helpful:
          type === "helpful"
            ? (prev[itemId]?.helpful || 0) + 1
            : prev[itemId]?.helpful || 0,
        notHelpful:
          type === "notHelpful"
            ? (prev[itemId]?.notHelpful || 0) + 1
            : prev[itemId]?.notHelpful || 0,
      },
    }));
  };

  const FaqItem = ({ item }: { item: FaqItem }) => {
    const isOpen = openItems.has(item.id);
    const currentVotes = votes[item.id] || { helpful: 0, notHelpful: 0 };
    const totalHelpful = (item.helpful || 0) + currentVotes.helpful;
    const totalNotHelpful = (item.notHelpful || 0) + currentVotes.notHelpful;

    return (
      <div className="border border-gray-200 rounded-lg bg-white">
        <button
          onClick={() => toggleItem(item.id)}
          className="w-full px-6 py-4 text-left flex items-center justify-between hover:bg-gray-50 transition-colors"
        >
          <div className="flex-1">
            <div className="flex items-center">
              {item.featured && showFeatured && (
                <span
                  className="mr-2 px-2 py-1 text-xs font-semibold rounded"
                  style={{
                    backgroundColor: theme.accentColor || "#fef3c7",
                    color: theme.primaryColor || "#d97706",
                  }}
                >
                  인기
                </span>
              )}
              <h3 className="text-lg font-semibold text-gray-900">
                {item.question}
              </h3>
            </div>

            {showLastUpdated && item.lastUpdated && (
              <p className="text-sm text-gray-500 mt-1">
                마지막 업데이트:{" "}
                {new Date(item.lastUpdated).toLocaleDateString("ko-KR")}
              </p>
            )}
          </div>

          <div className="ml-4 flex items-center">
            {showVoting && (totalHelpful > 0 || totalNotHelpful > 0) && (
              <div className="flex items-center mr-4 text-sm text-gray-500">
                <span className="text-green-600">👍 {totalHelpful}</span>
                {totalNotHelpful > 0 && (
                  <span className="ml-2 text-red-600">
                    👎 {totalNotHelpful}
                  </span>
                )}
              </div>
            )}

            <svg
              className={clsx(
                "w-5 h-5 transition-transform",
                isOpen ? "transform rotate-180" : ""
              )}
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M19 9l-7 7-7-7"
              />
            </svg>
          </div>
        </button>

        {isOpen && (
          <div className="px-6 pb-6">
            <div className="pt-2 border-t border-gray-100">
              <div className="prose prose-sm max-w-none text-gray-700 mb-4">
                {item.answer}
              </div>

              {/* Tags */}
              {item.tags.length > 0 && (
                <div className="flex flex-wrap gap-2 mb-4">
                  {item.tags.map((tag) => (
                    <span
                      key={tag}
                      className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded"
                    >
                      #{tag}
                    </span>
                  ))}
                </div>
              )}

              {/* Voting */}
              {showVoting && (
                <div className="flex items-center justify-between pt-4 border-t border-gray-100">
                  <span className="text-sm text-gray-600">
                    이 답변이 도움이 되었나요?
                  </span>
                  <div className="flex space-x-2">
                    <button
                      onClick={() => handleVote(item.id, "helpful")}
                      className="flex items-center px-3 py-1 text-sm text-green-600 hover:bg-green-50 rounded transition-colors"
                    >
                      👍 도움됨 {totalHelpful > 0 && `(${totalHelpful})`}
                    </button>
                    <button
                      onClick={() => handleVote(item.id, "notHelpful")}
                      className="flex items-center px-3 py-1 text-sm text-red-600 hover:bg-red-50 rounded transition-colors"
                    >
                      👎 도움 안됨{" "}
                      {totalNotHelpful > 0 && `(${totalNotHelpful})`}
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    );
  };

  return (
    <section
      className={clsx("py-16 bg-white", className)}
      style={{ fontFamily: theme.fontFamily }}
    >
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="text-center mb-12">
          <h2
            className="text-3xl font-bold mb-4"
            style={{ color: theme.primaryColor || "#1f2937" }}
          >
            {title}
          </h2>
          <p className="text-xl text-gray-600 max-w-2xl mx-auto">
            {description}
          </p>
        </div>

        {/* Search */}
        {showSearch && (
          <div className="mb-8">
            <div className="relative">
              <input
                type="text"
                placeholder="질문이나 키워드로 검색해보세요..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full px-4 py-3 pl-12 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                style={{
                  borderColor: theme.primaryColor
                    ? `${theme.primaryColor}20`
                    : undefined,
                }}
              />
              <svg
                className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                />
              </svg>
            </div>
          </div>
        )}

        {/* Categories */}
        {showCategories && (
          <div className="flex flex-wrap justify-center gap-2 mb-8">
            {categories.map((category) => (
              <button
                key={category}
                onClick={() => setSelectedCategory(category)}
                className={clsx(
                  "px-4 py-2 rounded-full text-sm font-medium transition-colors",
                  selectedCategory === category
                    ? "text-white"
                    : "text-gray-600 bg-gray-100 hover:bg-gray-200"
                )}
                style={{
                  backgroundColor:
                    selectedCategory === category
                      ? theme.primaryColor || "#3b82f6"
                      : undefined,
                }}
              >
                {category}
              </button>
            ))}
          </div>
        )}

        {/* Results count */}
        <div className="mb-6 text-sm text-gray-600">
          {filteredItems.length}개의 결과{" "}
          {searchQuery && `"${searchQuery}"에 대한 검색 결과`}
        </div>

        {/* FAQ Items */}
        <div className="space-y-4">
          {filteredItems.length > 0 ? (
            filteredItems
              .slice(0, maxItemsPerCategory)
              .map((item) => <FaqItem key={item.id} item={item} />)
          ) : (
            <div className="text-center py-12">
              <div className="text-gray-400 mb-4">
                <svg
                  className="w-16 h-16 mx-auto"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={1}
                    d="M9.172 16.172a4 4 0 015.656 0M9 12h6m-6-4h6m2 5.291A7.962 7.962 0 0112 15c-2.34 0-4.47-.881-6.08-2.33A7.96 7.96 0 003 10.5C3 5.358 7.358 1 12.5 1S22 5.358 22 10.5c0 1.441-.322 2.805-.896 4.023A7.957 7.957 0 0118 17.5c-2.34 0-4.47-.881-6.08-2.33z"
                  />
                </svg>
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">
                검색 결과가 없습니다
              </h3>
              <p className="text-gray-600 mb-4">
                다른 키워드로 검색해보시거나 카테고리를 변경해보세요.
              </p>
              <button
                onClick={() => {
                  setSearchQuery("");
                  setSelectedCategory("전체");
                }}
                className="text-blue-600 hover:text-blue-800 font-medium"
              >
                검색 초기화
              </button>
            </div>
          )}
        </div>

        {/* Contact CTA */}
        <div className="mt-12 text-center bg-gray-50 rounded-lg p-8">
          <h3 className="text-lg font-semibold text-gray-900 mb-2">
            찾으시는 답변이 없나요?
          </h3>
          <p className="text-gray-600 mb-4">
            저희 고객 지원팀이 직접 도움을 드리겠습니다.
          </p>
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <a
              href="/contact"
              className="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white hover:opacity-90 transition-opacity"
              style={{ backgroundColor: theme.primaryColor || "#3b82f6" }}
            >
              문의하기
            </a>
            <a
              href="/docs"
              className="inline-flex items-center px-6 py-3 border border-gray-300 text-base font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 transition-colors"
            >
              문서 보기
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}
