import { useEffect, useCallback, useState } from 'react';
import { Loader2, Trash2 } from 'lucide-react';
import { listInstalled, uninstallSkill } from '@/lib/skillhubApi';
import type { InstalledSkill } from './types';

export default function InstalledTab() {
  const [skills, setSkills] = useState<InstalledSkill[]>([]);
  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 [confirmSlug, setConfirmSlug] = useState<string | null>(null);

  const fetchInstalled = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const resp = await listInstalled();
      setSkills(resp.skills);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load installed skills');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchInstalled();
  }, [fetchInstalled]);

  const handleUninstall = async (slug: string) => {
    setUninstallingSlug(slug);
    setResultMsg(null);
    setConfirmSlug(null);
    try {
      const result = await uninstallSkill(slug);
      setResultMsg(result.message);
      await fetchInstalled();
    } catch (err) {
      setResultMsg(err instanceof Error ? err.message : 'Uninstall failed');
    } finally {
      setUninstallingSlug(null);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin" style={{ color: 'var(--pc-accent)' }} />
      </div>
    );
  }

  if (error) {
    return (
      <div className="card card-radius-6 p-8 text-center">
        <p style={{ color: 'var(--color-status-error)' }}>{error}</p>
        <button
          onClick={fetchInstalled}
          className="btn-electric mt-4 px-4 py-2 text-sm font-medium"
        >
          Retry
        </button>
      </div>
    );
  }

  if (skills.length === 0) {
    return (
      <div className="card card-radius-6 p-8 text-center">
        <p style={{ color: 'var(--pc-text-muted)' }}>
          No skills installed yet. Browse the marketplace to find skills.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      {resultMsg && (
        <div
          className="p-3 rounded-lg text-xs"
          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>
      )}
      {skills.map((skill) => (
        <div key={skill.slug} className="card card-radius-6 p-4 flex items-center gap-4">
          <div className="min-w-0 flex-1">
            <h4
              className="text-sm font-semibold truncate"
              style={{ color: 'var(--pc-text-primary)' }}
            >
              {skill.name || skill.slug}
            </h4>
            <div
              className="flex items-center gap-3 text-xs mt-1"
              style={{ color: 'var(--pc-text-faint)' }}
            >
              <span>{skill.slug}</span>
              {skill.version && <span>v{skill.version}</span>}
              {skill.installed_at > 0 && (
                <span>{new Date(skill.installed_at * 1000).toLocaleDateString()}</span>
              )}
            </div>
          </div>
          {confirmSlug === skill.slug ? (
            <div className="flex items-center gap-1">
              <button
                onClick={() => handleUninstall(skill.slug)}
                disabled={uninstallingSlug === skill.slug}
                className="px-3 py-1.5 rounded-lg text-xs font-medium transition-all"
                style={{
                  background: 'rgba(239, 68, 68, 0.9)',
                  color: 'white',
                  border: 'none',
                  cursor: uninstallingSlug === skill.slug ? 'wait' : 'pointer',
                  opacity: uninstallingSlug === skill.slug ? 0.7 : 1,
                }}
              >
                {uninstallingSlug === skill.slug ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : '确认'}
              </button>
              <button
                onClick={() => setConfirmSlug(null)}
                disabled={uninstallingSlug === skill.slug}
                className="px-3 py-1.5 rounded-lg text-xs font-medium transition-all"
                style={{
                  color: 'var(--pc-text-faint)',
                  border: '1px solid rgba(0,0,0,0.1)',
                  background: 'transparent',
                  cursor: uninstallingSlug === skill.slug ? 'not-allowed' : 'pointer',
                }}
              >
                取消
              </button>
            </div>
          ) : (
            <button
              onClick={() => setConfirmSlug(skill.slug)}
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all"
              style={{
                color: 'var(--color-status-error)',
                border: '1px solid rgba(239, 68, 68, 0.2)',
                background: 'rgba(239, 68, 68, 0.06)',
                cursor: 'pointer',
              }}
            >
              <Trash2 className="h-3.5 w-3.5" />
              卸载
            </button>
          )}
        </div>
      ))}
    </div>
  );
}
