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

interface PortfolioItem {
  id: string;
  title: string;
  description: string;
  category: string;
  image: string;
  technologies?: string[];
  projectUrl?: string;
  githubUrl?: string;
  date?: string;
  client?: string;
}

interface StandardPortfolioProps {
  title?: string;
  description?: string;
  portfolioItems?: PortfolioItem[];
  categories?: string[];
  showFilters?: boolean;
  showTechnologies?: boolean;
  layout?: "grid" | "masonry";
  itemsPerPage?: number;
  className?: string;
  theme?: {
    primaryColor?: string;
    secondaryColor?: string;
    accentColor?: string;
    fontFamily?: string;
  };
}

const defaultPortfolioItems: PortfolioItem[] = [
  {
    id: "1",
    title: "E-커머스 플랫폼",
    description: "React와 Node.js를 활용한 풀스택 전자상거래 솔루션",
    category: "웹 개발",
    image: "/images/portfolio/ecommerce-platform.jpg",
    technologies: ["React", "Node.js", "PostgreSQL", "Redis"],
    projectUrl: "https://example-ecommerce.com",
    githubUrl: "https://github.com/example/ecommerce",
    date: "2024-01-15",
    client: "온라인몰 스타트업",
  },
  {
    id: "2",
    title: "모바일 앱 디자인",
    description: "사용자 친화적인 헬스케어 모바일 앱 UI/UX 디자인",
    category: "디자인",
    image: "/images/portfolio/mobile-app-design.jpg",
    technologies: ["Figma", "Sketch", "Adobe XD"],
    date: "2024-01-10",
    client: "헬스케어 스타트업",
  },
  {
    id: "3",
    title: "데이터 분석 대시보드",
    description: "실시간 비즈니스 인텔리전스 대시보드 구축",
    category: "데이터 분석",
    image: "/images/portfolio/analytics-dashboard.jpg",
    technologies: ["Python", "React", "D3.js", "MongoDB"],
    projectUrl: "https://example-dashboard.com",
    date: "2023-12-20",
    client: "제조업체",
  },
  {
    id: "4",
    title: "브랜드 아이덴티티",
    description: "스타트업을 위한 완전한 브랜드 아이덴티티 시스템",
    category: "디자인",
    image: "/images/portfolio/brand-identity.jpg",
    technologies: ["Adobe Illustrator", "Adobe Photoshop"],
    date: "2023-12-01",
    client: "테크 스타트업",
  },
  {
    id: "5",
    title: "AI 챗봇 시스템",
    description: "자연어 처리 기반 고객 서비스 챗봇",
    category: "AI/ML",
    image: "/images/portfolio/ai-chatbot.jpg",
    technologies: ["Python", "TensorFlow", "FastAPI", "Docker"],
    githubUrl: "https://github.com/example/ai-chatbot",
    date: "2023-11-15",
    client: "금융 서비스",
  },
  {
    id: "6",
    title: "클라우드 인프라",
    description: "AWS 기반 확장 가능한 마이크로서비스 아키텍처",
    category: "클라우드",
    image: "/images/portfolio/cloud-infrastructure.jpg",
    technologies: ["AWS", "Docker", "Kubernetes", "Terraform"],
    date: "2023-10-30",
    client: "대기업",
  },
];

const defaultCategories = [
  "전체",
  "웹 개발",
  "디자인",
  "데이터 분석",
  "AI/ML",
  "클라우드",
];

