'use client';

import React, { useState, useEffect } from 'react';
import { User, ShieldCheck, Mail, Phone, Building } from 'lucide-react';
import SmartAuthCard from '@/components/ui/smartauth/SmartAuthCard';
import SmartAuthButton from '@/components/ui/smartauth/SmartAuthButton';
import SmartAuthBadge from '@/components/ui/smartauth/SmartAuthBadge';

export default function SuperAdminProfilePage() {
  const [user, setUser] = useState<any>(null);
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);

  useEffect(() => {
    async function loadProfile() {
      try {
        const res = await fetch('/api/v1/account');
        const data = await res.json();
        if (data.success) {
          setUser(data.data.user);
          setName(data.data.user.name || '');
          setPhone(data.data.user.phone || '');
        }
      } catch {}
    }
    loadProfile();
  }, []);

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setMsg(null);
    try {
      const res = await fetch('/api/v1/account', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, phone }),
      });
      const data = await res.json();
      if (data.success) {
        setMsg('Super Admin profile updated successfully in MySQL.');
      }
    } catch {
      setMsg('Failed to update profile.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-7 max-w-4xl animate-in fade-in duration-150">
      <div>
        <h1 className="text-2xl font-extrabold text-slate-900 tracking-tight">Super Admin Root Profile</h1>
        <p className="text-xs text-slate-500 mt-1">Platform owner root identity credentials and system master keys.</p>
      </div>

      {msg && (
        <div className="p-3 bg-emerald-50 border border-emerald-200 text-emerald-800 rounded-xl text-xs font-semibold">
          {msg}
        </div>
      )}

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div className="p-5 bg-white rounded-2xl border border-slate-200/90 shadow-sm space-y-2">
          <span className="text-[11px] font-mono font-bold text-slate-400 uppercase">SUPER ADMIN USER ID</span>
          <div className="text-lg font-mono font-extrabold text-emerald-800">{user?.userCode || 'USR-2026-000001'}</div>
          <span className="text-xs text-slate-500">Root identifier • Highest system rank</span>
        </div>

        <div className="p-5 bg-white rounded-2xl border border-slate-200/90 shadow-sm space-y-2">
          <span className="text-[11px] font-mono font-bold text-slate-400 uppercase">PLATFORM AUTHORITY</span>
          <div className="flex items-center gap-2">
            <SmartAuthBadge variant="error" size="md">SUPER_ADMIN (UNRESTRICTED)</SmartAuthBadge>
          </div>
          <span className="text-xs text-slate-500">Root access to all database tables & settings</span>
        </div>
      </div>

      <SmartAuthCard title="Personal & Contact Information" headerIcon={User}>
        <form onSubmit={handleSave} className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <label className="text-xs font-bold text-slate-700">Full Name</label>
              <input
                type="text"
                required
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="w-full px-4 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
              />
            </div>

            <div className="space-y-1.5">
              <label className="text-xs font-bold text-slate-700">Email Address (Root)</label>
              <input
                type="email"
                disabled
                value={user?.email || ''}
                className="w-full px-4 py-2.5 text-xs rounded-xl border border-slate-200 bg-slate-50 text-slate-500 cursor-not-allowed font-mono"
              />
            </div>
          </div>

          <div className="space-y-1.5">
            <label className="text-xs font-bold text-slate-700">Contact Phone Number</label>
            <input
              type="text"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              className="w-full px-4 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500/20 font-mono"
            />
          </div>

          <div className="pt-2 flex justify-end">
            <SmartAuthButton type="submit" variant="primary" size="md" loading={saving}>
              Save Profile
            </SmartAuthButton>
          </div>
        </form>
      </SmartAuthCard>
    </div>
  );
}
