"use client";

import { useState, useEffect } from "react";
import { Clock, Server, Database, AlertCircle, CheckCircle, RefreshCw, Play, Timer, KeyRound, Mic, Users } from "lucide-react";

interface VoiceEngineConfig {
  engine: string;
  voice_id: string;
  model: string;
}

interface UserWithVoice {
  id: number;
  full_name: string | null;
  username: string | null;
  email: string | null;
  voice_engine: VoiceEngineConfig | null;
  instances: { id: number }[];
}

interface AdminSettings {
  id: string;
  instanceRetentionDays: number;
  trialDays: number;
}

interface DeletionStats {
  total: number;
  active: number;
  stopped: number;
  deleted: number;
  pendingDeletion: number;
}

export default function AdminSettingsPage() {
  const [settings, setSettings] = useState<AdminSettings | null>(null);
  const [stats, setStats] = useState<DeletionStats | null>(null);
  const [elevenlabsKey, setElevenlabsKey] = useState("");
  const [elevenlabsVoiceId, setElevenlabsVoiceId] = useState("");
  const [openaiKey, setOpenaiKey] = useState("");
  const [openaiVoice, setOpenaiVoice] = useState("alloy");
  const [googleCreds, setGoogleCreds] = useState("");
  const [googleVoice, setGoogleVoice] = useState("");
  const [defaultEngine, setDefaultEngine] = useState("elevenlabs");
  const [savingVoiceEngine, setSavingVoiceEngine] = useState(false);
  const [voiceUsers, setVoiceUsers] = useState<UserWithVoice[]>([]);
  const [editingUserVoice, setEditingUserVoice] = useState<number | null>(null);
  const [userVoiceForm, setUserVoiceForm] = useState({ engine: "", voice_id: "", model: "" });
  const [savingUserVoice, setSavingUserVoice] = useState(false);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [runningCron, setRunningCron] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  useEffect(() => {
    fetchSettings();
    fetchStats();
    fetchVoiceEngineConfig();
    fetchVoiceEngineUsers();
  }, []);

  const fetchVoiceEngineConfig = async () => {
    try {
      const res = await fetch("/api/admin/voice-engines");
      if (res.ok) {
        const data = await res.json();
        setElevenlabsKey(data.elevenlabsKey || "");
        setElevenlabsVoiceId(data.elevenlabsVoiceId || "");
        setOpenaiKey(data.openaiKey || "");
        setOpenaiVoice(data.openaiVoice || "alloy");
        setGoogleCreds(data.googleCreds || "");
        setGoogleVoice(data.googleVoice || "");
        setDefaultEngine(data.defaultEngine || "elevenlabs");
      }
    } catch {}
  };

  const fetchVoiceEngineUsers = async () => {
    try {
      const res = await fetch("/api/admin/voice-engines/users");
      if (res.ok) {
        const data = await res.json();
        setVoiceUsers(data.users || []);
      }
    } catch {}
  };

  const handleSaveVoiceEngineConfig = async () => {
    setSavingVoiceEngine(true);
    try {
      const res = await fetch("/api/admin/voice-engines", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          elevenlabsKey, elevenlabsVoiceId,
          openaiKey, openaiVoice,
          googleCreds, googleVoice,
          defaultEngine,
        }),
      });
      if (res.ok) {
        showMessage("success", "Voice engine config saved.");
      } else {
        showMessage("error", "Failed to save config.");
      }
    } catch {
      showMessage("error", "Failed to save config.");
    } finally {
      setSavingVoiceEngine(false);
    }
  };

  const handleEditUserVoice = (user: UserWithVoice) => {
    const ve = user.voice_engine || { engine: "", voice_id: "", model: "" };
    setUserVoiceForm({ engine: ve.engine || "", voice_id: ve.voice_id || "", model: ve.model || "" });
    setEditingUserVoice(user.id);
  };

  const handleSaveUserVoice = async () => {
    if (!editingUserVoice) return;
    setSavingUserVoice(true);
    try {
      const res = await fetch(`/api/admin/voice-engines/users/${editingUserVoice}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(userVoiceForm),
      });
      if (res.ok) {
        showMessage("success", "User voice config saved.");
        setEditingUserVoice(null);
        fetchVoiceEngineUsers();
      } else {
        showMessage("error", "Failed to save user voice config.");
      }
    } catch {
      showMessage("error", "Failed to save user voice config.");
    } finally {
      setSavingUserVoice(false);
    }
  };

  const fetchSettings = async () => {
    try {
      const res = await fetch("/api/admin/settings/retention");
      if (res.ok) {
        const data = await res.json();
        setSettings(data.settings);
      }
    } catch {
      console.error("Failed to fetch settings");
    }
  };

  const fetchStats = async () => {
    try {
      const res = await fetch("/api/admin/cron/auto-delete");
      if (res.ok) {
        const data = await res.json();
        setStats(data.stats);
      }
    } catch {
      console.error("Failed to fetch stats");
    } finally {
      setLoading(false);
    }
  };

  const showMessage = (type: "success" | "error", text: string) => {
    setMessage({ type, text });
    setTimeout(() => setMessage(null), 5000);
  };

  const handleSaveSettings = async () => {
    if (!settings) return;

    setSaving(true);
    try {
      const res = await fetch("/api/admin/settings/retention", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          days: settings.instanceRetentionDays,
          trialDays: settings.trialDays
        })
      });

      const data = await res.json();

      if (res.ok) {
        showMessage("success", "Settings saved successfully");
        setSettings(data.settings);
      } else {
        showMessage("error", data.error || "Failed to save settings");
      }
    } catch {
      showMessage("error", "Failed to save settings");
    } finally {
      setSaving(false);
    }
  };

  const handleRunCron = async () => {
    setRunningCron(true);
    try {
      const res = await fetch("/api/admin/cron/auto-delete", {
        method: "POST"
      });

      const data = await res.json();

      if (res.ok) {
        showMessage("success", data.message || "Cron job completed successfully");
        await fetchStats();
      } else {
        showMessage("error", data.error || "Failed to run cron job");
      }
    } catch {
      showMessage("error", "Failed to run cron job");
    } finally {
      setRunningCron(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <RefreshCw className="animate-spin text-brand" size={32} />
      </div>
    );
  }

  return (
    <div className="space-y-6">
        {/* Message */}
        {message && (
          <div className={`p-4 rounded-md ${message.type === "success" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`}>
            {message.text}
          </div>
        )}

        {/* Trial Period Settings */}
        <div className="bg-white rounded-lg border">
          <div className="p-6 border-b">
            <div className="flex items-center gap-2">
              <Timer size={20} className="text-slate-600" />
              <h2 className="text-lg font-semibold text-slate-900">Trial Period Settings</h2>
            </div>
            <p className="mt-1 text-sm text-slate-600">
              Configure the free trial duration for new users. After the trial expires, user instances will be stopped automatically.
            </p>
          </div>
          <div className="p-6 space-y-6">
            {settings && (
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">
                  Trial Duration (days)
                </label>
                <div className="flex items-center gap-4">
                  <input
                    type="number"
                    min="1"
                    max="365"
                    value={settings.trialDays}
                    onChange={(e) => setSettings({
                      ...settings,
                      trialDays: parseInt(e.target.value) || 14
                    })}
                    className="w-24 px-3 py-2 border rounded-md text-sm text-slate-900"
                  />
                  <span className="text-sm text-slate-600">days (1-365)</span>
                </div>
                <p className="mt-2 text-xs text-slate-500">
                  New users get this many days of free trial. After expiry, their instances are stopped and subscription status changes to PAST_DUE.
                  Set to 14 days by default.
                </p>
              </div>
            )}
          </div>
          <div className="p-6 bg-slate-50 border-t flex justify-end">
            <button
              onClick={handleSaveSettings}
              disabled={saving}
              className="px-4 py-2 bg-brand text-white rounded-md hover:opacity-90 disabled:opacity-50"
            >
              {saving ? "Saving..." : "Save Settings"}
            </button>
          </div>
        </div>

        {/* Voice Engines Config */}
        <div className="bg-white rounded-lg border">
          <div className="p-6 border-b">
            <div className="flex items-center gap-2">
              <Mic size={20} className="text-slate-600" />
              <h2 className="text-lg font-semibold text-slate-900">Voice Engines</h2>
            </div>
            <p className="mt-1 text-sm text-slate-600">
              Configure global voice engine credentials and default engine. Per-user overrides can be set below.
            </p>
          </div>
          <div className="p-6 space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Default Engine</label>
                <select
                  value={defaultEngine}
                  onChange={(e) => setDefaultEngine(e.target.value)}
                  className="w-full px-3 py-2 border rounded-md text-sm"
                >
                  <option value="elevenlabs">ElevenLabs</option>
                  <option value="openai">OpenAI TTS</option>
                  <option value="google">Google Cloud TTS</option>
                  <option value="free">Free (Edge-TTS)</option>
                </select>
              </div>
            </div>

            <div className="border-t pt-4">
              <h3 className="font-medium text-slate-900 mb-3 flex items-center gap-2">
                <KeyRound size={16} /> ElevenLabs
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">API Key</label>
                  <input
                    type="password"
                    value={elevenlabsKey}
                    onChange={(e) => setElevenlabsKey(e.target.value)}
                    placeholder="elevenlabs api key"
                    className="w-full px-3 py-2 border rounded-md text-sm font-mono"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Voice ID</label>
                  <input
                    type="text"
                    value={elevenlabsVoiceId}
                    onChange={(e) => setElevenlabsVoiceId(e.target.value)}
                    placeholder="voice_id"
                    className="w-full px-3 py-2 border rounded-md text-sm font-mono"
                  />
                </div>
              </div>
            </div>

            <div className="border-t pt-4">
              <h3 className="font-medium text-slate-900 mb-3 flex items-center gap-2">
                <KeyRound size={16} /> OpenAI TTS
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">API Key</label>
                  <input
                    type="password"
                    value={openaiKey}
                    onChange={(e) => setOpenaiKey(e.target.value)}
                    placeholder="sk-..."
                    className="w-full px-3 py-2 border rounded-md text-sm font-mono"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Voice</label>
                  <select
                    value={openaiVoice}
                    onChange={(e) => setOpenaiVoice(e.target.value)}
                    className="w-full px-3 py-2 border rounded-md text-sm"
                  >
                    <option value="alloy">Alloy</option>
                    <option value="echo">Echo</option>
                    <option value="fable">Fable</option>
                    <option value="nova">Nova</option>
                    <option value="shimmer">Shimmer</option>
                    <option value="coral">Coral</option>
                  </select>
                </div>
              </div>
            </div>

            <div className="border-t pt-4">
              <h3 className="font-medium text-slate-900 mb-3 flex items-center gap-2">
                <KeyRound size={16} /> Google Cloud TTS
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">
                    Service Account JSON (paste full JSON)
                  </label>
                  <textarea
                    value={googleCreds}
                    onChange={(e) => setGoogleCreds(e.target.value)}
                    placeholder='{"type": "service_account", ...}'
                    rows={3}
                    className="w-full px-3 py-2 border rounded-md text-sm font-mono"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Voice Name</label>
                  <input
                    type="text"
                    value={googleVoice}
                    onChange={(e) => setGoogleVoice(e.target.value)}
                    placeholder="en-US-Wavenet-D"
                    className="w-full px-3 py-2 border rounded-md text-sm font-mono"
                  />
                  <p className="mt-1 text-xs text-slate-500">Leave empty to use default.</p>
                </div>
              </div>
            </div>

            <div className="border-t pt-4">
              <h3 className="font-medium text-slate-900 mb-3">Free (Edge-TTS)</h3>
              <p className="text-sm text-slate-600">
                No API key needed. Edge-TTS runs locally in the container using Microsoft&apos;s neural TTS voices.
                No configuration required.
              </p>
            </div>
          </div>
          <div className="p-6 bg-slate-50 border-t flex justify-end">
            <button
              onClick={handleSaveVoiceEngineConfig}
              disabled={savingVoiceEngine}
              className="px-4 py-2 bg-brand text-white rounded-md hover:opacity-90 disabled:opacity-50"
            >
              {savingVoiceEngine ? "Saving..." : "Save Voice Config"}
            </button>
          </div>
        </div>

        {/* Per-User Voice Engine Overrides */}
        <div className="bg-white rounded-lg border">
          <div className="p-6 border-b">
            <div className="flex items-center gap-2">
              <Users size={20} className="text-slate-600" />
              <h2 className="text-lg font-semibold text-slate-900">Per-User Voice Engine</h2>
            </div>
            <p className="mt-1 text-sm text-slate-600">
              Override the voice engine for specific users. Their Jarvis instances will use this config.
            </p>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-slate-50 border-b">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">User</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Jarvis Instances</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Voice Engine</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-200">
                  {voiceUsers.map((user: UserWithVoice) => {
                    const ve = user.voice_engine || { engine: "", voice_id: "", model: "" };
                  return (
                    <tr key={user.id} className="hover:bg-slate-50">
                      <td className="px-4 py-3">
                        <p className="font-medium text-slate-900">{user.full_name || user.username}</p>
                        <p className="text-xs text-slate-500">{user.email}</p>
                      </td>
                      <td className="px-4 py-3">
                        <span className="text-sm text-slate-600">
                          {user.instances?.length || 0} instance{(user.instances?.length || 0) !== 1 ? "s" : ""}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        {editingUserVoice === user.id ? (
                          <div className="flex gap-2">
                            <select
                              value={userVoiceForm.engine}
                              onChange={(e) => setUserVoiceForm({ ...userVoiceForm, engine: e.target.value })}
                              className="px-2 py-1 border rounded text-xs"
                            >
                              <option value="">Use default</option>
                              <option value="elevenlabs">ElevenLabs</option>
                              <option value="openai">OpenAI TTS</option>
                              <option value="google">Google TTS</option>
                              <option value="free">Free (Edge-TTS)</option>
                            </select>
                            <input
                              type="text"
                              value={userVoiceForm.voice_id}
                              onChange={(e) => setUserVoiceForm({ ...userVoiceForm, voice_id: e.target.value })}
                              placeholder="voice id"
                              className="px-2 py-1 border rounded text-xs w-28 font-mono"
                            />
                          </div>
                        ) : (
                          <span className="text-sm text-slate-700">{ve.engine || "default"} {ve.voice_id ? `(${ve.voice_id})` : ""}</span>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        {editingUserVoice === user.id ? (
                          <div className="flex gap-2">
                            <button
                              onClick={handleSaveUserVoice}
                              disabled={savingUserVoice}
                              className="px-2 py-1 bg-brand text-white rounded text-xs"
                            >
                              {savingUserVoice ? "Saving..." : "Save"}
                            </button>
                            <button
                              onClick={() => setEditingUserVoice(null)}
                              className="px-2 py-1 border rounded text-xs"
                            >
                              Cancel
                            </button>
                          </div>
                        ) : (
                          <button
                            onClick={() => handleEditUserVoice(user)}
                            className="px-2 py-1 border rounded text-xs text-brand hover:bg-slate-50"
                          >
                            Edit
                          </button>
                        )}
                      </td>
                    </tr>
                  );
                })}
                {voiceUsers.length === 0 && (
                  <tr>
                    <td colSpan={4} className="px-4 py-8 text-center text-slate-500">No users found.</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Instance Lifecycle Settings */}
        <div className="bg-white rounded-lg border">
          <div className="p-6 border-b">
            <h2 className="text-lg font-semibold text-slate-900">Instance Lifecycle Settings</h2>
            <p className="mt-1 text-sm text-slate-600">
              Configure how long stopped or deleted instances are kept before permanent deletion
            </p>
          </div>
          <div className="p-6 space-y-6">
            {settings && (
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">
                  Instance Retention Period (days)
                </label>
                <div className="flex items-center gap-4">
                  <input
                    type="number"
                    min="1"
                    max="90"
                    value={settings.instanceRetentionDays}
                    onChange={(e) => setSettings({
                      ...settings,
                      instanceRetentionDays: parseInt(e.target.value) || 7
                    })}
                    className="w-24 px-3 py-2 border rounded-md text-sm text-slate-900"
                  />
                  <span className="text-sm text-slate-600">days (1-90)</span>
                </div>
                <p className="mt-2 text-xs text-slate-500">
                  Instances that are stopped or deleted will be permanently deleted after this many days.
                  Set to 7 days by default.
                </p>
              </div>
            )}
          </div>
          <div className="p-6 bg-slate-50 border-t flex justify-end">
            <button
              onClick={handleSaveSettings}
              disabled={saving}
              className="px-4 py-2 bg-brand text-white rounded-md hover:opacity-90 disabled:opacity-50"
            >
              {saving ? "Saving..." : "Save Settings"}
            </button>
          </div>
        </div>

        {/* Deletion Statistics */}
        {stats && (
          <div className="bg-white rounded-lg border">
            <div className="p-6 border-b">
              <h2 className="text-lg font-semibold text-slate-900">Instance Statistics</h2>
              <p className="mt-1 text-sm text-slate-600">
                Overview of current instance states and pending deletions
              </p>
            </div>
            <div className="p-6">
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
                <div className="p-4 bg-blue-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <Database className="text-blue-600" size={20} />
                    <div>
                      <p className="text-2xl font-bold text-blue-900">{stats.total}</p>
                      <p className="text-xs text-blue-600">Total Instances</p>
                    </div>
                  </div>
                </div>
                <div className="p-4 bg-green-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <CheckCircle className="text-green-600" size={20} />
                    <div>
                      <p className="text-2xl font-bold text-green-900">{stats.active}</p>
                      <p className="text-xs text-green-600">Active / Running</p>
                    </div>
                  </div>
                </div>
                <div className="p-4 bg-amber-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <Clock className="text-amber-600" size={20} />
                    <div>
                      <p className="text-2xl font-bold text-amber-900">{stats.stopped}</p>
                      <p className="text-xs text-amber-600">Stopped</p>
                    </div>
                  </div>
                </div>
                <div className="p-4 bg-red-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <AlertCircle className="text-red-600" size={20} />
                    <div>
                      <p className="text-2xl font-bold text-red-900">{stats.deleted}</p>
                      <p className="text-xs text-red-600">Soft Deleted</p>
                    </div>
                  </div>
                </div>
                <div className="p-4 bg-purple-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <Server className="text-purple-600" size={20} />
                    <div>
                      <p className="text-2xl font-bold text-purple-900">{stats.pendingDeletion}</p>
                      <p className="text-xs text-purple-600">Pending Deletion</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Auto-Deletion Cron */}
        <div className="bg-white rounded-lg border">
          <div className="p-6 border-b">
            <h2 className="text-lg font-semibold text-slate-900">Auto-Deletion Cron Job</h2>
            <p className="mt-1 text-sm text-slate-600">
              Manually trigger or configure automatic deletion of expired instances
            </p>
          </div>
          <div className="p-6 space-y-4">
            <div className="p-4 bg-slate-50 rounded-md">
              <h3 className="font-medium text-slate-900 mb-2">External Cron Configuration</h3>
              <p className="text-sm text-slate-600 mb-3">
                Set up a cron job to call this endpoint daily:
              </p>
              <code className="block p-3 bg-slate-900 text-green-400 rounded text-sm overflow-x-auto">
                curl -X POST https://wakelai.com/api/admin/cron/auto-delete \<br />
                &nbsp;&nbsp;-H &quot;Authorization: Bearer YOUR_ADMIN_CRON_SECRET&quot;
              </code>
              <p className="mt-3 text-xs text-slate-500">
                Set ADMIN_CRON_SECRET in your environment variables.
              </p>
            </div>

            <div className="flex items-center gap-4">
              <button
                onClick={handleRunCron}
                disabled={runningCron}
                className="px-4 py-2 bg-brand text-white rounded-md hover:opacity-90 disabled:opacity-50 flex items-center gap-2"
              >
                {runningCron ? (
                  <>
                    <RefreshCw className="animate-spin" size={16} />
                    Running...
                  </>
                ) : (
                  <>
                    <Play size={16} />
                    Run Cron Now
                  </>
                )}
              </button>
              <span className="text-sm text-slate-600">
                Manually trigger the auto-deletion process
              </span>
            </div>
          </div>
        </div>

        {/* System Info */}
        <div className="bg-white rounded-lg border">
          <div className="p-6 border-b">
            <h2 className="text-lg font-semibold text-slate-900">System Information</h2>
          </div>
          <div className="p-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
              <div>
                <span className="text-slate-500">Runtime mode:</span>
                <span className="ml-2 font-medium">{process.env.DOKPLOY_API_MODE || "local-docker"}</span>
              </div>
              <div>
                <span className="text-slate-500">Root domain:</span>
                <span className="ml-2 font-medium">{process.env.APP_ROOT_DOMAIN || "wakelai.com"}</span>
              </div>
              <div>
                <span className="text-slate-500">Hermes image:</span>
                <span className="ml-2 font-medium">{process.env.HERMES_IMAGE || "-"}</span>
              </div>
              <div>
                <span className="text-slate-500">Docker network:</span>
                <span className="ml-2 font-medium">{process.env.HERMES_DOCKER_NETWORK || "wakelai-runtime"}</span>
              </div>
            </div>
          </div>
      </div>
    </div>
  );
}
