'use client';

import AdminShell from '@/components/AdminShell';
import { api } from '@/lib/api';
import { useEffect, useState, useCallback, useRef } from 'react';
import { Brain, Search, Check, Power, PowerOff, ChevronDown, Play, Loader2, Eye, MessageSquare, Video, Sparkles } from 'lucide-react';

const MODERATION_TYPES = [
  { key: 'text', label: 'Text Moderation', icon: MessageSquare, desc: 'Analyze post text, comments, and captions for policy violations' },
  { key: 'image', label: 'Image Moderation', icon: Eye, desc: 'Analyze uploaded images for inappropriate content (requires vision model)' },
  { key: 'video', label: 'Video Moderation', icon: Video, desc: 'Analyze video frames extracted from Quips (requires vision model)' },
];

interface ModelInfo {
  id: string;
  name: string;
  description?: string;
  pricing: { prompt: string; completion: string; image?: string };
  context_length: number;
  architecture?: Record<string, any>;
}

interface ModerationConfig {
  id: string;
  moderation_type: string;
  model_id: string;
  model_name: string;
  system_prompt: string;
  enabled: boolean;
  updated_at: string;
}

export default function AIModerationPage() {
  const [configs, setConfigs] = useState<ModerationConfig[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeType, setActiveType] = useState('text');

  const loadConfigs = useCallback(() => {
    setLoading(true);
    api.getAIModerationConfigs()
      .then((data) => setConfigs(data.configs || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

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

  const getConfig = (type: string) => configs.find(c => c.moderation_type === type);

  return (
    <AdminShell>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
          <Brain className="w-6 h-6" /> AI Moderation
        </h1>
        <p className="text-sm text-gray-500 mt-1">Configure AI models for content moderation via OpenRouter</p>
      </div>

      {/* Config Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        {MODERATION_TYPES.map((mt) => {
          const config = getConfig(mt.key);
          const Icon = mt.icon;
          return (
            <button
              key={mt.key}
              onClick={() => setActiveType(mt.key)}
              className={`card p-4 text-left transition-all ${
                activeType === mt.key ? 'ring-2 ring-brand-500 shadow-md' : 'hover:shadow-sm'
              }`}
            >
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-2">
                  <Icon className="w-5 h-5 text-gray-600" />
                  <span className="font-semibold text-gray-900 text-sm">{mt.label}</span>
                </div>
                {config?.enabled ? (
                  <span className="flex items-center gap-1 text-xs font-medium text-green-700 bg-green-100 px-2 py-0.5 rounded-full">
                    <Power className="w-3 h-3" /> On
                  </span>
                ) : (
                  <span className="flex items-center gap-1 text-xs font-medium text-gray-400 bg-gray-100 px-2 py-0.5 rounded-full">
                    <PowerOff className="w-3 h-3" /> Off
                  </span>
                )}
              </div>
              <p className="text-xs text-gray-400 mb-2">{mt.desc}</p>
              {config?.model_id ? (
                <p className="text-xs font-mono text-brand-600 truncate">{config.model_name || config.model_id}</p>
              ) : (
                <p className="text-xs text-gray-300 italic">No model selected</p>
              )}
            </button>
          );
        })}
      </div>

      {/* Active Config Editor */}
      <ConfigEditor
        key={activeType}
        moderationType={activeType}
        config={getConfig(activeType)}
        onSaved={loadConfigs}
      />
    </AdminShell>
  );
}

// ─── Config Editor for a single moderation type ─────────

function ConfigEditor({ moderationType, config, onSaved }: {
  moderationType: string;
  config?: ModerationConfig;
  onSaved: () => void;
}) {
  const [modelId, setModelId] = useState(config?.model_id || '');
  const [modelName, setModelName] = useState(config?.model_name || '');
  const [systemPrompt, setSystemPrompt] = useState(config?.system_prompt || '');
  const [enabled, setEnabled] = useState(config?.enabled || false);
  const [saving, setSaving] = useState(false);

  // Model picker
  const [showPicker, setShowPicker] = useState(false);
  const [models, setModels] = useState<ModelInfo[]>([]);
  const [modelsLoading, setModelsLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [capability, setCapability] = useState('');
  const searchTimer = useRef<any>(null);

  // Test
  const [testInput, setTestInput] = useState('');
  const [testResult, setTestResult] = useState<any>(null);
  const [testing, setTesting] = useState(false);

  const loadModels = useCallback((search?: string, cap?: string) => {
    setModelsLoading(true);
    api.listOpenRouterModels({ search, capability: cap })
      .then((data) => setModels(data.models || []))
      .catch(() => {})
      .finally(() => setModelsLoading(false));
  }, []);

  useEffect(() => {
    if (showPicker) loadModels(searchTerm || undefined, capability || undefined);
  }, [showPicker]);

  const onSearchChange = (val: string) => {
    setSearchTerm(val);
    if (searchTimer.current) clearTimeout(searchTimer.current);
    searchTimer.current = setTimeout(() => {
      loadModels(val || undefined, capability || undefined);
    }, 400);
  };

  const onCapabilityChange = (val: string) => {
    setCapability(val);
    loadModels(searchTerm || undefined, val || undefined);
  };

  const selectModel = (m: ModelInfo) => {
    setModelId(m.id);
    setModelName(m.name);
    setShowPicker(false);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await api.setAIModerationConfig({
        moderation_type: moderationType,
        model_id: modelId,
        model_name: modelName,
        system_prompt: systemPrompt,
        enabled,
      });
      onSaved();
    } catch (e: any) {
      alert(e.message);
    } finally {
      setSaving(false);
    }
  };

  const handleTest = async () => {
    if (!testInput.trim()) return;
    setTesting(true);
    setTestResult(null);
    try {
      const data = moderationType === 'text'
        ? { moderation_type: moderationType, content: testInput }
        : { moderation_type: moderationType, image_url: testInput };
      const res = await api.testAIModeration(data);
      setTestResult(res.result);
    } catch (e: any) {
      setTestResult({ error: e.message });
    } finally {
      setTesting(false);
    }
  };

  const isFree = (m: ModelInfo) => m.pricing.prompt === '0' || m.pricing.prompt === '0.0';
  const isVision = (m: ModelInfo) => {
    const modality = m.architecture?.modality;
    return typeof modality === 'string' && modality.includes('image');
  };

  return (
    <div className="space-y-4">
      {/* Model Selection */}
      <div className="card p-5">
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-semibold text-gray-900">
            {MODERATION_TYPES.find(t => t.key === moderationType)?.label} Configuration
          </h2>
          <label className="flex items-center gap-2 cursor-pointer">
            <span className="text-sm text-gray-500">Enabled</span>
            <button
              onClick={() => setEnabled(!enabled)}
              className={`relative w-10 h-6 rounded-full transition-colors ${enabled ? 'bg-green-500' : 'bg-gray-300'}`}
            >
              <span className={`absolute top-0.5 w-5 h-5 bg-white rounded-full shadow transition-transform ${enabled ? 'left-[18px]' : 'left-0.5'}`} />
            </button>
          </label>
        </div>

        {/* Selected Model */}
        <div className="mb-4">
          <label className="text-sm font-medium text-gray-600 block mb-1">Model</label>
          <div className="flex gap-2">
            <div
              onClick={() => setShowPicker(!showPicker)}
              className="flex-1 flex items-center justify-between px-3 py-2 border border-warm-300 rounded-lg cursor-pointer hover:bg-warm-50 transition-colors"
            >
              {modelId ? (
                <div>
                  <span className="text-sm font-medium text-gray-900">{modelName || modelId}</span>
                  <span className="text-xs text-gray-400 ml-2 font-mono">{modelId}</span>
                </div>
              ) : (
                <span className="text-sm text-gray-400">Click to select a model...</span>
              )}
              <ChevronDown className="w-4 h-4 text-gray-400" />
            </div>
          </div>
        </div>

        {/* Model Picker */}
        {showPicker && (
          <div className="mb-4 border border-warm-200 rounded-lg overflow-hidden">
            <div className="p-3 bg-warm-100 flex gap-2">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  placeholder="Search models..."
                  value={searchTerm}
                  onChange={(e) => onSearchChange(e.target.value)}
                  className="w-full pl-9 pr-3 py-2 text-sm border border-warm-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500"
                />
              </div>
              <select
                value={capability}
                onChange={(e) => onCapabilityChange(e.target.value)}
                className="text-sm border border-warm-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-brand-500"
              >
                <option value="">All Models</option>
                <option value="free">Free Only</option>
                <option value="vision">Vision Only</option>
              </select>
            </div>
            <div className="max-h-80 overflow-y-auto">
              {modelsLoading ? (
                <div className="p-4 text-center text-gray-400 text-sm flex items-center justify-center gap-2">
                  <Loader2 className="w-4 h-4 animate-spin" /> Loading models...
                </div>
              ) : models.length === 0 ? (
                <div className="p-4 text-center text-gray-400 text-sm">No models found</div>
              ) : (
                models.map((m) => (
                  <div
                    key={m.id}
                    onClick={() => selectModel(m)}
                    className={`px-3 py-2.5 border-b border-warm-100 cursor-pointer hover:bg-brand-50 transition-colors ${modelId === m.id ? 'bg-brand-50' : ''}`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2 min-w-0">
                        {modelId === m.id && <Check className="w-4 h-4 text-brand-600 flex-shrink-0" />}
                        <div className="min-w-0">
                          <div className="text-sm font-medium text-gray-900 truncate">{m.name}</div>
                          <div className="text-xs text-gray-400 font-mono truncate">{m.id}</div>
                        </div>
                      </div>
                      <div className="flex items-center gap-2 flex-shrink-0 ml-2">
                        {isVision(m) && (
                          <span className="text-xs bg-purple-100 text-purple-700 px-1.5 py-0.5 rounded font-medium">Vision</span>
                        )}
                        {isFree(m) ? (
                          <span className="text-xs bg-green-100 text-green-700 px-1.5 py-0.5 rounded font-medium">Free</span>
                        ) : (
                          <span className="text-xs text-gray-400">${m.pricing.prompt}/tok</span>
                        )}
                        <span className="text-xs text-gray-300">{(m.context_length / 1000).toFixed(0)}k ctx</span>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        )}

        {/* System Prompt */}
        <div className="mb-4">
          <label className="text-sm font-medium text-gray-600 block mb-1">
            System Prompt <span className="text-gray-400 font-normal">(leave blank for default)</span>
          </label>
          <textarea
            rows={5}
            value={systemPrompt}
            onChange={(e) => setSystemPrompt(e.target.value)}
            placeholder="Custom system prompt for this moderation type... Leave blank to use the built-in default."
            className="w-full text-sm border border-warm-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-brand-500 font-mono"
          />
        </div>

        {/* Save */}
        <div className="flex items-center justify-between">
          <div className="text-xs text-gray-400">
            {config?.updated_at && `Last updated: ${new Date(config.updated_at).toLocaleString()}`}
          </div>
          <button onClick={handleSave} disabled={saving} className="btn-primary text-sm flex items-center gap-1.5">
            <Sparkles className="w-4 h-4" /> {saving ? 'Saving...' : 'Save Configuration'}
          </button>
        </div>
      </div>

      {/* Test Panel */}
      <div className="card p-5">
        <h3 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
          <Play className="w-4 h-4" /> Test Moderation
        </h3>
        <p className="text-xs text-gray-400 mb-3">
          {moderationType === 'text'
            ? 'Enter text content to test moderation'
            : 'Enter an image URL to test vision moderation'}
        </p>
        <div className="flex gap-2 mb-3">
          <input
            type="text"
            value={testInput}
            onChange={(e) => setTestInput(e.target.value)}
            placeholder={moderationType === 'text' ? 'Enter test text...' : 'Enter image URL...'}
            className="flex-1 text-sm border border-warm-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-brand-500"
          />
          <button
            onClick={handleTest}
            disabled={testing || !modelId || !enabled}
            className="btn-primary text-sm flex items-center gap-1.5 disabled:opacity-40"
          >
            {testing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
            Test
          </button>
        </div>
        {!modelId && <p className="text-xs text-amber-600">Select and save a model first to test</p>}

        {testResult && (
          <div className={`p-4 rounded-lg text-sm ${testResult.error ? 'bg-red-50 text-red-700' : testResult.action === 'flag' ? 'bg-red-50' : testResult.action === 'nsfw' ? 'bg-amber-50' : 'bg-green-50'}`}>
            {testResult.error ? (
              <p>{testResult.error}</p>
            ) : (
              <div className="space-y-3">
                {/* Verdict */}
                <div className="flex items-center gap-2 flex-wrap">
                  <span className={`text-lg font-bold ${testResult.action === 'flag' ? 'text-red-700' : testResult.action === 'nsfw' ? 'text-amber-700' : 'text-green-700'}`}>
                    {testResult.action === 'flag' ? '⛔ FLAGGED' : testResult.action === 'nsfw' ? '⚠️ NSFW' : '✅ CLEAN'}
                  </span>
                  {testResult.nsfw_reason && (
                    <span className="text-xs font-medium bg-amber-200 text-amber-800 px-2 py-0.5 rounded-full">{testResult.nsfw_reason}</span>
                  )}
                  {testResult.reason && <span className="text-gray-600">— {testResult.reason}</span>}
                </div>

                {/* Overall Explanation */}
                {testResult.explanation && (
                  <div className="bg-white/60 rounded-lg p-3 border border-warm-200">
                    <p className="text-xs font-semibold text-gray-500 uppercase mb-1">AI Analysis</p>
                    <p className="text-sm text-gray-700 leading-relaxed">{testResult.explanation}</p>
                  </div>
                )}

                {/* Score Bars with Detail */}
                <div className="space-y-2">
                  <ScoreBarDetailed label="Hate" value={testResult.hate} detail={testResult.hate_detail} />
                  <ScoreBarDetailed label="Greed" value={testResult.greed} detail={testResult.greed_detail} />
                  <ScoreBarDetailed label="Delusion" value={testResult.delusion} detail={testResult.delusion_detail} />
                </div>

                {testResult.raw_content && (
                  <details className="mt-2">
                    <summary className="text-xs text-gray-400 cursor-pointer">Raw model response</summary>
                    <pre className="mt-1 text-xs bg-white p-2 rounded border border-warm-200 overflow-x-auto whitespace-pre-wrap">{testResult.raw_content}</pre>
                  </details>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function ScoreBarDetailed({ label, value, detail }: { label: string; value: number; detail?: string }) {
  const pct = Math.round((value || 0) * 100);
  const color = pct > 50 ? 'bg-red-500' : pct > 25 ? 'bg-amber-400' : 'bg-green-400';
  const textColor = pct > 50 ? 'text-red-700' : pct > 25 ? 'text-amber-700' : 'text-green-700';
  return (
    <div className="bg-white/50 rounded-lg p-2.5 border border-warm-100">
      <div className="flex justify-between text-xs mb-1">
        <span className="font-semibold text-gray-700">{label}</span>
        <span className={`font-mono font-bold ${textColor}`}>{pct}%</span>
      </div>
      <div className="h-1.5 bg-gray-200 rounded-full overflow-hidden mb-1.5">
        <div className={`h-full ${color} rounded-full transition-all`} style={{ width: `${pct}%` }} />
      </div>
      {detail && <p className="text-xs text-gray-500 leading-relaxed">{detail}</p>}
    </div>
  );
}
