// frontend/src/pages/Settings.jsx
import { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext.jsx';
import { useT } from '../i18n/translations.js';
import { api } from '../context/AuthContext.jsx';
import { Card, Button, Input, Select } from '../components/ui/index.jsx';
import { CheckCircle2, XCircle, AlertCircle, Eye, EyeOff, ImageIcon, Upload, Trash2, RefreshCw } from 'lucide-react';
import toast from 'react-hot-toast';

const PROVIDERS = [
  { id: 'claude', name: 'Anthropic Claude', models: ['claude-opus-4-5', 'claude-sonnet-4-5', 'claude-haiku-4-5-20251001'] },
  { id: 'openai', name: 'OpenAI GPT', models: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo'] },
  { id: 'gemini', name: 'Google Gemini', models: ['gemini-1.5-pro', 'gemini-1.5-flash', 'gemini-2.0-flash'] },
];

export default function Settings() {
  const { user } = useAuth();
  const t = useT(user?.locale);
  const [tab, setTab] = useState('profile');
  const [profile, setProfile] = useState({});
  const [apiKeys, setApiKeys] = useState({});
  const [saving, setSaving] = useState(false);
  const [keyInputs, setKeyInputs] = useState({});
  const [showKeys, setShowKeys] = useState({});
  const [testing, setTesting] = useState({});
  const [codexStatus, setCodexStatus] = useState(null);
  const [codexAuthJson, setCodexAuthJson] = useState('');
  const [codexSaving, setCodexSaving] = useState(false);
  const [codexDisconnecting, setCodexDisconnecting] = useState(false);

  useEffect(() => {
    fetchProfile();
    if (user?.plan?.byok) fetchApiKeys();
    fetchCodexStatus();
  }, []);

  async function fetchCodexStatus() {
    try {
      const { data } = await api.get('/codex/status');
      setCodexStatus(data);
    } catch {}
  }

  async function connectChatGPT() {
    if (!codexAuthJson.trim()) {
      toast.error('Paste the contents of your auth.json file');
      return;
    }
    setCodexSaving(true);
    try {
      await api.post('/codex/connect', { authJson: codexAuthJson });
      toast.success('ChatGPT connected successfully!');
      setCodexAuthJson('');
      await fetchCodexStatus();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Failed to connect ChatGPT');
    } finally {
      setCodexSaving(false);
    }
  }

  async function disconnectChatGPT() {
    if (!confirm('Disconnect ChatGPT? Your credentials will be deleted and image generation will be disabled.')) return;
    setCodexDisconnecting(true);
    try {
      await api.delete('/codex/disconnect');
      toast.success('ChatGPT disconnected');
      await fetchCodexStatus();
    } catch {
      toast.error('Failed to disconnect');
    } finally {
      setCodexDisconnecting(false);
    }
  }

  async function fetchProfile() {
    try {
      const { data } = await api.get('/profile');
      setProfile(data);
    } catch {}
  }

  async function fetchApiKeys() {
    try {
      const { data } = await api.get('/profile/api-keys');
      const map = {};
      for (const k of data) map[k.provider] = k;
      setApiKeys(map);
    } catch {}
  }

  async function saveProfile() {
    setSaving(true);
    try {
      await api.put('/profile', {
        niche: profile.niche,
        brandName: profile.brand_name,
        targetAudience: profile.target_audience,
        tone: profile.tone,
        writingStyle: profile.writing_style,
        personality: profile.personality,
        avoidWords: typeof profile.avoid_words === 'string'
          ? profile.avoid_words.split(',').map(w => w.trim()).filter(Boolean)
          : profile.avoid_words,
        cta: profile.cta,
        examplePhrases: typeof profile.example_phrases === 'string'
          ? profile.example_phrases.split(',').map(w => w.trim()).filter(Boolean)
          : profile.example_phrases,
        scriptsPerDay: parseInt(profile.scripts_per_day) || undefined,
        postsPerDay: parseInt(profile.posts_per_day) || undefined,
        newsletterFreq: profile.newsletter_freq,
        outputTimezone: profile.output_timezone,
      });
      toast.success(t('settings.saved'));
    } catch {
      toast.error(t('common.error'));
    } finally {
      setSaving(false);
    }
  }

  async function saveApiKey(provider) {
    const key = keyInputs[provider];
    if (!key) return;
    setTesting(t_ => ({ ...t_, [provider]: 'saving' }));
    try {
      const model = keyInputs[`${provider}_model`] || PROVIDERS.find(p => p.id === provider)?.models[0];
      const { data } = await api.put(`/profile/api-keys/${provider}`, { apiKey: key, model });
      if (data.valid) toast.success('Key saved and verified ✓');
      else toast.error(`Key saved but test failed: ${data.error}`);
      setKeyInputs(k => ({ ...k, [provider]: '' }));
      fetchApiKeys();
    } catch {
      toast.error('Failed to save key');
    } finally {
      setTesting(t_ => ({ ...t_, [provider]: null }));
    }
  }

  async function testKey(provider) {
    setTesting(t_ => ({ ...t_, [provider]: 'testing' }));
    try {
      const { data } = await api.post(`/profile/api-keys/${provider}/test`);
      if (data.valid) toast.success('Connection successful ✓');
      else toast.error(`Test failed: ${data.error}`);
      fetchApiKeys();
    } catch {
      toast.error('Test failed');
    } finally {
      setTesting(t_ => ({ ...t_, [provider]: null }));
    }
  }

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-semibold text-gray-900">Settings</h1>

      {/* Tabs */}
      <div className="flex gap-1 bg-gray-100 p-1 rounded-xl w-fit">
        {[
          { id: 'profile', label: t('settings.profile') },
          { id: 'apikeys', label: t('settings.apiKeys') },
          { id: 'chatgpt', label: 'ChatGPT (Images)' },
        ].map(tab_ => (
          <button
            key={tab_.id}
            onClick={() => setTab(tab_.id)}
            className={`px-4 py-1.5 rounded-lg text-sm font-medium transition-all ${
              tab === tab_.id ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            {tab_.label}
          </button>
        ))}
      </div>

      {/* Profile tab */}
      {tab === 'profile' && (
        <Card className="p-6 space-y-5">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
            <Input
              label={t('settings.niche')}
              value={profile.niche || ''}
              onChange={e => setProfile(p => ({ ...p, niche: e.target.value }))}
              placeholder={t('settings.nichePlaceholder')}
            />
            <Input
              label={t('settings.brand')}
              value={profile.brand_name || ''}
              onChange={e => setProfile(p => ({ ...p, brand_name: e.target.value }))}
            />
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('settings.audience')}</label>
              <textarea
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
                rows={2}
                placeholder={t('settings.audiencePlaceholder')}
                value={profile.target_audience || ''}
                onChange={e => setProfile(p => ({ ...p, target_audience: e.target.value }))}
              />
            </div>
            <Select
              label={t('settings.tone')}
              value={profile.tone || ''}
              onChange={e => setProfile(p => ({ ...p, tone: e.target.value }))}
            >
              <option value="">Select tone…</option>
              {['Casual and conversational', 'Professional and authoritative', 'Educational and step-by-step', 'Energetic and motivational', 'Direct and no-nonsense', 'Storytelling and narrative', 'Humorous and entertaining'].map(t_ => (
                <option key={t_} value={t_}>{t_}</option>
              ))}
            </Select>
            <Input
              label={t('settings.writingStyle')}
              value={profile.writing_style || ''}
              onChange={e => setProfile(p => ({ ...p, writing_style: e.target.value }))}
              placeholder="e.g. short punchy sentences"
            />
            <Input
              label={t('settings.personality')}
              value={profile.personality || ''}
              onChange={e => setProfile(p => ({ ...p, personality: e.target.value }))}
              placeholder="e.g. expert friend who tells it straight"
            />
            <Input
              label={t('settings.avoidWords')}
              value={Array.isArray(profile.avoid_words) ? profile.avoid_words.join(', ') : (profile.avoid_words || '')}
              onChange={e => setProfile(p => ({ ...p, avoid_words: e.target.value }))}
              placeholder="leverage, synergy, game-changer"
            />
            <Input
              label={t('settings.cta')}
              value={profile.cta || ''}
              onChange={e => setProfile(p => ({ ...p, cta: e.target.value }))}
              placeholder="Like and subscribe for more"
            />
            <Select
              label={t('settings.timezone')}
              value={profile.output_timezone || 'UTC'}
              onChange={e => setProfile(p => ({ ...p, output_timezone: e.target.value }))}
            >
              {['UTC', 'Europe/Bucharest', 'Europe/London', 'America/New_York', 'America/Los_Angeles', 'Asia/Tokyo'].map(tz => (
                <option key={tz} value={tz}>{tz}</option>
              ))}
            </Select>
            <Select
              label="Newsletter frequency"
              value={profile.newsletter_freq || 'daily'}
              onChange={e => setProfile(p => ({ ...p, newsletter_freq: e.target.value }))}
            >
              <option value="daily">Daily</option>
              <option value="weekly">Weekly</option>
            </Select>
          </div>
          <div className="flex justify-end pt-2 border-t border-gray-100">
            <Button onClick={saveProfile} loading={saving}>{t('settings.save')}</Button>
          </div>
        </Card>
      )}

      {/* API Keys tab */}
      {tab === 'apikeys' && (
        <div className="space-y-4">
          {!user?.plan?.byok ? (
            <Card className="p-5">
              <div className="flex gap-3 items-start">
                <AlertCircle size={18} className="text-amber-500 flex-shrink-0 mt-0.5" />
                <p className="text-sm text-gray-600">{t('settings.starterNotice')}</p>
              </div>
            </Card>
          ) : (
            <>
              <p className="text-sm text-gray-500">{t('settings.byokNotice')}</p>
              {PROVIDERS.map(provider => {
                const existing = apiKeys[provider.id];
                const isLoading = testing[provider.id];
                return (
                  <Card key={provider.id} className="p-5">
                    <div className="flex items-center justify-between mb-4">
                      <h3 className="font-medium text-gray-900">{provider.name}</h3>
                      {existing ? (
                        <div className="flex items-center gap-2">
                          {existing.is_valid === true && <span className="flex items-center gap-1 text-xs text-emerald-600"><CheckCircle2 size={13} /> {t('settings.keyValid')}</span>}
                          {existing.is_valid === false && <span className="flex items-center gap-1 text-xs text-red-600"><XCircle size={13} /> {t('settings.keyInvalid')}</span>}
                          {existing.is_valid === null && <span className="flex items-center gap-1 text-xs text-gray-400"><AlertCircle size={13} /> Not tested</span>}
                          <Button size="sm" variant="ghost" onClick={() => testKey(provider.id)} loading={isLoading === 'testing'}>
                            {t('settings.testKey')}
                          </Button>
                        </div>
                      ) : (
                        <span className="text-xs text-gray-400">{t('settings.keyMissing')}</span>
                      )}
                    </div>

                    <div className="space-y-3">
                      <div className="relative">
                        <Input
                          label={`${provider.name} API Key`}
                          type={showKeys[provider.id] ? 'text' : 'password'}
                          value={keyInputs[provider.id] || ''}
                          onChange={e => setKeyInputs(k => ({ ...k, [provider.id]: e.target.value }))}
                          placeholder={existing ? 'Enter new key to replace…' : 'sk-ant-...'}
                        />
                        <button
                          type="button"
                          onClick={() => setShowKeys(s => ({ ...s, [provider.id]: !s[provider.id] }))}
                          className="absolute right-3 top-8 text-gray-400 hover:text-gray-600"
                        >
                          {showKeys[provider.id] ? <EyeOff size={14} /> : <Eye size={14} />}
                        </button>
                      </div>
                      <Select
                        label="Model"
                        value={keyInputs[`${provider.id}_model`] || provider.models[0]}
                        onChange={e => setKeyInputs(k => ({ ...k, [`${provider.id}_model`]: e.target.value }))}
                      >
                        {provider.models.map(m => <option key={m} value={m}>{m}</option>)}
                      </Select>
                      <Button
                        onClick={() => saveApiKey(provider.id)}
                        loading={isLoading === 'saving'}
                        disabled={!keyInputs[provider.id]}
                        size="sm"
                      >
                        Save key
                      </Button>
                    </div>
                  </Card>
                );
              })}
            </>
          )}
        </div>
      )}

      {/* ChatGPT (Codex) tab */}
      {tab === 'chatgpt' && (
        <div className="space-y-6">

          {/* Status card */}
          <Card className="p-6">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 bg-gray-900 rounded-xl flex items-center justify-center">
                <ImageIcon size={18} className="text-white" />
              </div>
              <div>
                <h3 className="font-semibold text-gray-900">ChatGPT Image Generation</h3>
                <p className="text-sm text-gray-500">Generates thumbnails and images using your own ChatGPT subscription via Codex CLI</p>
              </div>
              {codexStatus?.connected && (
                <span className="ml-auto flex items-center gap-1.5 text-sm font-medium text-emerald-600">
                  <CheckCircle2 size={15} /> Connected
                </span>
              )}
            </div>

            <div className="bg-amber-50 border border-amber-200 rounded-lg p-4 mb-5 text-sm text-amber-800">
              <strong>This integration is separate from text AI providers.</strong> When connected, image generation uses your ChatGPT subscription — not your Claude/OpenAI API keys.
            </div>

            {codexStatus?.connected ? (
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div className="bg-gray-50 rounded-lg p-3">
                    <div className="text-gray-500 text-xs mb-1">Connected since</div>
                    <div className="font-medium text-gray-900">
                      {codexStatus.connectedAt ? new Date(codexStatus.connectedAt).toLocaleDateString() : '—'}
                    </div>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-3">
                    <div className="text-gray-500 text-xs mb-1">Last used</div>
                    <div className="font-medium text-gray-900">
                      {codexStatus.lastUsedAt ? new Date(codexStatus.lastUsedAt).toLocaleDateString() : 'Never'}
                    </div>
                  </div>
                </div>

                {codexStatus.status === 'expired' && (
                  <div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700">
                    Your ChatGPT session has expired. Disconnect and reconnect with a fresh auth.json.
                  </div>
                )}

                <div className="flex gap-3">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={fetchCodexStatus}
                    className="flex items-center gap-2"
                  >
                    <RefreshCw size={13} /> Refresh status
                  </Button>
                  <Button
                    variant="danger"
                    size="sm"
                    loading={codexDisconnecting}
                    onClick={disconnectChatGPT}
                    className="flex items-center gap-2"
                  >
                    <Trash2 size={13} /> Disconnect ChatGPT
                  </Button>
                </div>
              </div>
            ) : (
              <div className="space-y-5">
                <div className="space-y-1">
                  <h4 className="font-medium text-gray-900 text-sm">How to connect</h4>
                  <ol className="text-sm text-gray-600 space-y-2 list-decimal list-inside">
                    <li>Install Codex CLI on your computer: <code className="bg-gray-100 px-1.5 py-0.5 rounded text-xs">npm install -g @openai/codex</code></li>
                    <li>Run <code className="bg-gray-100 px-1.5 py-0.5 rounded text-xs">codex login</code> — a browser window opens to authenticate with your ChatGPT account</li>
                    <li>Find the <code className="bg-gray-100 px-1.5 py-0.5 rounded text-xs">auth.json</code> file created at <code className="bg-gray-100 px-1.5 py-0.5 rounded text-xs">~/.codex/auth.json</code></li>
                    <li>Paste its entire contents below and click Connect</li>
                  </ol>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Contents of <code className="bg-gray-100 px-1 rounded">~/.codex/auth.json</code>
                  </label>
                  <textarea
                    value={codexAuthJson}
                    onChange={e => setCodexAuthJson(e.target.value)}
                    placeholder='{"accessToken": "...", "refreshToken": "..."}'
                    rows={6}
                    className="w-full font-mono text-xs border border-gray-200 rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none bg-gray-50"
                  />
                  <p className="text-xs text-gray-400 mt-1">
                    Your credentials are encrypted with AES-256 and never shared. Only used for image generation on your behalf.
                  </p>
                </div>

                <Button
                  onClick={connectChatGPT}
                  loading={codexSaving}
                  disabled={!codexAuthJson.trim()}
                  className="flex items-center gap-2"
                >
                  <Upload size={15} /> Connect ChatGPT
                </Button>
              </div>
            )}
          </Card>
        </div>
      )}
    </div>
  );
}
