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

export default function ManagePlans() {
  const [plans, setPlans] = useState<any[]>([]);
  const { token, user } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    if (user?.role !== 'superadmin') {
      navigate('/dashboard');
      return;
    }
    fetchPlans();
  }, [user]);

  const fetchPlans = async () => {
    try {
      const res = await axios.get('/api/plans');
      setPlans(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  const handleUpdate = async (id: number, planData: any) => {
    try {
      await axios.put(`/api/plans/${id}`, planData, {
        headers: { Authorization: `Bearer ${token}` }
      });
      alert('Plan updated successfully!');
      fetchPlans();
    } catch (err) {
      alert('Failed to update plan');
    }
  };

  const handleFeatureChange = (planId: number, index: number, val: string) => {
    setPlans(prev => prev.map(p => {
      if (p.id === planId) {
        const feats = [...p.features];
        feats[index] = val;
        return { ...p, features: feats };
      }
      return p;
    }));
  };

  const addFeature = (planId: number) => {
    setPlans(prev => prev.map(p => {
      if (p.id === planId) {
        return { ...p, features: [...p.features, ''] };
      }
      return p;
    }));
  };

  const removeFeature = (planId: number, index: number) => {
    setPlans(prev => prev.map(p => {
      if (p.id === planId) {
        const feats = [...p.features];
        feats.splice(index, 1);
        return { ...p, features: feats };
      }
      return p;
    }));
  };

  const handleInputChange = (planId: number, field: string, val: any) => {
    setPlans(prev => prev.map(p => {
      if (p.id === planId) return { ...p, [field]: val };
      return p;
    }));
  };

  return (
    <div className="font-body-md text-body-md overflow-x-hidden min-h-screen bg-[#f8fafc] text-[#0f172a] -mt-5 -mx-3 px-3 py-10" style={{ fontFamily: 'Inter, sans-serif' }}>
      <div className="px-4 py-8 max-w-[1200px] mx-auto">
        
        <div className="flex justify-between items-center mb-10">
          <div>
            <h1 className="font-display-lg text-[32px] md:text-[48px] font-bold leading-tight text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>
              Manage Pricing Plans
            </h1>
            <p className="font-body-lg text-[16px] md:text-[18px] text-[#475569] mt-2">Edit the text and features displayed on the public landing page.</p>
          </div>
          <button onClick={() => navigate('/dashboard')} className="flex items-center gap-2 px-6 py-3 rounded-lg border border-slate-300 hover:bg-[#1a233a] transition-colors">
            <span className="material-symbols-outlined text-[20px]">arrow_back</span>
            Back to Dashboard
          </button>
        </div>

        <div className="space-y-12">
          {plans.map(plan => (
            <div key={plan.id} className="glass-card p-8 rounded-2xl border border-slate-300">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                
                {/* Details Form */}
                <div className="space-y-4">
                  <h2 className="text-[24px] font-bold text-[#0f172a] mb-4" style={{ fontFamily: 'Outfit, sans-serif' }}>Plan Details</h2>
                  
                  <div>
                    <label className="block text-[14px] text-[#475569] mb-1">Plan Name</label>
                    <input 
                      type="text" 
                      value={plan.name} 
                      onChange={(e) => handleInputChange(plan.id, 'name', e.target.value)}
                      className="w-full bg-white border border-slate-300 rounded-lg p-3 text-[#0f172a] focus:outline-none focus:border-[#8083ff]" 
                    />
                  </div>
                  
                  <div>
                    <label className="block text-[14px] text-[#475569] mb-1">Subtitle</label>
                    <input 
                      type="text" 
                      value={plan.subtitle} 
                      onChange={(e) => handleInputChange(plan.id, 'subtitle', e.target.value)}
                      className="w-full bg-white border border-slate-300 rounded-lg p-3 text-[#0f172a] focus:outline-none focus:border-[#8083ff]" 
                    />
                  </div>
                  
                  <div className="flex gap-4">
                    <div className="flex-1">
                      <label className="block text-[14px] text-[#475569] mb-1">Price ($/yr)</label>
                      <input 
                        type="number" 
                        value={plan.price} 
                        onChange={(e) => handleInputChange(plan.id, 'price', Number(e.target.value))}
                        className="w-full bg-white border border-slate-300 rounded-lg p-3 text-[#0f172a] focus:outline-none focus:border-[#8083ff]" 
                      />
                    </div>
                    <div className="flex-1 flex items-center mt-6">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input 
                          type="checkbox" 
                          checked={plan.isPopular === 1}
                          onChange={(e) => handleInputChange(plan.id, 'isPopular', e.target.checked ? 1 : 0)}
                          className="w-5 h-5 accent-[#8083ff]"
                        />
                        <span className="text-[#0f172a]">Highlight as Popular</span>
                      </label>
                    </div>
                  </div>
                </div>

                {/* Features List */}
                <div>
                  <div className="flex justify-between items-center mb-4">
                    <h2 className="text-[24px] font-bold text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>Features</h2>
                    <button onClick={() => addFeature(plan.id)} className="text-[#8083ff] hover:text-[#c0c1ff] text-[14px] font-bold flex items-center gap-1">
                      <span className="material-symbols-outlined text-[16px]">add</span> Add Feature
                    </button>
                  </div>
                  
                  <div className="space-y-3">
                    {plan.features.map((feat: string, idx: number) => (
                      <div key={idx} className="flex gap-2">
                        <input 
                          type="text" 
                          value={feat} 
                          onChange={(e) => handleFeatureChange(plan.id, idx, e.target.value)}
                          className="flex-1 bg-white border border-slate-300 rounded-lg p-3 text-[#0f172a] focus:outline-none focus:border-[#8083ff]" 
                          placeholder="Feature description"
                        />
                        <button onClick={() => removeFeature(plan.id, idx)} className="w-12 h-12 bg-[#ffb4ab]/10 text-[#ffb4ab] rounded-lg flex items-center justify-center hover:bg-[#ffb4ab]/20 transition-colors">
                          <span className="material-symbols-outlined">delete</span>
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              <div className="mt-8 pt-6 border-t border-slate-300 flex justify-end">
                <button onClick={() => handleUpdate(plan.id, plan)} className="bg-[#8083ff] text-[#0d0096] px-8 py-3 rounded-xl font-bold primary-glow hover:scale-105 transition-transform active:scale-95">
                  Save Changes
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
