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

interface TeamMember {
  id: string;
  name: string;
  position: string;
  department: string;
  bio: string;
  avatar: string;
  skills: string[];
  experience: string;
  email?: string;
  phone?: string;
  socialLinks: {
    linkedin?: string;
    twitter?: string;
    github?: string;
    portfolio?: string;
  };
  achievements?: string[];
  certifications?: string[];
}

interface PlusTeamProps {
  title?: string;
  description?: string;
  teamMembers?: TeamMember[];
  layout?: "grid" | "carousel" | "masonry";
  showSkills?: boolean;
  showBio?: boolean;
  showSocial?: boolean;
  showModal?: boolean;
  groupByDepartment?: boolean;
  className?: string;
  theme?: {
    primaryColor?: string;
    secondaryColor?: string;
    accentColor?: string;
    fontFamily?: string;
  };
}

const defaultTeamMembers: TeamMember[] = [
  {
    id: "1",
    name: "김지영",
    position: "CEO & 설립자",
    department: "경영진",
    bio: "15년 이상의 기술 업계 경험을 바탕으로 혁신적인 솔루션을 제공하는 비전을 가지고 있습니다.",
    avatar: "/images/team/ceo.jpg",
    skills: ["전략 기획", "비즈니스 개발", "팀 리더십", "투자 유치"],
    experience: "15년",
    email: "jiyoung@company.com",
    socialLinks: {
      linkedin: "https://linkedin.com/in/jiyoung-kim",
      twitter: "https://twitter.com/jiyoung_kim",
    },
    achievements: ["Forbes 30 Under 30", "Tech Innovation Award 2023"],
    certifications: ["PMP", "Agile Master"],
  },
  {
    id: "2",
    name: "박민수",
    position: "CTO",
    department: "기술",
    bio: "풀스택 개발자로 시작하여 대규모 시스템 아키텍처 설계와 팀 관리를 담당하고 있습니다.",
    avatar: "/images/team/cto.jpg",
    skills: ["시스템 아키텍처", "클라우드 인프라", "DevOps", "팀 관리"],
    experience: "12년",
    email: "minsu@company.com",
    socialLinks: {
      linkedin: "https://linkedin.com/in/minsu-park",
      github: "https://github.com/minsu-park",
    },
    achievements: [
      "AWS Solutions Architect Professional",
      "Google Cloud Expert",
    ],
    certifications: ["AWS SAA", "GCP Professional", "Kubernetes CKA"],
  },
  {
    id: "3",
    name: "이수진",
    position: "UX/UI 디자인 리드",
    department: "디자인",
    bio: "사용자 중심의 디자인 철학으로 직관적이고 아름다운 인터페이스를 만들어갑니다.",
    avatar: "/images/team/designer.jpg",
    skills: ["UI/UX 디자인", "프로토타이핑", "디자인 시스템", "사용자 리서치"],
    experience: "8년",
    email: "sujin@company.com",
    socialLinks: {
      linkedin: "https://linkedin.com/in/sujin-lee",
      portfolio: "https://sujinlee.design",
    },
    achievements: ["Red Dot Design Award", "iF Design Award"],
    certifications: ["Google UX Design Certificate", "Adobe Certified Expert"],
  },
  {
    id: "4",
    name: "정현우",
    position: "시니어 풀스택 개발자",
    department: "기술",
    bio: "최신 기술 스택을 활용하여 확장 가능한 웹 애플리케이션을 개발하는 것이 전문 분야입니다.",
    avatar: "/images/team/developer.jpg",
    skills: ["React", "Node.js", "Python", "AWS", "Docker"],
    experience: "6년",
    email: "hyunwoo@company.com",
    socialLinks: {
      github: "https://github.com/hyunwoo-jung",
      linkedin: "https://linkedin.com/in/hyunwoo-jung",
    },
    achievements: ["오픈소스 기여자", "해커톤 우승"],
    certifications: ["AWS Developer Associate", "MongoDB Developer"],
  },
];

