"use client";

import { useState, useTransition } from 'react';
import { setFeaturedBusiness, removeFeaturedBusiness } from '@/app/actions/business';
import { Star, X, Loader2, Save } from 'lucide-react';
import { toast } from 'react-hot-toast';

interface Props {
  business: {
    id: string;
    name: string;
    isFeatured: boolean;
    founderName?: string | null;
    founderImageUrl?: string | null;
    keyMetric?: string | null;
  };
}

export default function FeaturedModal({ business }: Props) {
  const [isOpen, setIsOpen] = useState(false);
  const [isPending, startTransition] = useTransition();

  const handleToggleFeature = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);
    const data = {
      founderName: formData.get('founderName') as string,
      founderImageUrl: formData.get('founderImageUrl') as string,
      keyMetric: formData.get('keyMetric') as string,
    };

    startTransition(async () => {
      const result = await setFeaturedBusiness(business.id, data);
      if (result.success) {
        toast.success("Entrepreneur du mois mis à jour !");
        setIsOpen(false);
      } else {
        toast.error(result.error || "Une erreur est survenue");
      }
    });
  };

  const handleRemove = async () => {
    if (confirm("Retirer cet entrepreneur du titre 'Entrepreneur du mois' ?")) {
      startTransition(async () => {
        const result = await removeFeaturedBusiness(business.id);
        if (result.success) {
          toast.success("Titre révoqué");
          setIsOpen(false);
        } else {
          toast.error(result.error || "Une erreur est survenue lors de la suppression");
        }
      });
    }
  };

  return (
    <>
      <button 
        onClick={() => setIsOpen(true)}
        className={`px-3 py-1.5 rounded-lg border text-sm font-medium transition-all flex items-center gap-2 mx-auto ${
          business.isFeatured 
            ? 'bg-amber-500/10 border-amber-500/50 text-amber-500 hover:bg-amber-500/20' 
            : 'bg-slate-800 border-slate-700 text-slate-400 hover:border-slate-500 hover:text-white'
        }`}
      >
        <Star className={`w-4 h-4 ${business.isFeatured ? 'fill-amber-500' : ''}`} />
        {business.isFeatured ? 'Vedette Active' : 'Mettre en avant'}
      </button>

      {isOpen && (
        <div className="modal-overlay">
          <div className="modal-content">
            <button 
              onClick={() => setIsOpen(false)}
              className="absolute top-4 right-4 text-slate-500 hover:text-white"
            >
              <X className="w-6 h-6" />
            </button>

            <div className="mb-6">
              <h2 className="text-2xl font-bold text-white mb-2">💰 Entrepreneur du Mois</h2>
              <p className="text-slate-400">Configurez les détails pour {business.name}.</p>
            </div>

            <form onSubmit={handleToggleFeature} className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-medium text-slate-400">Nom du fondateur</label>
                <input 
                  name="founderName" 
                  defaultValue={business.founderName || ''}
                  required 
                  className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-amber-500"
                  placeholder="Ex: Aliko Dangote"
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-slate-400">URL Photo du fondateur</label>
                <input 
                  name="founderImageUrl" 
                  defaultValue={business.founderImageUrl || ''}
                  required 
                  className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-amber-500"
                  placeholder="https://..."
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-slate-400">Métrique Clé (ex: Chiffre d'affaires, Impact)</label>
                <input 
                  name="keyMetric" 
                  defaultValue={business.keyMetric || ''}
                  required 
                  className="w-full bg-slate-900 border border-slate-700 rounded-lg p-3 text-white focus:outline-none focus:border-amber-500"
                  placeholder="Ex: +500 emplois créés"
                />
              </div>

              <div className="pt-4 flex flex-col gap-3">
                <button 
                  type="submit" 
                  disabled={isPending}
                  className="w-full bg-amber-500 hover:bg-amber-600 text-slate-900 font-bold py-3 rounded-lg flex items-center justify-center gap-2 transition-colors"
                >
                  {isPending ? <Loader2 className="w-5 h-5 animate-spin" /> : <Save className="w-5 h-5" />}
                  Définir comme Entrepreneur du Mois
                </button>

                {business.isFeatured && (
                  <button 
                    type="button"
                    onClick={handleRemove}
                    disabled={isPending}
                    className="w-full bg-slate-800 hover:bg-red-900/30 text-red-400 font-semibold py-3 rounded-lg transition-colors border border-red-900/50"
                  >
                    Révoquer le titre
                  </button>
                )}
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  );
}
