'use client';
import React, { useState, useEffect } from 'react';
import { User, Lock, Save, Loader2 } from 'lucide-react';

export default function AdminProfile() {
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);
  
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    password: '',
    securityQuestion1: '',
    securityAnswer1: '',
    securityQuestion2: '',
    securityAnswer2: ''
  });

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

  const fetchProfile = async () => {
    try {
      const res = await fetch('/api/auth/profile');
      if (res.ok) {
        const data = await res.json();
        setFormData(prev => ({
          ...prev,
          name: data.name || '',
          email: data.email || '',
          phone: data.phone || '',
          securityQuestion1: data.securityQuestion1 || '',
          securityQuestion2: data.securityQuestion2 || ''
        }));
      }
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setMessage(null);

    try {
      const res = await fetch('/api/auth/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });
      
      const data = await res.json();
      if (res.ok) {
        setMessage({ type: 'success', text: 'Profile updated successfully!' });
        // Clear sensitive fields
        setFormData(prev => ({ ...prev, password: '', securityAnswer1: '', securityAnswer2: '' }));
      } else {
        setMessage({ type: 'error', text: data.error || 'Failed to update.' });
      }
    } catch (e) {
      setMessage({ type: 'error', text: 'Network error.' });
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) return <div className="p-10 text-center"><Loader2 className="animate-spin mx-auto text-primary" /></div>;

  return (
    <div className="max-w-3xl mx-auto">
      <h2 className="text-2xl font-bold text-slate-800 mb-6">My Profile & Security</h2>
      
      {message && (
        <div className={`p-4 rounded-lg mb-6 ${message.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
          {message.text}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-8">
        {/* Personal Info */}
        <div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
          <h3 className="font-bold text-lg mb-4 flex items-center gap-2"><User size={20} className="text-primary" /> Personal Information</h3>
          <div className="grid md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Full Name</label>
              <input 
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                value={formData.name}
                onChange={e => setFormData({...formData, name: e.target.value})}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Email Address</label>
              <input 
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none bg-slate-50 cursor-not-allowed"
                value={formData.email}
                disabled
                title="Email cannot be changed directly"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Phone Number</label>
              <input 
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                value={formData.phone}
                onChange={e => setFormData({...formData, phone: e.target.value})}
                placeholder="+44 7700 900000"
              />
            </div>
          </div>
        </div>

        {/* Security Questions */}
        <div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
          <h3 className="font-bold text-lg mb-4 flex items-center gap-2"><Lock size={20} className="text-primary" /> Security Recovery Questions</h3>
          <p className="text-sm text-slate-500 mb-4">Set these questions to recover your password if you forget it.</p>
          
          <div className="space-y-4">
            <div className="grid md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Question 1</label>
                <input 
                  className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                  value={formData.securityQuestion1}
                  onChange={e => setFormData({...formData, securityQuestion1: e.target.value})}
                  placeholder="e.g. What was my first pet's name?"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Answer 1</label>
                <input 
                  type="password"
                  className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                  value={formData.securityAnswer1}
                  onChange={e => setFormData({...formData, securityAnswer1: e.target.value})}
                  placeholder="Only change if updating"
                />
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Question 2</label>
                <input 
                  className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                  value={formData.securityQuestion2}
                  onChange={e => setFormData({...formData, securityQuestion2: e.target.value})}
                  placeholder="e.g. What city was I born in?"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Answer 2</label>
                <input 
                  type="password"
                  className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                  value={formData.securityAnswer2}
                  onChange={e => setFormData({...formData, securityAnswer2: e.target.value})}
                  placeholder="Only change if updating"
                />
              </div>
            </div>
          </div>
        </div>

        {/* Change Password */}
        <div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
          <h3 className="font-bold text-lg mb-4 text-red-600">Change Password</h3>
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">New Password</label>
            <input 
              type="password"
              className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
              value={formData.password}
              onChange={e => setFormData({...formData, password: e.target.value})}
              placeholder="Leave blank to keep current password"
            />
          </div>
        </div>

        <button 
          type="submit" 
          disabled={submitting}
          className="w-full bg-primary hover:bg-primary-dark text-white py-4 rounded-xl font-bold text-lg transition flex items-center justify-center gap-2 disabled:opacity-50"
        >
          {submitting ? <Loader2 className="animate-spin" /> : <Save />} Save Changes
        </button>
      </form>
    </div>
  );
}