"use client";

import { useEffect, useState } from "react";
import { Button, Input } from "@/components/ui";

interface PlatformInfo {
  proFamilies: number;
  freeFamilies: number;
  totalUsers: number;
  freeMaxChildren: number;
  freeMaxMembers: number;
  aiModel: string;
  aiBaseUrl: string;
}

export default function AdminSettings() {
  const [info, setInfo] = useState<PlatformInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [freeMaxChildren, setFreeMaxChildren] = useState(1);
  const [freeMaxMembers, setFreeMaxMembers] = useState(2);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

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

  const fetchInfo = async () => {
    try {
      const res = await fetch("/api/admin/stats", { credentials: "include" });
      const data = await res.json();
      setFreeMaxChildren(1);
      setFreeMaxMembers(2);
      setInfo({
        proFamilies: data.overview?.proFamilies || 0,
        freeFamilies: data.overview?.freeFamilies || 0,
        totalUsers: data.overview?.totalUsers || 0,
        freeMaxChildren: 1,
        freeMaxMembers: 2,
        aiModel: "minimax-2.7",
        aiBaseUrl: "https://llm.manohargupta.com",
      });
    } catch (err) {
      console.error("Failed to fetch:", err);
    }
    setLoading(false);
  };

  const handleSaveLimits = async () => {
    setSaving(true);
    try {
      // Apply new limits to all free-tier families
      const res = await fetch("/api/admin/families/limits", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ maxChildren: freeMaxChildren, maxMembers: freeMaxMembers }),
      });
      if (res.ok) {
        setSaved(true);
        setTimeout(() => setSaved(false), 3000);
      }
    } catch (err) {
      console.error("Failed to save:", err);
    }
    setSaving(false);
  };

  if (loading || !info) return <div className="p-6 text-white">Loading...</div>;

  return (
    <div className="p-6 space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Settings</h1>
        <p className="text-gray-400">Platform configuration and limits</p>
      </div>

      {/* Platform Summary */}
      <div className="grid grid-cols-3 gap-4">
        <div className="bg-gray-800 p-4 rounded-xl text-center">
          <div className="text-2xl font-bold text-rose-400">{info.proFamilies}</div>
          <div className="text-xs text-gray-400 mt-1">Pro Families</div>
        </div>
        <div className="bg-gray-800 p-4 rounded-xl text-center">
          <div className="text-2xl font-bold text-gray-400">{info.freeFamilies}</div>
          <div className="text-xs text-gray-400 mt-1">Free Families</div>
        </div>
        <div className="bg-gray-800 p-4 rounded-xl text-center">
          <div className="text-2xl font-bold text-blue-400">{info.totalUsers}</div>
          <div className="text-xs text-gray-400 mt-1">Total Users</div>
        </div>
      </div>

      {/* Pricing — read-only display */}
      <div className="bg-gray-800 p-6 rounded-xl space-y-3">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-semibold">Pricing</h3>
          <span className="text-xs text-gray-500 bg-gray-700 px-2 py-1 rounded">Set via env var</span>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-gray-700 px-4 py-3 rounded-lg">
            <div className="text-xs text-gray-500 mb-1">Pro Monthly Price</div>
            <div className="text-xl font-bold text-emerald-400">$9.99 / month</div>
          </div>
          <div className="bg-gray-700 px-4 py-3 rounded-lg">
            <div className="text-xs text-gray-500 mb-1">Annual Run Rate</div>
            <div className="text-xl font-bold text-emerald-400">
              ${(info.proFamilies * 9.99 * 12).toFixed(0)} / year
            </div>
          </div>
        </div>
        <p className="text-xs text-gray-600">
          To change pricing, update <code className="text-gray-400">PRO_PRICE</code> in Dokploy dashboard and redeploy.
        </p>
      </div>

      {/* Free Tier Limits — editable */}
      <div className="bg-gray-800 p-6 rounded-xl space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-semibold">Free Tier Limits</h3>
          <span className="text-xs text-emerald-400 bg-emerald-400/10 px-2 py-1 rounded">Editable</span>
        </div>
        <p className="text-xs text-gray-500">
          These limits are applied to all free-tier families. Existing families will be updated.
        </p>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm text-gray-400 mb-1">Max Children per Family</label>
            <Input
              type="number"
              min={1}
              max={10}
              value={freeMaxChildren}
              onChange={(e) => setFreeMaxChildren(Number(e.target.value))}
            />
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Max Family Members</label>
            <Input
              type="number"
              min={1}
              max={10}
              value={freeMaxMembers}
              onChange={(e) => setFreeMaxMembers(Number(e.target.value))}
            />
          </div>
        </div>
        <Button onClick={handleSaveLimits} disabled={saving}>
          {saved ? "✓ Saved" : saving ? "Saving…" : "Apply to All Free Families"}
        </Button>
      </div>

      {/* AI Configuration — read-only */}
      <div className="bg-gray-800 p-6 rounded-xl space-y-3">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-semibold">AI Configuration</h3>
          <span className="text-xs text-gray-500 bg-gray-700 px-2 py-1 rounded">Set via env var</span>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-gray-700 px-4 py-3 rounded-lg">
            <div className="text-xs text-gray-500 mb-1">Model</div>
            <div className="font-mono text-sm text-blue-400">{info.aiModel}</div>
          </div>
          <div className="bg-gray-700 px-4 py-3 rounded-lg">
            <div className="text-xs text-gray-500 mb-1">LiteLLM Gateway</div>
            <div className="font-mono text-sm text-blue-400 truncate">{info.aiBaseUrl}</div>
          </div>
        </div>
        <p className="text-xs text-gray-600">
          To change AI settings, update <code className="text-gray-400">LITELLM_BASE_URL</code> and <code className="text-gray-400">LITELLM_API_KEY</code> in Dokploy.
        </p>
      </div>

      {/* Admin Access */}
      <div className="bg-gray-800 p-6 rounded-xl space-y-3">
        <h3 className="text-lg font-semibold">Admin Access</h3>
        <p className="text-sm text-gray-400">
          Admin login: <code className="text-gray-300">/admin-login</code><br />
          Password changes must be made directly in the database via the <code className="text-gray-300">admins</code> table.
        </p>
        <div className="bg-amber-500/10 border border-amber-500/20 rounded-lg px-4 py-3">
          <div className="text-amber-400 text-sm font-medium">Security Reminder</div>
          <div className="text-gray-400 text-xs mt-1">
            Change the default admin password immediately if still using <code>admin123</code>.
          </div>
        </div>
      </div>
    </div>
  );
}
