import { useState, useRef, useEffect } from 'react';
import { Plus, Loader2 } from 'lucide-react';
import { t } from '@/lib/i18n';
import { useSkills } from '@/hooks/useApi';
import { toggleSkill as toggleSkillApi } from '@/lib/api';
import { assetBasePath } from '@/lib/basePath';
import type { Skill } from '@/types/api';

function SkillSwitch({
  enabled,
  loading,
  onToggle,
}: {
  enabled: boolean;
  loading: boolean;
  onToggle: () => void;
}) {
  return (
    <button
      onClick={onToggle}
      disabled={loading}
      className="relative w-10 h-6 rounded-full transition-colors disabled:opacity-50 flex-shrink-0"
      style={{
        background: enabled ? 'var(--pc-accent)' : 'var(--pc-border)',
      }}
      aria-pressed={enabled}
      aria-label={enabled ? t('skills.enabled') : t('skills.disabled')}
    >
      {loading ? (
        <Loader2 className="absolute top-1 left-1 w-4 h-4 animate-spin text-white" />
      ) : (
        <span
          className="absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform"
          style={{
            transform: enabled ? 'translateX(16px)' : 'translateX(0)',
          }}
        />
      )}
    </button>
  );
}

function SkillCard({
  skill,
  isToggling,
  onToggle,
}: {
  skill: Skill;
  isToggling: boolean;
  onToggle: () => void;
}) {
  const descRef = useRef<HTMLParagraphElement>(null);
  const [isTruncated, setIsTruncated] = useState(false);
  const [showTooltip, setShowTooltip] = useState(false);

  useEffect(() => {
    requestAnimationFrame(() => {
      if (descRef.current) {
        setIsTruncated(descRef.current.scrollHeight > descRef.current.clientHeight);
      }
    });
  }, [skill.description]);

  return (
    <div
      style={{
        width: 326,
        height: 140,
        padding: 16,
        background: '#F6F6F6',
        borderRadius: 6,
        boxSizing: 'border-box',
      }}
    >
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          height: 20,
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0, flex: 1 }}>
          <img
            src={`${assetBasePath}/icons/skill-icon.svg`}
            alt="skill"
            width={20}
            height={20}
            style={{ flexShrink: 0 }}
          />
          <span
            style={{
              fontSize: 14,
              color: 'var(--pc-text-primary)',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {skill.name}
          </span>
        </div>
        <SkillSwitch
          enabled={skill.enabled}
          loading={isToggling}
          onToggle={onToggle}
        />
      </div>

      <div
        className="relative"
        onMouseEnter={() => isTruncated && setShowTooltip(true)}
        onMouseLeave={() => setShowTooltip(false)}
      >
        <p
          ref={descRef}
          style={{
            width: 294,
            height: 40,
            fontSize: 14,
            color: 'var(--pc-text-muted)',
            margin: 0,
            marginTop: 8,
            lineHeight: '20px',
            overflow: 'hidden',
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical',
          }}
        >
          {skill.description}
        </p>
        {isTruncated && showTooltip && (
          <div
            className="absolute z-50 left-0 top-full mt-1 p-2 rounded-md text-xs whitespace-pre-wrap max-w-[300px] shadow-lg border"
            style={{
              background: '#ffffff',
              color: 'var(--pc-text-primary)',
              borderColor: 'var(--pc-border)',
            }}
          >
            {skill.description}
          </div>
        )}
      </div>

      <div style={{ marginTop: 8 }}>
        <span
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            height: 24,
            paddingLeft: 8,
            paddingRight: 8,
            fontSize: 12,
            color: 'var(--pc-text-secondary)',
            background: '#E6E6E6',
            borderRadius: 4,
            boxSizing: 'border-box',
          }}
        >
          {skill.tags?.includes('open-skills') ? 'Open Skills' : '内置'}
        </span>
      </div>
    </div>
  );
}

