"use client";

import React, { useState } from 'react';
import { X, Plus, Trash2, Save, Loader2 } from 'lucide-react';
import { updatePricingPlanDetail } from '@/app/actions/plans';
import { toast } from 'react-hot-toast';

interface PlanEditModalProps {
  isOpen: boolean;
  onClose: () => void;
  plan: any;
  currentCycle: 'monthly' | 'yearly';
}

export default function PlanEditModal({ isOpen, onClose, plan, currentCycle }: PlanEditModalProps) {
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: plan.name,
    priceXOF: plan.priceXOF,
    yearlyPriceXOF: plan.yearlyPriceXOF || '',
    priceEUR: plan.priceEUR,
    yearlyPriceEUR: plan.yearlyPriceEUR || '',
    description: plan.description,
    offerLimit: plan.offerLimit.toString(),
    recommended: plan.recommended,
    color: plan.color,
  });
  const [features, setFeatures] = useState<string[]>(plan.features || []);

  const handleAddFeature = () => {
    setFeatures([...features, '']);
  };

  const handleFeatureChange = (index: number, value: string) => {
    const newFeatures = [...features];
    newFeatures[index] = value;
    setFeatures(newFeatures);
  };

  const handleRemoveFeature = (index: number) => {
    setFeatures(features.filter((_, i) => i !== index));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const result = await updatePricingPlanDetail(plan.id, {
        ...formData,
        features: features.filter(f => f.trim() !== ''),
      });
      if (result.success) {
        toast.success("Détails du forfait mis à jour !");
        onClose();
        window.location.reload(); // Refresh to catch changes
      } else {
        toast.error(result.error || "Erreur lors de la sauvegarde.");
      }
    } catch (error) {
      toast.error("Erreur réseau");
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 sm:p-6">
      <div className="fixed inset-0 bg-slate-950/80 backdrop-blur-sm transition-opacity" onClick={onClose}></div>
      
      <div className="relative bg-slate-900 border border-slate-700 w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col transition-all">
        {/* Header */}
        <div className="p-6 border-b border-slate-700 flex justify-between items-center bg-slate-800/50">
          <div>
            <h2 className="text-xl font-bold text-white font-serif">Modifier le plan {plan.tier}</h2>
            <p className="text-sm text-slate-400">
              Édition du mode <span className="text-indigo-400 font-bold uppercase">{currentCycle === 'yearly' ? 'Annuel' : 'Mensuel'}</span>
            </p>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-white transition-colors">
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 overflow-y-auto flex-1">
          <form id="plan-form" onSubmit={handleSubmit} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <label className="text-sm font-medium text-slate-400 font-sans uppercase tracking-wider">Nom affiché</label>
                <input 
                  value={formData.name}
                  onChange={(e) => setFormData({...formData, name: e.target.value})}
                  className="w-full bg-slate-950 border border-slate-700 rounded-xl p-3 text-white focus:outline-none focus:border-indigo-500 transition-colors"
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium text-slate-400 font-sans uppercase tracking-wider">Limite d'offres</label>
                <input 
                  type="number"
                  value={formData.offerLimit}
                  onChange={(e) => setFormData({...formData, offerLimit: e.target.value})}
                  className="w-full bg-slate-950 border border-slate-700 rounded-xl p-3 text-white focus:outline-none focus:border-indigo-500 transition-colors"
                />
              </div>
              
              {currentCycle === 'monthly' ? (
                <>
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-slate-400 font-sans uppercase tracking-wider">Prix XOF (Mensuel)</label>
                    <input 
                      value={formData.priceXOF}
                      onChange={(e) => setFormData({...formData, priceXOF: e.target.value})}
                      className="w-full bg-slate-950 border border-slate-700 rounded-xl p-3 text-white focus:outline-none focus:border-indigo-500 transition-colors"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-slate-400 font-sans uppercase tracking-wider">Prix EUR (Mensuel)</label>
                    <input 
                      value={formData.priceEUR}
                      onChange={(e) => setFormData({...formData, priceEUR: e.target.value})}
                      className="w-full bg-slate-950 border border-slate-700 rounded-xl p-3 text-white focus:outline-none focus:border-indigo-500 transition-colors"
                    />
                  </div>
                </>
              ) : (
                <>
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-slate-400 font-sans uppercase tracking-wider">Prix XOF (Annuel)</label>
                    <input 
                      value={formData.yearlyPriceXOF}
                      onChange={(e) => setFormData({...formData, yearlyPriceXOF: e.target.value})}
                      placeholder="ex: 45 000 FCFA"
                      className="w-full bg-slate-950 border border-slate-700 rounded-xl p-3 text-white focus:outline-none focus:border-indigo-500 transition-colors shadow-[0_0_10px_rgba(16,185,129,0.1)] border-emerald-500/30"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-slate-400 font-sans uppercase tracking-wider">Prix EUR (Annuel)</label>
                    <input 
                      value={formData.yearlyPriceEUR}
                      onChange={(e) => setFormData({...formData, yearlyPriceEUR: e.target.value})}
                      placeholder="ex: 69 €"
                      className="w-full bg-slate-950 border border-slate-700 rounded-xl p-3 text-white focus:outline-none focus:border-indigo-500 transition-colors shadow-[0_0_10px_rgba(16,185,129,0.1)] border-emerald-500/30"
                    />
                  </div>
                </>
              )}
            </div>

            <div className="space-y-2">
              <label className="text-sm font-medium text-slate-400 font-sans uppercase tracking-wider">Description</label>
              <textarea 
                rows={2}
                value={formData.description}
                onChange={(e) => setFormData({...formData, description: e.target.value})}
                className="w-full bg-slate-950 border border-slate-700 rounded-xl p-3 text-white focus:outline-none focus:border-indigo-500 transition-colors resize-none"
              />
            </div>

            <div className="grid grid-cols-2 gap-6">
                <div className="space-y-2">
                    <label className="text-sm font-medium text-slate-400 font-sans uppercase tracking-wider">Couleur (Tailwind)</label>
                    <select 
                        value={formData.color}
                        onChange={(e) => setFormData({...formData, color: e.target.value})}
                        className="w-full bg-slate-950 border border-slate-700 rounded-xl p-3 text-white focus:outline-none focus:border-indigo-500 transition-colors"
                    >
                        <option value="gray">Gris (Starter)</option>
                        <option value="brand">Brand (Booster)</option>
                        <option value="amber">Amber (Empire)</option>
                        <option value="rose">Rose</option>
                        <option value="blue">Blue</option>
                    </select>
                </div>
                <div className="flex items-end pb-3">
                    <label className="flex items-center gap-3 cursor-pointer group">
                        <div className={`w-10 h-6 rounded-full transition-colors relative ${formData.recommended ? 'bg-indigo-600' : 'bg-slate-700'}`}>
                            <div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${formData.recommended ? 'translate-x-4' : ''}`} />
                        </div>
                        <input 
                            type="checkbox"
                            className="sr-only"
                            checked={formData.recommended}
                            onChange={(e) => setFormData({...formData, recommended: e.target.checked})}
                        />
                        <span className="text-sm font-medium text-slate-300 group-hover:text-white transition-colors uppercase tracking-wider">Mettre en avant</span>
                    </label>
                </div>
            </div>

            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <label className="text-sm font-medium text-slate-400 font-sans uppercase tracking-wider">Avantages du plan</label>
                <button 
                  type="button" 
                  onClick={handleAddFeature}
                  className="text-xs font-bold text-indigo-400 hover:text-indigo-300 flex items-center gap-1 uppercase tracking-tight"
                >
                  <Plus className="w-3 h-3" /> Ajouter un avantage
                </button>
              </div>
              <div className="space-y-3">
                {features.map((feature, index) => (
                  <div key={index} className="flex gap-2">
                    <input 
                      value={feature}
                      onChange={(e) => handleFeatureChange(index, e.target.value)}
                      placeholder="Ex: 50 Offres produits"
                      className="flex-1 bg-slate-950 border border-slate-700 rounded-xl p-3 text-white focus:outline-none focus:border-indigo-500 transition-colors"
                    />
                    <button 
                      type="button"
                      onClick={() => handleRemoveFeature(index)}
                      className="p-3 text-slate-500 hover:text-rose-500 bg-slate-950 border border-slate-700 rounded-xl transition-colors"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                ))}
              </div>
            </div>
          </form>
        </div>

        {/* Footer */}
        <div className="p-6 border-t border-slate-700 bg-slate-800/50 flex justify-end gap-3">
          <button 
            type="button" 
            onClick={onClose}
            className="px-6 py-2.5 rounded-xl font-bold text-slate-400 hover:text-white border border-slate-700 hover:bg-slate-700 transition-all uppercase tracking-wider text-sm"
          >
            Annuler
          </button>
          <button 
            type="submit" 
            form="plan-form"
            disabled={loading}
            className="px-8 py-2.5 bg-indigo-600 hover:bg-indigo-700 disabled:bg-slate-700 text-white rounded-xl font-bold transition-all shadow-lg flex items-center gap-2 uppercase tracking-wider text-sm"
          >
            {loading ? <Loader2 className="w-5 h-5 animate-spin" /> : <Save className="w-5 h-5" />}
            Sauvegarder
          </button>
        </div>
      </div>
    </div>
  );
}
