"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Upload, Plus, X } from "lucide-react";

type ProjectFormData = {
  title: string;
  partner: string;
  tag: string;
  tagColor: string;
  location: string;
  period: string;
  description: string;
  outcomes: string[];
  image: string;
  published: boolean;
  order: number;
};

const TAGS = [
  { name: "Nutrition", color: "#E67E22" },
  { name: "Sécurité alimentaire", color: "#1E40AF" },
  { name: "Résilience", color: "#4A7C59" },
  { name: "Genre", color: "#9B59B6" },
  { name: "Suivi-Évaluation", color: "#E74C3C" },
  { name: "Nutrition maternelle", color: "#E91E63" },
];

export default function ProjectForm({ projectId, onSuccess, onCancel }: { projectId?: string; onSuccess?: () => void; onCancel?: () => void }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [formData, setFormData] = useState<ProjectFormData>({
    title: "",
    partner: "",
    tag: "Nutrition",
    tagColor: "#E67E22",
    location: "",
    period: "",
    description: "",
    outcomes: [""],
    image: "",
    published: false,
    order: 0,
  });

  useEffect(() => {
    if (projectId) {
      fetch(`/api/admin/projects/${projectId}`)
        .then((res) => res.json())
        .then((data) => setFormData(data));
    }
  }, [projectId]);

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    const formData = new FormData();
    formData.append("file", file);

    try {
      const res = await fetch("/api/upload", {
        method: "POST",
        body: formData,
      });
      const data = await res.json();
      setFormData((prev) => ({ ...prev, image: data.url }));
    } catch (error) {
      console.error("Upload error:", error);
      alert("Erreur lors du téléchargement");
    } finally {
      setUploading(false);
    }
  };

  const addOutcome = () => {
    setFormData({ ...formData, outcomes: [...formData.outcomes, ""] });
  };

  const updateOutcome = (index: number, value: string) => {
    const newOutcomes = [...formData.outcomes];
    newOutcomes[index] = value;
    setFormData({ ...formData, outcomes: newOutcomes });
  };

  const removeOutcome = (index: number) => {
    const newOutcomes = formData.outcomes.filter((_, i) => i !== index);
    setFormData({ ...formData, outcomes: newOutcomes });
  };

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

    try {
      const url = projectId
        ? `/api/admin/projects/${projectId}`
        : "/api/admin/projects";
      const method = projectId ? "PUT" : "POST";

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (res.ok) {
        if (onSuccess) { onSuccess(); } else { router.push("/admin/projets"); router.refresh(); }
      } else {
        alert("Erreur lors de l'enregistrement");
      }
    } catch (error) {
      console.error("Submit error:", error);
      alert("Erreur lors de l'enregistrement");
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Title */}
      <div>
        <label className="block text-sm font-bold text-gray-700 mb-2">
          Titre du projet <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          required
          value={formData.title}
          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
          className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59]"
          placeholder="Ex: Production d'aliments de complément"
        />
      </div>

      {/* Partner & Location */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-bold text-gray-700 mb-2">
            Partenaire <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            required
            value={formData.partner}
            onChange={(e) => setFormData({ ...formData, partner: e.target.value })}
            className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59]"
            placeholder="Ex: UNICEF · OMS"
          />
        </div>
        <div>
          <label className="block text-sm font-bold text-gray-700 mb-2">
            Localisation <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            required
            value={formData.location}
            onChange={(e) => setFormData({ ...formData, location: e.target.value })}
            className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59]"
            placeholder="Ex: Brakna · Gorgol"
          />
        </div>
      </div>

      {/* Tag & Period */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-bold text-gray-700 mb-2">
            Tag <span className="text-red-500">*</span>
          </label>
          <select
            required
            value={formData.tag}
            onChange={(e) => {
              const tag = TAGS.find((t) => t.name === e.target.value);
              setFormData({
                ...formData,
                tag: e.target.value,
                tagColor: tag?.color || "#E67E22",
              });
            }}
            className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59]"
          >
            {TAGS.map((tag) => (
              <option key={tag.name} value={tag.name}>
                {tag.name}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className="block text-sm font-bold text-gray-700 mb-2">
            Période <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            required
            value={formData.period}
            onChange={(e) => setFormData({ ...formData, period: e.target.value })}
            className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59]"
            placeholder="Ex: 2018–2022"
          />
        </div>
      </div>

      {/* Description */}
      <div>
        <label className="block text-sm font-bold text-gray-700 mb-2">
          Description <span className="text-red-500">*</span>
        </label>
        <textarea
          required
          rows={4}
          value={formData.description}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          className="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59] resize-none"
          placeholder="Description du projet..."
        />
      </div>

      {/* Outcomes */}
      <div>
        <div className="flex items-center justify-between mb-2">
          <label className="block text-sm font-bold text-gray-700">
            Résultats <span className="text-red-500">*</span>
          </label>
          <button
            type="button"
            onClick={addOutcome}
            className="flex items-center gap-1 text-sm text-[#4A7C59] hover:text-[#3d6849] font-medium"
          >
            <Plus size={16} />
            Ajouter
          </button>
        </div>
        <div className="space-y-3">
          {formData.outcomes.map((outcome, index) => (
            <div key={index} className="flex items-center gap-2">
              <input
                type="text"
                required
                value={outcome}
                onChange={(e) => updateOutcome(index, e.target.value)}
                className="flex-1 px-4 py-3 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#4A7C59] focus:border-[#4A7C59]"
                placeholder={`Résultat ${index + 1}`}
              />
              {formData.outcomes.length > 1 && (
                <button
                  type="button"
                  onClick={() => removeOutcome(index)}
                  className="p-2 text-red-600 hover:bg-red-50 rounded-lg"
                >
                  <X size={18} />
                </button>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Image Upload */}
      <div>
        <label className="block text-sm font-bold text-gray-700 mb-2">
          Image <span className="text-red-500">*</span>
        </label>
        <div className="relative">
          <input
            type="file"
            accept="image/*"
            onChange={handleImageUpload}
            className="hidden"
            id="project-image-upload"
          />
          <label
            htmlFor="project-image-upload"
            className="flex items-center justify-center gap-2 px-4 py-3 border-2 border-gray-200 rounded-xl cursor-pointer hover:bg-gray-50 transition-colors"
          >
            {uploading ? (
              <>
                <div className="w-5 h-5 border-2 border-[#4A7C59]/30 border-t-[#4A7C59] rounded-full animate-spin"></div>
                Téléchargement...
              </>
            ) : (
              <>
                <Upload size={18} />
                {formData.image ? "Changer l'image" : "Télécharger l'image"}
              </>
            )}
          </label>
        </div>
      </div>

      {/* Image Preview */}
      {formData.image && (
        <div className="relative w-full h-48 rounded-xl overflow-hidden border-2 border-gray-200">
          <img src={formData.image} alt="Preview" className="w-full h-full object-cover" />
        </div>
      )}

      {/* Published */}
      <div>
        <label className="flex items-center gap-2 cursor-pointer">
          <input
            type="checkbox"
            checked={formData.published}
            onChange={(e) => setFormData({ ...formData, published: e.target.checked })}
            className="w-5 h-5 rounded border-gray-300 text-[#4A7C59] focus:ring-[#4A7C59]"
          />
          <span className="text-sm font-medium text-gray-700">Publier immédiatement</span>
        </label>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-4 pt-4">
        <button
          type="submit"
          disabled={loading}
          className="px-8 py-3 bg-[#4A7C59] hover:bg-[#3d6849] text-white font-semibold rounded-xl transition-all disabled:opacity-50"
        >
          {loading ? "Enregistrement..." : projectId ? "Mettre à jour" : "Créer le projet"}
        </button>
        <button
          type="button"
          onClick={() => { if (onCancel) { onCancel(); } else { router.back(); } }}
          className="px-8 py-3 border-2 border-gray-300 hover:bg-gray-50 text-gray-700 font-semibold rounded-xl transition-all"
        >
          Annuler
        </button>
      </div>
    </form>
  );
}
