import { useState, useEffect } from 'react';
import axios from 'axios';
import { useAuth } from '../context/AuthContext';

interface User {
  id: number;
  email: string;
  firstName: string;
  lastName: string;
  membershipStatus: string;
  planType: string | null;
}

export default function ManageMemberships() {
  const [users, setUsers] = useState<User[]>([]);
  const { token, user } = useAuth();
  const [error, setError] = useState('');
  const [plans, setPlans] = useState<any[]>([]);
  const [membershipModal, setMembershipModal] = useState<{isOpen: boolean, user: User | null}>({isOpen: false, user: null});
  const [selectedStatus, setSelectedStatus] = useState('inactive');
  const [selectedPlan, setSelectedPlan] = useState('Basic');

  useEffect(() => {
    fetch('/api/plans')
      .then(res => res.json())
      .then(data => setPlans(data))
      .catch(err => console.error(err));
  }, []);

  const fetchUsers = async () => {
    try {
      const res = await axios.get('/api/users', { headers: { Authorization: `Bearer ${token}` } });
      setUsers(res.data);
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to fetch users');
    }
  };

  useEffect(() => {
    fetchUsers();
  }, [token]);

  const updateMembership = async () => {
    if (!membershipModal.user) return;
    try {
      await axios.post(`/api/users/${membershipModal.user.id}/membership`, 
        { membershipStatus: selectedStatus, planType: selectedPlan }, 
        { headers: { Authorization: `Bearer ${token}` } }
      );
      setMembershipModal({isOpen: false, user: null});
      fetchUsers();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to update membership');
    }
  };

  if (user?.role !== 'superadmin') {
    return (
      <div className="flex flex-col items-center justify-center mt-20 text-center">
        <span className="material-symbols-outlined text-[#ffb4ab] text-[64px] mb-4">gpp_bad</span>
        <h2 className="text-[32px] font-bold text-[#0f172a] mb-2" style={{ fontFamily: 'Outfit, sans-serif' }}>Access Denied</h2>
        <p className="text-[#475569]">You do not have permission to view this page.</p>
      </div>
    );
  }

  return (
    <div className="max-w-[1440px] mx-auto px-4 md:px-8 py-8" style={{ fontFamily: 'Inter, sans-serif' }}>
      
      <div className="mb-10 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-[32px] md:text-[40px] font-bold text-[#0f172a] leading-tight" style={{ fontFamily: 'Outfit, sans-serif' }}>Manage Memberships</h1>
          <p className="text-[16px] text-[#475569] mt-2">Manually activate or upgrade user memberships.</p>
        </div>
      </div>

      {error && (
        <div className="mb-6 px-4 py-3 bg-[#ffb4ab]/10 border border-[#ffb4ab]/20 rounded-lg text-[#ffb4ab] text-[14px]">
          {error}
        </div>
      )}

      <div className="glass-card rounded-xl overflow-hidden w-full overflow-x-auto">
        <table className="w-full text-left border-collapse min-w-[700px]">
          <thead>
            <tr className="bg-white/30 text-[#475569] text-[12px] md:text-[14px] font-semibold uppercase tracking-wider">
              <th className="px-6 py-4">ID</th>
              <th className="px-6 py-4">User</th>
              <th className="px-6 py-4">Plan Type</th>
              <th className="px-6 py-4">Status</th>
              <th className="px-6 py-4 text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/5">
            {users.map(u => (
              <tr key={u.id} className="hover:bg-black/5 transition-colors group">
                <td className="px-6 py-5 text-[#475569] text-[14px]">#{u.id}</td>
                <td className="px-6 py-5">
                  <div className="font-medium text-[#0f172a] text-[14px]">{u.firstName} {u.lastName}</div>
                  <div className="text-[#475569] text-[12px]">{u.email}</div>
                </td>
                <td className="px-6 py-5 text-[#c0c1ff] font-semibold text-[14px]">{u.planType || 'None'}</td>
                <td className="px-6 py-5">
                  <span className={`px-3 py-1 rounded-full text-[12px] font-semibold border ${
                    u.membershipStatus === 'active' 
                      ? 'bg-[#4edea3]/15 text-[#4edea3] border-[#4edea3]/20' 
                      : 'bg-[#ffb4ab]/15 text-[#ffb4ab] border-[#ffb4ab]/20'
                  }`}>
                    {u.membershipStatus}
                  </span>
                </td>
                <td className="px-6 py-5 text-right flex items-center justify-end gap-2">
                  <button 
                    className="bg-[#e2e8f0]/40 hover:bg-[#e2e8f0]/80 text-[#0f172a] px-3 py-1.5 rounded-lg font-semibold text-[12px] transition-all active:scale-95 border border-black/5 flex items-center gap-1"
                    onClick={() => {
                      setSelectedStatus(u.membershipStatus || 'inactive');
                      setSelectedPlan(u.planType || (plans.length > 0 ? plans[0].name : 'Basic'));
                      setMembershipModal({isOpen: true, user: u});
                    }}
                  >
                    <span className="material-symbols-outlined text-[16px]">edit_note</span>
                    Set Membership
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {/* Set Membership Modal */}
      {membershipModal.isOpen && membershipModal.user && (
        <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-[60] flex items-center justify-center p-4">
          <div className="bg-white border border-black/10 rounded-xl shadow-2xl max-w-sm w-full p-6">
            <h3 className="text-[20px] font-bold text-[#0f172a] mb-4" style={{ fontFamily: 'Outfit, sans-serif' }}>Set Membership</h3>
            <p className="text-[#475569] text-[14px] mb-4">Manage membership for {membershipModal.user.firstName} {membershipModal.user.lastName}.</p>
            
            <div className="mb-4">
              <label className="block text-[#475569] text-[12px] font-semibold mb-2">Status</label>
              <select 
                value={selectedStatus}
                onChange={(e) => setSelectedStatus(e.target.value)}
                className="w-full bg-[#f1f5f9] text-[#0f172a] p-3 rounded-lg border border-slate-300 focus:outline-none focus:border-[#8083ff] text-[14px]"
              >
                <option value="inactive">Inactive</option>
                <option value="active">Active</option>
              </select>
            </div>

            <div className="mb-6">
              <label className="block text-[#475569] text-[12px] font-semibold mb-2">Plan Type</label>
              <select 
                value={selectedPlan}
                onChange={(e) => setSelectedPlan(e.target.value)}
                className="w-full bg-[#f1f5f9] text-[#0f172a] p-3 rounded-lg border border-slate-300 focus:outline-none focus:border-[#8083ff] text-[14px]"
              >
                {plans.length > 0 ? plans.map(p => (
                  <option key={p.id} value={p.name}>{p.name}</option>
                )) : (
                  <>
                    <option value="Basic">Basic</option>
                    <option value="Small Business">Small Business</option>
                    <option value="Enterprise">Enterprise</option>
                  </>
                )}
              </select>
            </div>

            <div className="flex justify-end gap-3">
              <button 
                onClick={() => setMembershipModal({isOpen: false, user: null})}
                className="px-4 py-2 rounded-lg bg-transparent border border-black/10 text-[#475569] hover:bg-black/5 font-semibold text-[14px] transition-all"
              >
                Cancel
              </button>
              <button 
                onClick={updateMembership}
                className="px-4 py-2 rounded-lg bg-[#8083ff] hover:bg-[#c0c1ff] text-[#0d0096] font-bold text-[14px] transition-all border-none"
              >
                Save
              </button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}
