'use client';

import { useState, useEffect } from 'react';
import { Save, Server, ShieldCheck, Zap } from 'lucide-react';
import AdminControlMenu from '@/components/admin/AdminControlMenu';
import { User, Lock, Bell, CreditCard } from 'lucide-react';
import axios from 'axios';
import { API_BASE_URL } from "../../../lib/api-config";

export default function AdminSettingsPage() {
  const [maintMode, setMaintMode] = useState(false);
  const [freeLimit, setFreeLimit] = useState(5);
  const [premiumPrice, setPremiumPrice] = useState(3000);

  const getCookieValue = (name: string) => {
        const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
        return match ? match[2] : null;
  }

  useEffect(() => {
    const fetchConfig = async () => {
      try {
        const res = await axios.get(`${API_BASE_URL}/api/system-status`);
        setMaintMode(res.data.maintenanceMode);
        if (res.data.freeLimit) setFreeLimit(res.data.freeLimit);
        if (res.data.premiumPrice) setPremiumPrice(res.data.premiumPrice);
      } catch (error) {
        console.error("Failed to load infra config", error);
      }
    }

    fetchConfig();
  }, []);

  const handleToggle = async () => {
    const newStatus = !maintMode;
    setMaintMode(newStatus);
  
    try {
      const token = getCookieValue('wtihub_token');
      await axios.post(`${API_BASE_URL}/api/toggle-maintenance`,
        {status: newStatus},
        {headers: {Authorization: `Bearer ${token}`}}
      );
    } catch (error) {
      setMaintMode(!newStatus)
      alert("System Config Sync Failed");
    }
  }

 const updateLimits = async () => {
    try {
      const token = getCookieValue('wtihub_token');
      await axios.post(`${API_BASE_URL}/api/update-limits`, {
        freeLimit: Number(freeLimit),
        premiumPrice: Number(premiumPrice)
      }, {
        headers: { Authorization: `Bearer ${token}` }
      });
      alert("Infrastructure parameters synchronized.");
    } catch (error) {
      alert("Update limits failed.");
    }
}

  return (
    <div className="min-h-screen bg-wtihub-bg p-8 pb-32">
      <div className="max-w-4xl mx-auto">
        <header className="mb-12">
          <h1 className="text-4xl font-black text-wtihub-text">System <span className="text-wtihub-green">Config</span></h1>
          <p className="text-gray-500 mt-2">Global infrastructure parameters.</p>
        </header>

        <div className="grid gap-6">
          {/* Service Status Card */}
          <div className="bg-wtihub-surface p-6 rounded-2xl border border-wtihub-border">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-wtihub-green/10 rounded-xl text-wtihub-green">
                  <Server size={24} />
                </div>
                <div>
                  <h3 className="font-bold">Maintenance Mode</h3>
                  <p className="text-xs text-gray-500">Lock the frontend for all non-admin users.</p>
                </div>
              </div>
              <button 
                onClick={handleToggle}
                className={`w-14 h-8 rounded-full transition-all relative ${maintMode ? 'bg-wtihub-green' : 'bg-gray-700'}`}
              >
                <div className={`absolute top-1 w-6 h-6 bg-white rounded-full transition-all ${maintMode ? 'left-7' : 'left-1'}`} />
              </button>
            </div>
          </div>

          {/* API Configuration */}
          <div className="bg-wtihub-surface p-6 rounded-2xl border border-wtihub-border">
            <h3 className="font-bold mb-4 flex items-center gap-2">
              <Zap size={18} className="text-wtihub-green" /> 
              Infrastructure Limits
            </h3>
            <div className="space-y-4">
              <div className="flex justify-between items-center text-sm">
                <span className="text-gray-400">Default Free Link Limit</span>
                <input type="number" value={freeLimit} onChange={(e) => setFreeLimit(Number(e.target.value))} className="bg-wtihub-bg border border-wtihub-border p-2 rounded w-20 text-center" />
              </div>
              <div className="flex justify-between items-center text-sm">
                <span className="text-gray-400">Premium Subscription Price (₦)</span>
                <input type="number" value={premiumPrice} onChange={(e) => setPremiumPrice(Number(e.target.value))} className="bg-wtihub-bg border border-wtihub-border p-2 rounded w-24 text-center" />
              </div>
            </div>
            <button
             onClick={updateLimits}
             className="mt-8 w-full flex items-center justify-center gap-2 py-3 bg-wtihub-green text-wtihub-bg font-bold rounded-lg hover:opacity-90 transition-all cursor-pointer">
              <Save size={18} /> Update Core Settings
            </button>
          </div>
        </div>
      </div>

      <AdminControlMenu />
    </div>
  );
}

export function MemberSettings() {
  return (
    <div className="min-h-screen bg-wtihub-bg p-8">
      <div className="max-w-4xl mx-auto">
        <h1 className="text-3xl font-black mb-8 text-wtihub-text">Account <span className="text-wtihub-green">Settings</span></h1>
        
        <div className="space-y-6">
          {/* Profile Section */}
          <section className="bg-wtihub-surface p-6 rounded-2xl border border-wtihub-border">
            <h2 className="flex items-center gap-2 font-bold mb-4 text-wtihub-text">
              <User size={18} className="text-wtihub-green" /> Personal Architecture
            </h2>
            <div className="grid grid-cols-2 gap-4">
              <input type="text" placeholder="Username" className="bg-wtihub-bg border border-wtihub-border p-3 rounded-lg outline-none focus:border-wtihub-green text-sm" />
              <input type="email" placeholder="Email Address" className="bg-wtihub-bg border border-wtihub-border p-3 rounded-lg outline-none focus:border-wtihub-green text-sm" />
            </div>
          </section>

          {/* Billing Section (Upsell) */}
          <section className="bg-wtihub-surface p-6 rounded-2xl border border-wtihub-border flex justify-between items-center">
            <div>
              <h2 className="flex items-center gap-2 font-bold text-wtihub-text">
                <CreditCard size={18} className="text-wtihub-green" /> Subscription
              </h2>
              <p className="text-xs text-gray-500 mt-1">You are currently on the <span className="font-bold">Standard Tier</span>.</p>
            </div>
            <button className="btn-wtihub px-6 py-2 text-sm">Upgrade to Premium</button>
          </section>
        </div>
      </div>
    </div>
  );
}