import { useState, useEffect, useCallback } from 'react';
import { Loader2 } from 'lucide-react';
import { getShowcase, uninstallSkill } from '@/lib/skillhubApi';
import { t } from '@/lib/i18n';
import SkillCardGrid from './SkillCardGrid';
import type { InstalledSkill, SkillHubSkill } from './types';

interface ShowcaseTabProps {
  category: string;
  installedSlugs: Set<string>;
  installedSkills: InstalledSkill[];
  onInstall: (slug: string) => void;
  onUninstalled?: () => void;
  onLoadingChange?: (loading: boolean) => void;
}

function installedToRow(skills: InstalledSkill[]): SkillHubSkill[] {
  return skills.map((s) => ({
    name: s.name || s.slug,
    slug: s.slug,
    description: `v${s.version} · ${s.source}`,
    version: s.version,
    author: '',
    tags: [],
    downloads: null,
    stars: null,
    created_at: s.installed_at ? String(s.installed_at) : null,
    updated_at: null,
    profile_url: null,
    zip_url: s.zip_url,
    sha256: s.sha256,
  }));
}

export default function ShowcaseTab({
  category,
  installedSlugs,
  installedSkills,
  onInstall,
  onUninstalled,
  onLoadingChange,
}: ShowcaseTabProps) {
  const [skills, setSkills] = useState<SkillHubSkill[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [uninstallingSlug, setUninstallingSlug] = useState<string | null>(null);
  const [resultMsg, setResultMsg] = useState<string | null>(null);

  const updateLoading = useCallback((val: boolean) => {
    setLoading(val);
    onLoadingChange?.(val);
  }, [onLoadingChange]);

  const fetchShowcase = useCallback(async (cat: string) => {
    if (cat === 'installed') {
      setSkills(installedToRow(installedSkills));
      updateLoading(false);
      setError(null);
      return;
    }

    updateLoading(true);
    setError(null);
    try {
      const resp = await getShowcase(cat);
      setSkills(resp.skills);
    } catch (err) {
      setError(err instanceof Error ? err.message : t('skillhub.load_failed'));
    } finally {
      updateLoading(false);
    }
  }, [installedSkills, updateLoading]);

  useEffect(() => {
    fetchShowcase(category);
  }, [category, fetchShowcase]);

  const handleUninstall = async (slug: string) => {
    setUninstallingSlug(slug);
    setResultMsg(null);
    try {
      const result = await uninstallSkill(slug);
      setResultMsg(result.message);
      if (category === 'installed') {
        onUninstalled?.();
      } else {
        onUninstalled?.();
      }
    } catch (err) {
      setResultMsg(err instanceof Error ? err.message : t('skillhub.load_failed'));
    } finally {
      setUninstallingSlug(null);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
      {resultMsg && (
        <div
          className="p-3 rounded-lg text-xs shrink-0 mb-4"
          style={{
            background: resultMsg.toLowerCase().includes('fail')
              ? 'rgba(239, 68, 68, 0.1)'
              : 'rgba(0, 230, 138, 0.1)',
            color: resultMsg.toLowerCase().includes('fail')
              ? 'var(--color-status-error)'
              : 'var(--color-status-success)',
          }}
        >
          {resultMsg}
        </div>
      )}

      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin" style={{ color: 'var(--pc-accent)' }} />
        </div>
      ) : error ? (
        <div
          className="p-8 text-center"
          style={{ background: '#FFFFFF', border: '1px solid rgba(0, 0, 0, 0.08)', borderRadius: 12 }}
        >
          <p style={{ color: 'var(--color-status-error)' }}>{error}</p>
          <button
            onClick={() => fetchShowcase(category)}
            className="btn-electric mt-4 px-4 py-2 text-sm font-medium"
          >
            {t('skillhub.retry')}
          </button>
        </div>
      ) : (
        <SkillCardGrid
          skills={skills}
          installedSlugs={installedSlugs}
          installingSlug={null}
          onInstall={onInstall}
          isInstalledMode={category === 'installed'}
          onUninstall={category === 'installed' ? handleUninstall : undefined}
          uninstallingSlug={uninstallingSlug}
        />
      )}
    </div>
  );
}
