import { useEffect, useMemo, useRef, useState } from 'react';
import { Cpu, Check, Plus, RefreshCw, Trash2, Pencil, Eye } from 'lucide-react';
import { useLocale } from '@/lib/i18n';
import {
  loadTrialModels,
  deleteModelConfiguration,
  loadConfiguredModels,
  saveModelConfiguration,
  updateModelConfiguration,
  type ModelInfo,
} from '@/lib/models';
import { PROVIDER_PRESETS } from '@/lib/providerPresets';

export default function ModelSwitch() {
  const { t, locale } = useLocale();
  const [configuredModels, setConfiguredModels] = useState<ModelInfo[]>([]);
  const [trialModels, setTrialModels] = useState<ModelInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [success, setSuccess] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [provider, setProvider] = useState(PROVIDER_PRESETS[0]?.providers[0]?.id ?? 'openrouter');
  const [model, setModel] = useState('');
  const [apiKey, setApiKey] = useState('');
  const [baseUrl, setBaseUrl] = useState('');
  const [editingTarget, setEditingTarget] = useState<{ provider: string; model: string } | null>(null);
  const [viewingModelKey, setViewingModelKey] = useState<string | null>(null);
  const editorCardRef = useRef<HTMLDivElement | null>(null);

  const providerOptions = useMemo(
    () =>
      PROVIDER_PRESETS.flatMap((tier) =>
        tier.providers.map((item) => ({
          id: item.id,
          label: item.labelZh,
        })),
      ),
    [],
  );

  const apiKeyPlaceholder = useMemo(() => {
    if (['qwen', 'qwen-intl', 'qwen-us', 'dashscope', 'dashscope-intl', 'dashscope-us'].includes(provider)) {
      return t('model.qwen_api_key_hint');
    }
    if (['qwen-code', 'qwen-oauth'].includes(provider)) {
      return t('model.qwen_oauth_hint');
    }
    return t('model.key_optional_hint');
  }, [provider, locale]);

  const baseUrlPlaceholder = useMemo(() => {
    if (provider === 'qwen' || provider === 'qwen-intl' || provider === 'qwen-us') {
      return t('model.base_url_hint_qwen');
    }
    return t('model.base_url_hint_openai');
  }, [provider, locale]);

  const fetchConfiguredModels = async (showRefreshing = false) => {
    if (showRefreshing) setRefreshing(true);
    setLoading(!showRefreshing);
    try {
      const [configured, trial] = await Promise.all([loadConfiguredModels(), loadTrialModels()]);
      setConfiguredModels(configured);
      setTrialModels(trial);
    } catch {
      setConfiguredModels([]);
      setTrialModels([]);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  const handleSave = async () => {
    if (!provider.trim() || !model.trim()) {
      setError(t('model.provider_model_required'));
      return;
    }
    setSaving(true);
    setError(null);
    setSuccess(null);
    try {
      if (editingTarget) {
        await updateModelConfiguration(editingTarget, {
          provider,
          model,
          apiKey: apiKey.trim() || undefined,
          baseUrl: baseUrl.trim() || undefined,
          label: model.trim(),
        });
        setSuccess(t('model.update_sync_success'));
      } else {
        await saveModelConfiguration({
          provider,
          model,
          apiKey: apiKey.trim() || undefined,
          baseUrl: baseUrl.trim() || undefined,
          label: model.trim(),
        });
        setSuccess(t('model.add_remote_success'));
      }
      setModel('');
      setApiKey('');
      setBaseUrl('');
      setEditingTarget(null);
      await fetchConfiguredModels();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : t('model.save_failed'));
    } finally {
      setSaving(false);
    }
  };

  const handleEdit = (configuredModel: ModelInfo) => {
    if (configuredModel.provider.startsWith('custom:')) {
      setProvider('custom');
      setBaseUrl(configuredModel.provider.slice('custom:'.length));
    } else {
      setProvider(configuredModel.provider);
      setBaseUrl(configuredModel.baseUrl ?? '');
    }
    setModel(configuredModel.value);
    setApiKey(configuredModel.apiKey ?? '');
    setEditingTarget({ provider: configuredModel.provider, model: configuredModel.value });
    setError(null);
    setSuccess(null);
    editorCardRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const cancelEdit = () => {
    setEditingTarget(null);
    setModel('');
    setApiKey('');
    setBaseUrl('');
  };

  const handleDelete = async (configuredModel: ModelInfo) => {
    setError(null);
    setSuccess(null);
    await deleteModelConfiguration({
      provider: configuredModel.provider,
      model: configuredModel.value,
    });
    setSuccess(t('model.deleted'));
    await fetchConfiguredModels();
  };

  useEffect(() => {
    void fetchConfiguredModels();
  }, []);

  return (
    <div className="p-6 space-y-6 animate-fade-in">
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          <Cpu className="h-5 w-5" style={{ color: 'var(--pc-accent)' }} />
          <h2 className="text-sm font-semibold uppercase tracking-wider" style={{ color: 'var(--pc-text-primary)' }}>
            {t('modelswitch.title')} ({configuredModels.length})
          </h2>
        </div>
        <button
          type="button"
          onClick={() => void fetchConfiguredModels(true)}
          disabled={refreshing}
          className="btn-secondary flex items-center gap-2 px-3 py-1.5 text-xs rounded-[6px]"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${refreshing ? 'animate-spin' : ''}`} />
          {t('common.refresh')}
        </button>
      </div>

      <div ref={editorCardRef} className="card card-radius-6 p-5 space-y-4">
        <h3 className="text-[12px] font-semibold uppercase tracking-wider" style={{ color: 'var(--pc-text-faint)' }}>
          {editingTarget ? t('model.edit_config') : t('model.add_config')}
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-1">
            <label className="text-xs" style={{ color: 'var(--pc-text-secondary)' }}>Provider</label>
            <select
              value={provider}
              onChange={(e) => setProvider(e.target.value)}
              className="w-full rounded-md border px-3 py-2 text-sm"
              style={{ borderColor: 'var(--pc-border)', background: 'var(--pc-bg-base)', color: 'var(--pc-text-primary)' }}
            >
              {providerOptions.map((item) => (
                <option key={item.id} value={item.id}>
                  {item.label} ({item.id})
                </option>
              ))}
            </select>
          </div>
          <div className="space-y-1">
            <label className="text-xs" style={{ color: 'var(--pc-text-secondary)' }}>Model</label>
            <input
              value={model}
              onChange={(e) => setModel(e.target.value)}
              placeholder={t('model.model_placeholder')}
              className="w-full rounded-md border px-3 py-2 text-sm"
              style={{ borderColor: 'var(--pc-border)', background: 'var(--pc-bg-base)', color: 'var(--pc-text-primary)' }}
            />
          </div>
          <div className="space-y-1">
            <label className="text-xs" style={{ color: 'var(--pc-text-secondary)' }}>API Key</label>
            <input
              value={apiKey}
              onChange={(e) => setApiKey(e.target.value)}
              placeholder={apiKeyPlaceholder}
              className="w-full rounded-md border px-3 py-2 text-sm"
              style={{ borderColor: 'var(--pc-border)', background: 'var(--pc-bg-base)', color: 'var(--pc-text-primary)' }}
            />
          </div>
          <div className="space-y-1">
            <label className="text-xs" style={{ color: 'var(--pc-text-secondary)' }}>Base URL</label>
            <input
              value={baseUrl}
              onChange={(e) => setBaseUrl(e.target.value)}
              placeholder={baseUrlPlaceholder}
              className="w-full rounded-md border px-3 py-2 text-sm"
              style={{ borderColor: 'var(--pc-border)', background: 'var(--pc-bg-base)', color: 'var(--pc-text-primary)' }}
            />
          </div>
        </div>

        {success && <div className="text-sm" style={{ color: 'var(--color-status-success)' }}>{success}</div>}
        {error && <div className="text-sm" style={{ color: 'var(--color-status-error)' }}>{error}</div>}

        <div className="flex justify-end gap-2">
          {editingTarget && (
            <button
              type="button"
              onClick={cancelEdit}
              disabled={saving}
              className="btn-secondary px-4 py-2 text-sm rounded-[6px]"
            >
              {t('model.cancel_edit')}
            </button>
          )}
          <button
            type="button"
            onClick={() => void handleSave()}
            disabled={saving}
            className="btn-electric flex items-center gap-2 px-4 py-2 text-sm rounded-[6px]"
          >
            <Plus className="h-4 w-4" />
            {saving ? t('model.saving') : editingTarget ? t('model.save_edit_sync') : t('model.add_write_remote')}
          </button>
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center h-40">
          <div className="h-8 w-8 border-2 rounded-full animate-spin" style={{ borderColor: 'var(--pc-border)', borderTopColor: 'var(--pc-accent)' }} />
        </div>
      ) : (
        <>
          <div>
            <h3 className="text-[10px] font-semibold uppercase tracking-wider mb-3" style={{ color: 'var(--pc-text-faint)' }}>
              {t('agent.model_selector_configured')} ({configuredModels.length})
            </h3>
            {configuredModels.length === 0 ? (
              <div className="card card-radius-6 p-5 text-sm" style={{ color: 'var(--pc-text-muted)' }}>
                {t('agent.model_selector_no_configured')}
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                {configuredModels.map((configuredModel) => (
                  <div key={`configured-${configuredModel.provider}-${configuredModel.value}`} className="card card-radius-6 p-5">
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <h4 className="text-sm font-semibold truncate" style={{ color: 'var(--pc-text-primary)' }}>
                          {configuredModel.label}
                        </h4>
                        <p className="text-sm mt-1" style={{ color: 'var(--pc-text-muted)' }}>
                          {configuredModel.description ?? t('model.current_model')}
                        </p>
                        <p className="text-xs mt-1 font-mono" style={{ color: 'var(--pc-text-faint)' }}>
                          {configuredModel.provider}
                        </p>
                      </div>
                      <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-semibold border" style={{ color: 'var(--color-status-success)', borderColor: 'rgba(0,230,138,0.2)', background: 'rgba(0,230,138,0.06)' }}>
                        <Check className="h-3 w-3" />
                        {t('modelswitch.status_active')}
                      </span>
                    </div>
                    <div className="mt-3 flex items-center gap-2">
                      <button
                        type="button"
                        onClick={() => {
                          const key = `${configuredModel.provider}::${configuredModel.value}`;
                          setViewingModelKey((prev) => (prev === key ? null : key));
                        }}
                        className="btn-secondary flex items-center gap-1 px-2.5 py-1 text-xs rounded-[6px]"
                      >
                        <Eye className="h-3.5 w-3.5" />
                        {t('model.view')}
                      </button>
                      <button
                        type="button"
                        onClick={() => handleEdit(configuredModel)}
                        className="btn-secondary flex items-center gap-1 px-2.5 py-1 text-xs rounded-[6px]"
                      >
                        <Pencil className="h-3.5 w-3.5" />
                        {t('common.edit')}
                      </button>
                      <button
                        type="button"
                        onClick={() => void handleDelete(configuredModel)}
                        className="btn-secondary flex items-center gap-1 px-2.5 py-1 text-xs rounded-[6px]"
                        style={{ color: 'var(--color-status-error)' }}
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                        {t('common.delete')}
                      </button>
                    </div>
                    {viewingModelKey === `${configuredModel.provider}::${configuredModel.value}` && (
                      <div className="mt-3 text-xs space-y-1" style={{ color: 'var(--pc-text-secondary)' }}>
                        <div>Provider: <span className="font-mono">{configuredModel.provider}</span></div>
                        <div>Model: <span className="font-mono">{configuredModel.value}</span></div>
                        <div>Base URL: <span className="font-mono">{configuredModel.baseUrl || t('model.not_set')}</span></div>
                        <div>API Key: <span className="font-mono">{configuredModel.apiKey || t('model.not_saved_locally')}</span></div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>

          <div>
            <h3 className="text-[10px] font-semibold uppercase tracking-wider mb-3" style={{ color: 'var(--pc-text-faint)' }}>
              {t('agent.model_selector_trial')} ({trialModels.length})
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
              {trialModels.map((trialModel) => (
                <div key={`trial-${trialModel.provider}-${trialModel.value}`} className="card card-radius-6 p-5">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <h4 className="text-sm font-semibold truncate" style={{ color: 'var(--pc-text-primary)' }}>
                        {trialModel.label}
                      </h4>
                      <p className="text-sm mt-1" style={{ color: 'var(--pc-text-muted)' }}>
                        {trialModel.description}
                      </p>
                      <p className="text-xs mt-1 font-mono" style={{ color: 'var(--pc-text-faint)' }}>
                        {trialModel.provider}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
