/**
 * 봇 카드 컴포넌트
 */
import { memo } from 'react';
import { motion } from 'framer-motion';
import { Play, Square, RefreshCw, Download } from 'lucide-react';

// X 아이콘 컴포넌트
export const XIcon = ({ size = 20, fill = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={fill}>
    <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
  </svg>
);

// Meilisearch 아이콘 컴포넌트
export const MeilisearchIcon = ({ size = 20 }) => (
  <svg width={size} height={size} viewBox="0 108.4 512 295.2">
    <defs>
      <linearGradient id="meili-a" x1="488.157" x2="-21.055" y1="469.917" y2="179.001" gradientTransform="matrix(1 0 0 -1 0 514)" gradientUnits="userSpaceOnUse">
        <stop offset="0" stopColor="#ff5caa" />
        <stop offset="1" stopColor="#ff4e62" />
      </linearGradient>
      <linearGradient id="meili-b" x1="522.305" x2="13.094" y1="410.144" y2="119.228" gradientTransform="matrix(1 0 0 -1 0 514)" gradientUnits="userSpaceOnUse">
        <stop offset="0" stopColor="#ff5caa" />
        <stop offset="1" stopColor="#ff4e62" />
      </linearGradient>
      <linearGradient id="meili-c" x1="556.456" x2="47.244" y1="350.368" y2="59.452" gradientTransform="matrix(1 0 0 -1 0 514)" gradientUnits="userSpaceOnUse">
        <stop offset="0" stopColor="#ff5caa" />
        <stop offset="1" stopColor="#ff4e62" />
      </linearGradient>
    </defs>
    <path d="m0 403.6 94.6-239.3c13.3-33.7 46.2-55.9 82.8-55.9h57l-94.6 239.3c-13.3 33.7-46.2 55.9-82.8 55.9z" fill="url(#meili-a)" />
    <path d="m138.8 403.6 94.6-239.3c13.3-33.7 46.2-55.9 82.8-55.9h57l-94.6 239.3c-13.3 33.7-46.2 55.9-82.8 55.9z" fill="url(#meili-b)" />
    <path d="m277.6 403.6 94.6-239.3c13.3-33.7 46.2-55.9 82.8-55.9h57l-94.6 239.3c-13.3 33.7-46.2 55.9-82.8 55.9z" fill="url(#meili-c)" />
  </svg>
);

/**
 * 리스트형 봇 (Meilisearch용) - 한 줄에 모든 정보
 */
export const BotListItem = memo(function BotListItem({
  bot,
  index,
  isInitialLoad,
  syncing,
  statusInfo,
  onSync,
  onToggle,
  onAnimationComplete,
  formatTime,
  formatInterval,
}) {
  return (
    <motion.div
      initial={isInitialLoad ? { opacity: 0, x: -10 } : false}
      animate={{ opacity: 1, x: 0 }}
      transition={isInitialLoad ? { delay: index * 0.05, duration: 0.2 } : { duration: 0.15 }}
      onAnimationComplete={onAnimationComplete}
      className="flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-xl hover:bg-gray-50 transition-colors"
    >
      {/* 상태 표시 */}
      <div className={`w-2 h-2 rounded-full ${statusInfo.dot} ${bot.status === 'running' ? 'animate-pulse' : ''}`} />

      {/* 이름 */}
      <div className="flex-1 min-w-0">
        <h3 className="font-medium text-gray-900 truncate">{bot.name}</h3>
      </div>

      {/* 통계 */}
      <div className="hidden sm:flex items-center gap-6 text-sm text-gray-500">
        <div className="text-center">
          <span className="font-semibold text-gray-900">{bot.schedules_added || 0}</span>
          <span className="ml-1">추가</span>
        </div>
        <div className="text-center">
          <span className="text-xs">{bot.last_check_at ? formatTime(bot.last_check_at) : '-'}</span>
        </div>
      </div>

      {/* 버튼 */}
      <div className="flex items-center gap-2">
        <button
          onClick={() => onSync(bot.id)}
          disabled={syncing === bot.id}
          className="p-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors disabled:opacity-50"
          title="전체 동기화"
        >
          {syncing === bot.id ? (
            <RefreshCw size={18} className="animate-spin" />
          ) : (
            <Download size={18} />
          )}
        </button>
        <button
          onClick={() => onToggle(bot.id, bot.status, bot.name)}
          className={`p-2 rounded-lg transition-colors ${
            bot.status === 'running'
              ? 'text-gray-500 hover:text-red-600 hover:bg-red-50'
              : 'text-gray-500 hover:text-green-600 hover:bg-green-50'
          }`}
          title={bot.status === 'running' ? '정지' : '시작'}
        >
          {bot.status === 'running' ? <Square size={18} /> : <Play size={18} />}
        </button>
      </div>
    </motion.div>
  );
});

/**
 * 미니 카드형 봇 (YouTube용) - 컴팩트한 카드
 */
export const BotMiniCard = memo(function BotMiniCard({
  bot,
  index,
  isInitialLoad,
  syncing,
  statusInfo,
  onSync,
  onToggle,
  onAnimationComplete,
  formatTime,
  formatInterval,
}) {
  return (
    <motion.div
      initial={isInitialLoad ? { opacity: 0, scale: 0.95 } : false}
      animate={{ opacity: 1, scale: 1 }}
      transition={isInitialLoad ? { delay: index * 0.05, duration: 0.2 } : { duration: 0.15 }}
      onAnimationComplete={onAnimationComplete}
      className="group relative bg-white border border-gray-200 rounded-xl overflow-hidden hover:shadow-md transition-all"
    >
      {/* 메인 영역 */}
      <div className="p-4">
        <div className="flex items-center justify-between">
          <h3 className="font-semibold text-gray-900 truncate flex-1">{bot.name}</h3>
          <span
            className={`ml-2 flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded-full ${statusInfo.bg} ${statusInfo.color}`}
          >
            <span className={`w-1.5 h-1.5 rounded-full ${statusInfo.dot} ${bot.status === 'running' ? 'animate-pulse' : ''}`} />
            {statusInfo.text}
          </span>
        </div>

        {/* 간단 통계 */}
        <div className="mt-2 flex items-center gap-3 text-xs text-gray-500">
          <span>총 <strong className="text-gray-900">{bot.schedules_added || 0}</strong></span>
          <span>•</span>
          <span>최근 <strong className={bot.last_added_count > 0 ? 'text-green-600' : 'text-gray-400'}>+{bot.last_added_count || 0}</strong></span>
          <span>•</span>
          <span>{formatInterval(bot.check_interval)}</span>
        </div>

        {/* 마지막 업데이트 */}
        <p className="mt-1 text-xs text-gray-400">
          {bot.last_check_at ? formatTime(bot.last_check_at) : '대기 중'}
        </p>
      </div>

      {/* 오류 메시지 */}
      {bot.status === 'error' && bot.error_message && (
        <div className="px-4 py-2 bg-red-50 text-red-600 text-xs">
          {bot.error_message}
        </div>
      )}

      {/* 호버시 나타나는 액션 버튼 */}
      <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-3">
        <button
          onClick={() => onSync(bot.id)}
          disabled={syncing === bot.id}
          className="flex items-center gap-1.5 px-3 py-2 bg-white text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-100 transition-colors disabled:opacity-50"
        >
          {syncing === bot.id ? (
            <RefreshCw size={14} className="animate-spin" />
          ) : (
            <Download size={14} />
          )}
          동기화
        </button>
        <button
          onClick={() => onToggle(bot.id, bot.status, bot.name)}
          className={`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
            bot.status === 'running'
              ? 'bg-red-500 text-white hover:bg-red-600'
              : 'bg-green-500 text-white hover:bg-green-600'
          }`}
        >
          {bot.status === 'running' ? <Square size={14} /> : <Play size={14} />}
          {bot.status === 'running' ? '정지' : '시작'}
        </button>
      </div>
    </motion.div>
  );
});

/**
 * 테이블 행 봇 (X용)
 */
export const BotTableRow = memo(function BotTableRow({
  bot,
  index,
  isInitialLoad,
  syncing,
  statusInfo,
  onSync,
  onToggle,
  onAnimationComplete,
  formatTime,
  formatInterval,
}) {
  return (
    <motion.tr
      initial={isInitialLoad ? { opacity: 0 } : false}
      animate={{ opacity: 1 }}
      transition={isInitialLoad ? { delay: index * 0.05, duration: 0.2 } : { duration: 0.15 }}
      onAnimationComplete={onAnimationComplete}
      className="border-b border-gray-100 last:border-0 hover:bg-gray-50 transition-colors"
    >
      <td className="px-4 py-3">
        <div className="flex items-center gap-2">
          <span className={`w-2 h-2 rounded-full ${statusInfo.dot} ${bot.status === 'running' ? 'animate-pulse' : ''}`} />
          <span className="font-medium text-gray-900">{bot.name}</span>
        </div>
      </td>
      <td className="px-4 py-3 text-sm text-gray-500">
        <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${statusInfo.bg} ${statusInfo.color}`}>
          {statusInfo.text}
        </span>
      </td>
      <td className="px-4 py-3 text-sm text-gray-900 font-medium">{bot.schedules_added || 0}</td>
      <td className="px-4 py-3 text-sm">
        <span className={bot.last_added_count > 0 ? 'text-green-600 font-medium' : 'text-gray-400'}>
          +{bot.last_added_count || 0}
        </span>
      </td>
      <td className="px-4 py-3 text-sm text-gray-500">{formatInterval(bot.check_interval)}</td>
      <td className="px-4 py-3 text-xs text-gray-400">
        {bot.last_check_at ? formatTime(bot.last_check_at) : '-'}
      </td>
      <td className="px-4 py-3">
        <div className="flex items-center gap-1">
          <button
            onClick={() => onSync(bot.id)}
            disabled={syncing === bot.id}
            className="p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors disabled:opacity-50"
            title="전체 동기화"
          >
            {syncing === bot.id ? (
              <RefreshCw size={16} className="animate-spin" />
            ) : (
              <Download size={16} />
            )}
          </button>
          <button
            onClick={() => onToggle(bot.id, bot.status, bot.name)}
            className={`p-1.5 rounded transition-colors ${
              bot.status === 'running'
                ? 'text-gray-400 hover:text-red-600 hover:bg-red-50'
                : 'text-gray-400 hover:text-green-600 hover:bg-green-50'
            }`}
            title={bot.status === 'running' ? '정지' : '시작'}
          >
            {bot.status === 'running' ? <Square size={16} /> : <Play size={16} />}
          </button>
        </div>
      </td>
    </motion.tr>
  );
});

/**
 * 테이블 래퍼
 */
export const BotTable = ({ children }) => (
  <div className="overflow-x-auto">
    <table className="w-full table-fixed">
      <thead>
        <tr className="border-b border-gray-200 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
          <th className="px-4 py-3 w-[28%]">이름</th>
          <th className="px-4 py-3 w-[10%]">상태</th>
          <th className="px-4 py-3 w-[10%]">총 추가</th>
          <th className="px-4 py-3 w-[10%]">최근</th>
          <th className="px-4 py-3 w-[10%]">간격</th>
          <th className="px-4 py-3 w-[20%]">마지막 업데이트</th>
          <th className="px-4 py-3 w-[12%]">액션</th>
        </tr>
      </thead>
      <tbody>{children}</tbody>
    </table>
  </div>
);

// 기본 카드 (호환성 유지)
const BotCard = BotMiniCard;

export default BotCard;