export function PlusTeam({
  title = "우리 팀",
  description = "열정적이고 전문적인 팀원들을 소개합니다.",
  teamMembers = defaultTeamMembers,
  layout = "grid",
  showSkills = true,
  showBio = true,
  showSocial = true,
  showModal = true,
  groupByDepartment = false,
  className,
  theme = {},
}: PlusTeamProps) {
  const [selectedMember, setSelectedMember] = useState<TeamMember | null>(null);

  // Group members by department if requested
  const organizedMembers = groupByDepartment
    ? teamMembers.reduce((groups, member) => {
        const dept = member.department;
        if (!groups[dept]) {
          groups[dept] = [];
        }
        groups[dept].push(member);
        return groups;
      }, {} as Record<string, TeamMember[]>)
    : { "All Members": teamMembers };

  const openModal = (member: TeamMember) => {
    if (showModal) {
      setSelectedMember(member);
    }
  };

  const closeModal = () => {
    setSelectedMember(null);
  };

  const TeamMemberCard = ({ member }: { member: TeamMember }) => (
    <div
      className={clsx(
        "bg-white rounded-lg shadow-lg overflow-hidden hover:shadow-xl transition-shadow duration-300",
        showModal && "cursor-pointer"
      )}
      onClick={() => openModal(member)}
      style={{
        fontFamily: theme.fontFamily,
      }}
    >
      <div className="relative">
        <img
          src={member.avatar}
          alt={member.name}
          className="w-full h-64 object-cover"
          onError={(e) => {
            const target = e.target as HTMLImageElement;
            target.src = `https://ui-avatars.com/api/?name=${encodeURIComponent(
              member.name
            )}&size=256&background=${
              theme.primaryColor?.replace("#", "") || "007bff"
            }&color=fff`;
          }}
        />
        <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent" />
        <div className="absolute bottom-4 left-4 text-white">
          <h3 className="text-xl font-bold">{member.name}</h3>
          <p className="text-sm opacity-90">{member.position}</p>
        </div>
      </div>

      <div className="p-6">
        <div className="mb-4">
          <span
            className="inline-block px-3 py-1 text-xs font-semibold rounded-full"
            style={{
              backgroundColor: theme.accentColor || "#e3f2fd",
              color: theme.primaryColor || "#1976d2",
            }}
          >
            {member.department}
          </span>
          <span className="ml-2 text-sm text-gray-600">
            {member.experience} 경력
          </span>
        </div>

        {showBio && (
          <p className="text-gray-700 text-sm mb-4 line-clamp-3">
            {member.bio}
          </p>
        )}

        {showSkills && member.skills.length > 0 && (
          <div className="mb-4">
            <h4 className="text-sm font-semibold text-gray-800 mb-2">
              주요 스킬
            </h4>
            <div className="flex flex-wrap gap-1">
              {member.skills.slice(0, 4).map((skill) => (
                <span
                  key={skill}
                  className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded"
                >
                  {skill}
                </span>
              ))}
              {member.skills.length > 4 && (
                <span className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded">
                  +{member.skills.length - 4}
                </span>
              )}
            </div>
          </div>
        )}

        {showSocial && (
          <div className="flex space-x-3">
            {member.email && (
              <a
                href={`mailto:${member.email}`}
                className="text-gray-400 hover:text-gray-600 transition-colors"
                onClick={(e) => e.stopPropagation()}
              >
                <span className="sr-only">Email</span>
                📧
              </a>
            )}
            {member.socialLinks.linkedin && (
              <a
                href={member.socialLinks.linkedin}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gray-400 hover:text-blue-600 transition-colors"
                onClick={(e) => e.stopPropagation()}
              >
                <span className="sr-only">LinkedIn</span>
                💼
              </a>
            )}
            {member.socialLinks.github && (
              <a
                href={member.socialLinks.github}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gray-400 hover:text-gray-900 transition-colors"
                onClick={(e) => e.stopPropagation()}
              >
                <span className="sr-only">GitHub</span>
                🔗
              </a>
            )}
            {member.socialLinks.portfolio && (
              <a
                href={member.socialLinks.portfolio}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gray-400 hover:text-purple-600 transition-colors"
                onClick={(e) => e.stopPropagation()}
              >
                <span className="sr-only">Portfolio</span>
                🎨
              </a>
            )}
          </div>
        )}
      </div>
    </div>
  );

  return (
    <section
      className={clsx("py-16 bg-gray-50", className)}
      style={{ fontFamily: theme.fontFamily }}
    >
      <div className="max-w-7xl 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-3xl mx-auto">
            {description}
          </p>
        </div>

        {/* Team Members */}
        {Object.entries(organizedMembers).map(([department, members]) => (
          <div key={department} className="mb-12">
            {groupByDepartment && department !== "All Members" && (
              <h3
                className="text-2xl font-semibold mb-8 text-center"
                style={{ color: theme.secondaryColor || "#374151" }}
              >
                {department}
              </h3>
            )}

            <div
              className={clsx(
                "grid gap-8",
                layout === "grid" &&
                  "grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",
                layout === "masonry" && "columns-1 md:columns-2 lg:columns-3",
                layout === "carousel" &&
                  "grid-cols-1 md:grid-cols-2 lg:grid-cols-3"
              )}
            >
              {members.map((member) => (
                <TeamMemberCard key={member.id} member={member} />
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Modal */}
      {showModal && selectedMember && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50"
          onClick={closeModal}
        >
          <div
            className="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="p-6">
              <div className="flex justify-between items-start mb-6">
                <div className="flex items-center">
                  <img
                    src={selectedMember.avatar}
                    alt={selectedMember.name}
                    className="w-20 h-20 rounded-full object-cover mr-4"
                    onError={(e) => {
                      const target = e.target as HTMLImageElement;
                      target.src = `https://ui-avatars.com/api/?name=${encodeURIComponent(
                        selectedMember.name
                      )}&size=80&background=${
                        theme.primaryColor?.replace("#", "") || "007bff"
                      }&color=fff`;
                    }}
                  />
                  <div>
                    <h3 className="text-2xl font-bold">
                      {selectedMember.name}
                    </h3>
                    <p className="text-lg text-gray-600">
                      {selectedMember.position}
                    </p>
                    <p className="text-sm text-gray-500">
                      {selectedMember.department} • {selectedMember.experience}{" "}
                      경력
                    </p>
                  </div>
                </div>
                <button
                  onClick={closeModal}
                  className="text-gray-400 hover:text-gray-600 text-2xl"
                >
                  ✕
                </button>
              </div>

              <div className="space-y-6">
                <div>
                  <h4 className="text-lg font-semibold mb-2">소개</h4>
                  <p className="text-gray-700">{selectedMember.bio}</p>
                </div>

                <div>
                  <h4 className="text-lg font-semibold mb-2">전문 분야</h4>
                  <div className="flex flex-wrap gap-2">
                    {selectedMember.skills.map((skill) => (
                      <span
                        key={skill}
                        className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm"
                      >
                        {skill}
                      </span>
                    ))}
                  </div>
                </div>

                {selectedMember.achievements &&
                  selectedMember.achievements.length > 0 && (
                    <div>
                      <h4 className="text-lg font-semibold mb-2">주요 성과</h4>
                      <ul className="list-disc list-inside text-gray-700 space-y-1">
                        {selectedMember.achievements.map(
                          (achievement, index) => (
                            <li key={index}>{achievement}</li>
                          )
                        )}
                      </ul>
                    </div>
                  )}

                {selectedMember.certifications &&
                  selectedMember.certifications.length > 0 && (
                    <div>
                      <h4 className="text-lg font-semibold mb-2">자격증</h4>
                      <div className="flex flex-wrap gap-2">
                        {selectedMember.certifications.map((cert) => (
                          <span
                            key={cert}
                            className="px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm"
                          >
                            {cert}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}

                <div>
                  <h4 className="text-lg font-semibold mb-2">연락처</h4>
                  <div className="flex space-x-4">
                    {selectedMember.email && (
                      <a
                        href={`mailto:${selectedMember.email}`}
                        className="flex items-center text-blue-600 hover:text-blue-800"
                      >
                        📧 이메일
                      </a>
                    )}
                    {selectedMember.socialLinks.linkedin && (
                      <a
                        href={selectedMember.socialLinks.linkedin}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center text-blue-600 hover:text-blue-800"
                      >
                        💼 LinkedIn
                      </a>
                    )}
                    {selectedMember.socialLinks.github && (
                      <a
                        href={selectedMember.socialLinks.github}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center text-gray-600 hover:text-gray-800"
                      >
                        🔗 GitHub
                      </a>
                    )}
                    {selectedMember.socialLinks.portfolio && (
                      <a
                        href={selectedMember.socialLinks.portfolio}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center text-purple-600 hover:text-purple-800"
                      >
                        🎨 Portfolio
                      </a>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}
