import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Package, Wrench, Loader2, Box, Shield, X } from 'lucide-react';
import apiClient from '../../api/client';

interface Toolset {
  toolset_id: string;
  name: string;
  description?: string;
  tools: string[];
  is_system: boolean;
  category: string;
}

export function ToolSettings() {
  const { t } = useTranslation();
  const [toolsets, setToolsets] = useState<Toolset[]>([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<Toolset | null>(null);

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

  const fetchToolsets = async () => {
    try {
      setLoading(true);
      const res = await apiClient.get('/api/v1/resource/custom-toolset');
      setToolsets(res.data.toolsets || []);
    } catch (err) {
      console.error('Failed to fetch toolsets:', err);
    } finally {
      setLoading(false);
    }
  };

  const systemToolsets = toolsets.filter(ts => ts.is_system);
  const userToolsets = toolsets.filter(ts => !ts.is_system);

  return (
    <div className="max-w-4xl space-y-6">
      <div>
        <div className="flex items-center gap-2 mb-1">
          <Wrench size={16} className="text-accent" />
          <h3 className="text-lg font-bold text-text-primary">
            {t('plugin.toolManagement')}
          </h3>
        </div>
        <p className="text-sm text-text-muted">{t('plugin.toolDesc')}</p>
      </div>

      {loading ? (
        <div className="flex flex-col items-center justify-center py-12 text-text-muted">
          <Loader2 size={24} className="animate-spin mb-3" />
          <span className="text-sm">{t('common.loading')}</span>
        </div>
      ) : toolsets.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-12 text-text-muted">
          <Box size={32} className="mb-3 opacity-40" />
          <span className="text-sm">{t('plugin.toolsetEmpty')}</span>
        </div>
      ) : (
        <>
          {systemToolsets.length > 0 && (
            <ToolsetGroup
              title={t('plugin.systemToolsets')}
              toolsets={systemToolsets}
              onSelect={setSelected}
            />
          )}
          {userToolsets.length > 0 && (
            <ToolsetGroup
              title={t('plugin.userToolsets')}
              toolsets={userToolsets}
              onSelect={setSelected}
            />
          )}
        </>
      )}

      {selected && (
        <ToolsetModal toolset={selected} onClose={() => setSelected(null)} />
      )}
    </div>
  );
}
/* PLACEHOLDER_TOOLSET_GROUP */

function ToolsetGroup({
  title,
  toolsets,
  onSelect,
}: {
  title: string;
  toolsets: Toolset[];
  onSelect: (ts: Toolset) => void;
}) {
  const { t } = useTranslation();
  return (
    <div>
      <h4 className="text-sm font-semibold text-text-secondary mb-3">
        {title}
      </h4>
      <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
        {toolsets.map((ts) => (
          <button
            key={ts.toolset_id}
            onClick={() => onSelect(ts)}
            className="relative flex flex-col items-start p-4 bg-bg-card border border-border-primary rounded-xl hover:border-accent/40 hover:shadow-sm transition-all text-left cursor-pointer"
          >
            {ts.is_system && (
              <span className="absolute top-2 right-2 text-[10px] font-medium px-1.5 py-0.5 rounded bg-accent/10 text-accent">
                {t('plugin.toolsetSystem')}
              </span>
            )}
            <div className="w-9 h-9 rounded-lg bg-accent-light flex items-center justify-center mb-2">
              {ts.is_system ? (
                <Shield size={16} className="text-accent" />
              ) : (
                <Package size={16} className="text-accent" />
              )}
            </div>
            <span className="text-sm font-medium text-text-primary">
              {ts.name}
            </span>
            {ts.description && (
              <span className="text-[11px] text-text-muted mt-0.5 line-clamp-2">
                {ts.description}
              </span>
            )}
            <span className="text-[11px] text-text-muted mt-1">
              {t('plugin.toolsetCount', { count: ts.tools.length })}
            </span>
          </button>
        ))}
      </div>
    </div>
  );
}
/* PLACEHOLDER_TOOLSET_MODAL */

function ToolsetModal({
  toolset,
  onClose,
}: {
  toolset: Toolset;
  onClose: () => void;
}) {
  const { t } = useTranslation();
  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40"
      onClick={onClose}
    >
      <div
        className="bg-bg-card border border-border-primary rounded-2xl shadow-lg w-full max-w-md mx-4"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-5 py-4 border-b border-border-primary">
          <div>
            <h4 className="text-sm font-bold text-text-primary">
              {toolset.name}
            </h4>
            {toolset.description && (
              <p className="text-[11px] text-text-muted mt-0.5">
                {toolset.description}
              </p>
            )}
          </div>
          <button
            onClick={onClose}
            className="p-1 rounded hover:bg-bg-secondary transition-colors"
          >
            <X size={16} className="text-text-muted" />
          </button>
        </div>
        <div className="px-5 py-4 space-y-2 max-h-80 overflow-y-auto">
          <p className="text-xs font-medium text-text-secondary mb-2">
            {t('plugin.toolsetTools')}
          </p>
          {toolset.tools.map((tool) => (
            <div
              key={tool}
              className="flex items-center gap-2.5 p-2.5 bg-bg-secondary rounded-lg"
            >
              <Package size={14} className="text-accent shrink-0" />
              <span className="text-sm text-text-primary">{tool}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}