export function StandardPortfolio({
  title = "포트폴리오",
  description = "저희가 수행한 다양한 프로젝트들을 확인해보세요.",
  portfolioItems = defaultPortfolioItems,
  categories = defaultCategories,
  showFilters = true,
  showTechnologies = true,
  layout = "grid",
  itemsPerPage = 6,
  className,
  theme = {},
}: StandardPortfolioProps) {
  const [selectedCategory, setSelectedCategory] = useState("전체");
  const [selectedItem, setSelectedItem] = useState<PortfolioItem | null>(null);
  const [showModal, setShowModal] = useState(false);

  const filteredItems =
    selectedCategory === "전체"
      ? portfolioItems
      : portfolioItems.filter((item) => item.category === selectedCategory);

  const openModal = (item: PortfolioItem) => {
    setSelectedItem(item);
    setShowModal(true);
  };

  const closeModal = () => {
    setSelectedItem(null);
    setShowModal(false);
  };

  const renderPortfolioItem = (item: PortfolioItem) => (
    <div
      key={item.id}
      className="group bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition-all duration-300 cursor-pointer"
      onClick={() => openModal(item)}
    >
      <div className="relative overflow-hidden">
        <img
          src={item.image}
          alt={item.title}
          className="w-full h-48 object-cover group-hover:scale-105 transition-transform duration-300"
        />
        <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-opacity duration-300 flex items-center justify-center">
          <div className="text-white opacity-0 group-hover:opacity-100 transition-opacity duration-300">
            <svg
              className="w-8 h-8"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
              />
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
              />
            </svg>
          </div>
        </div>
      </div>

      <div className="p-6">
        <div className="flex items-center justify-between mb-2">
          <span
            className="text-xs font-semibold px-2 py-1 rounded"
            style={{
              backgroundColor: `${theme.primaryColor}20` || "#3b82f620",
              color: theme.primaryColor || "#3b82f6",
            }}
          >
            {item.category}
          </span>
          {item.date && (
            <span className="text-xs text-gray-500">
              {new Date(item.date).toLocaleDateString("ko-KR")}
            </span>
          )}
        </div>

        <h3 className="font-bold text-lg mb-2 group-hover:text-blue-600 transition-colors">
          {item.title}
        </h3>

        <p className="text-gray-600 text-sm mb-4 line-clamp-2">
          {item.description}
        </p>

        {showTechnologies &&
          item.technologies &&
          item.technologies.length > 0 && (
            <div className="flex flex-wrap gap-1">
              {item.technologies.slice(0, 3).map((tech) => (
                <span
                  key={tech}
                  className="text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded"
                >
                  {tech}
                </span>
              ))}
              {item.technologies.length > 3 && (
                <span className="text-xs text-gray-500">
                  +{item.technologies.length - 3}
                </span>
              )}
            </div>
          )}
      </div>
    </div>
  );

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

          {/* Filters */}
          {showFilters && (
            <div className="flex flex-wrap justify-center gap-2 mb-12">
              {categories.map((category) => (
                <button
                  key={category}
                  onClick={() => setSelectedCategory(category)}
                  className={clsx(
                    "px-4 py-2 rounded-full text-sm font-medium transition-colors duration-300",
                    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>
          )}

          {/* Portfolio Grid */}
          <div
            className={clsx(
              layout === "grid" && "grid gap-8 md:grid-cols-2 lg:grid-cols-3",
              layout === "masonry" &&
                "columns-1 md:columns-2 lg:columns-3 gap-8"
            )}
          >
            {filteredItems.map(renderPortfolioItem)}
          </div>
        </div>
      </section>

      {/* Modal */}
      {showModal && selectedItem && (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex justify-between items-start mb-6">
                <h3 className="text-2xl font-bold">{selectedItem.title}</h3>
                <button
                  onClick={closeModal}
                  className="text-gray-500 hover:text-gray-700"
                >
                  <svg
                    className="w-6 h-6"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M6 18L18 6M6 6l12 12"
                    />
                  </svg>
                </button>
              </div>

              <img
                src={selectedItem.image}
                alt={selectedItem.title}
                className="w-full h-64 object-cover rounded-lg mb-6"
              />

              <div className="grid md:grid-cols-2 gap-6">
                <div>
                  <h4 className="font-semibold mb-2">프로젝트 설명</h4>
                  <p className="text-gray-600 mb-4">
                    {selectedItem.description}
                  </p>

                  {selectedItem.client && (
                    <div className="mb-4">
                      <h4 className="font-semibold mb-1">클라이언트</h4>
                      <p className="text-gray-600">{selectedItem.client}</p>
                    </div>
                  )}

                  {selectedItem.date && (
                    <div className="mb-4">
                      <h4 className="font-semibold mb-1">완료일</h4>
                      <p className="text-gray-600">
                        {new Date(selectedItem.date).toLocaleDateString(
                          "ko-KR"
                        )}
                      </p>
                    </div>
                  )}
                </div>

                <div>
                  {selectedItem.technologies &&
                    selectedItem.technologies.length > 0 && (
                      <div className="mb-6">
                        <h4 className="font-semibold mb-2">사용 기술</h4>
                        <div className="flex flex-wrap gap-2">
                          {selectedItem.technologies.map((tech) => (
                            <span
                              key={tech}
                              className="bg-gray-100 text-gray-700 px-3 py-1 rounded"
                            >
                              {tech}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}

                  <div className="flex gap-4">
                    {selectedItem.projectUrl && (
                      <a
                        href={selectedItem.projectUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="px-4 py-2 rounded text-white font-medium transition-colors"
                        style={{
                          backgroundColor: theme.primaryColor || "#3b82f6",
                        }}
                      >
                        프로젝트 보기
                      </a>
                    )}
                    {selectedItem.githubUrl && (
                      <a
                        href={selectedItem.githubUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="px-4 py-2 border border-gray-300 rounded text-gray-700 font-medium hover:bg-gray-50 transition-colors"
                      >
                        GitHub
                      </a>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