export default function Skills() {
  const { data: skills, loading, error, refetch } = useSkills();
  const [toggling, setToggling] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [isSearchFocused, setIsSearchFocused] = useState(false);

  const handleToggle = async (skillName: string, currentEnabled: boolean) => {
    setToggling(skillName);
    try {
      await toggleSkillApi(skillName, !currentEnabled);
      refetch();
    } catch (err) {
      console.error('Failed to toggle skill:', err);
    } finally {
      setToggling(null);
    }
  };

  const filtered = (skills || []).filter((skill) => {
    if (!searchQuery) return true;
    const q = searchQuery.toLowerCase();
    return (
      skill.name.toLowerCase().includes(q) ||
      skill.description.toLowerCase().includes(q)
    );
  });

  if (loading) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 200 }}>
        <Loader2 className="h-8 w-8 animate-spin" style={{ color: 'var(--pc-accent)' }} />
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ textAlign: 'center', padding: 24 }}>
        <p style={{ color: 'var(--pc-text-muted)' }}>{t('skills.empty')}</p>
      </div>
    );
  }

  return (
    <div
      style={{
        maxWidth: 1040,
        width: '100%',
        padding: '0 24px',
        boxSizing: 'border-box',
        marginTop: 0,
        marginBottom: 0,
      }}
    >
      <div
        style={{
          width: 992,
          height: 36,
          display: 'flex',
          alignItems: 'center',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <span style={{ fontSize: 14, color: 'var(--pc-text-primary)', fontWeight: 500 }}>
            已安装（{skills?.length || 0}）
          </span>
          <span style={{ fontSize: 14, color: 'var(--pc-accent)', fontWeight: 500 }}>
            技能市场
          </span>
        </div>

        <div style={{ flex: 1 }} />

        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div
            style={{
              width: 236,
              height: 36,
              background: isSearchFocused ? '#FFFFFF' : '#E6E6E6',
              borderRadius: 4,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              paddingLeft: 10,
              paddingRight: 10,
              gap: 6,
              boxSizing: 'border-box',
              border: isSearchFocused ? '2px solid #3790FA' : '2px solid transparent',
              transition: 'all 0.2s ease',
            }}
          >
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 6,
                justifyContent: 'flex-start',
                width: isSearchFocused || searchQuery ? '100%' : 'auto',
                transition: 'all 0.2s ease',
              }}
            >
              <img
                src={`${assetBasePath}/icons/search.svg`}
                alt="search"
                width={14}
                height={14}
                style={{ flexShrink: 0 }}
              />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onFocus={() => setIsSearchFocused(true)}
                onBlur={() => setIsSearchFocused(false)}
                placeholder="搜索"
                className="placeholder-[#A6A6A6]"
                style={{
                  border: 'none',
                  outline: 'none',
                  background: 'transparent',
                  fontSize: 14,
                  color: 'var(--pc-text-primary)',
                  width: isSearchFocused || searchQuery ? '100%' : 40,
                  padding: 0,
                  textAlign: 'left',
                  transition: 'all 0.2s ease',
                }}
              />
            </div>
          </div>

          <button
            style={{
              width: 80,
              height: 36,
              background: '#E6E6E6',
              border: 'none',
              borderRadius: 4,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 4,
              cursor: 'pointer',
              color: 'var(--pc-text-primary)',
              fontSize: 14,
              boxSizing: 'border-box',
            }}
          >
            <Plus size={14} />
            <span>添加</span>
          </button>
        </div>
      </div>

      <div
        style={{
          width: 992,
          display: 'flex',
          flexWrap: 'wrap',
          gap: 7,
          marginTop: 8,
        }}
      >
        {filtered.length === 0 ? (
          <div
            style={{
              width: 992,
              textAlign: 'center',
              padding: '48px 0',
              color: 'var(--pc-text-muted)',
              fontSize: 14,
            }}
          >
            {t('skills.empty')}
          </div>
        ) : (
          filtered.map((skill) => (
            <SkillCard
              key={skill.name}
              skill={skill}
              isToggling={toggling === skill.name}
              onToggle={() => handleToggle(skill.name, skill.enabled)}
            />
          ))
        )}
      </div>
    </div>
  );
}
