import React, { useState, useEffect } from "react";
import axios from "axios";
import { toast } from "react-toastify";

/* =====================
   Constants (Optimized)
===================== */
const API_BASE = process.env.REACT_APP_API_BASE_URL;

const SECTORS = [
    { label: "All", value: "All" },
    { label: "Water Supply", value: "Water Supply" },
    { label: "Storm Water", value: "Storm Water" },
    { label: "Electromechanical", value: "Electromechanical & Instrumentation" },
    { label: "Real Estate / Buildings", value: "Real estate / Buildings" },
    { label: "Tunnel", value: "Tunnel" },
    { label: "Roads", value: "Roads" },
    { label: "Wastewater / Sewerage", value: "Wastewater / Sewerage" },
    { label: "Irrigation", value: "Irrigation" },
    { label: "Renewable Energy", value: "Renewable Energy" },
];

const AddProjects = () => {
  const [projects, setProjects] = useState([]);
  const [sector, setSector] = useState("");
  const [image, setImage] = useState(null);
  const [imagePreview, setImagePreview] = useState(null);
  const [editMode, setEditMode] = useState(false);
  const [editProjectId, setEditProjectId] = useState(null);

  /* =====================
     Fetch Projects
  ===================== */
  const fetchProjects = async () => {
    try {
      const res = await axios.get(`${API_BASE}/api/projects`);
      setProjects(res.data);
    } catch (err) {
      console.error("Error fetching projects", err);
    }
  };

  useEffect(() => {
    fetchProjects();
  }, []);

  /* =====================
     Helpers
  ===================== */
  const resetForm = () => {
    setSector("");
    setImage(null);
    setImagePreview(null);
    setEditMode(false);
    setEditProjectId(null);
  };

  const handleImageChange = (e) => {
    const file = e.target.files[0];
    setImage(file);
    setImagePreview(file ? URL.createObjectURL(file) : null);
  };

  /* =====================
     Submit (Add / Update)
  ===================== */
  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!sector || (!editMode && !image)) {
      toast.error("Sector and image are required!");
      return;
    }

    const formData = new FormData();
    formData.append("sector", sector);
    if (image) formData.append("image", image);

    try {
      if (editMode) {
        await axios.post(
          `${API_BASE}/api/projects/update/${editProjectId}`,
          formData
        );
        toast.success("Project updated successfully!");
      } else {
        await axios.post(`${API_BASE}/api/projects`, formData);
        toast.success("Project added successfully!");
      }

      resetForm();
      fetchProjects();
    } catch (err) {
      console.error("Failed to save project", err);
      toast.error("Error saving project");
    }
  };

  /* =====================
     Edit Project
  ===================== */
  const handleEdit = (project) => {
    setSector(project.sector);
    setImage(null);
    setImagePreview(`${API_BASE}${project.image}`);
    setEditMode(true);
    setEditProjectId(project.id);
  };

  /* =====================
     Delete Project
  ===================== */
  const handleDelete = async (id) => {
    if (!window.confirm("Are you sure you want to delete this project?")) return;

    try {
      await axios.delete(`${API_BASE}/api/projects/${id}`);
      toast.success("Project deleted");
      fetchProjects();
    } catch (err) {
      console.error("Failed to delete", err);
      toast.error("Failed to delete project");
    }
  };

  return (
    <div className="p-6 min-h-screen bg-gray-50">
      <h1 className="text-3xl font-bold text-blue-900 mb-6">
        {editMode ? "Edit Project" : "Add New Project"}
      </h1>

      {/* FORM */}
      <form
        onSubmit={handleSubmit}
        className="space-y-4 max-w-md mx-auto bg-white p-6 rounded-lg shadow"
      >
        <select
          value={sector}
          onChange={(e) => setSector(e.target.value)}
          className="w-full border p-2 rounded"
        >
          <option value="">Select Sector</option>
          {SECTORS.map((s) => (
            <option key={s.value} value={s.value}>
              {s.label}
            </option>
          ))}
        </select>

        <input
          type="file"
          accept="image/*"
          onChange={handleImageChange}
          className="w-full"
        />

        {imagePreview && (
          <img
            src={imagePreview}
            alt="Preview"
            className="h-48 w-full object-cover rounded"
          />
        )}

        <div className="flex justify-between gap-4">
          <button
            type="submit"
            className="flex-1 bg-blue-900 text-white py-2 rounded hover:bg-blue-800"
          >
            {editMode ? "Update Project" : "Save Project"}
          </button>

          {editMode && (
            <button
              type="button"
              onClick={resetForm}
              className="flex-1 bg-gray-300 text-black py-2 rounded hover:bg-gray-400"
            >
              Cancel
            </button>
          )}
        </div>
      </form>

      {/* PROJECT LIST */}
      <div className="mt-10">
        <h2 className="text-2xl font-semibold text-blue-800 mb-4">
          All Projects
        </h2>

        <div className="grid md:grid-cols-3 sm:grid-cols-2 gap-6">
          {projects.map((proj) => (
            <div
              key={proj.id}
              className="bg-white p-4 rounded-xl shadow hover:shadow-lg transition-all"
            >
              <img
                src={`${API_BASE}${proj.image}`}
                alt={proj.sector}
                className="h-56 w-full object-cover rounded mb-3"
              />

              <p className="text-sm text-gray-700 capitalize mb-1">
                Sector: {proj.sector}
              </p>

              <div className="flex justify-between mt-2">
                <button
                  onClick={() => handleEdit(proj)}
                  className="text-blue-600 hover:underline"
                >
                  Edit
                </button>
                <button
                  onClick={() => handleDelete(proj.id)}
                  className="text-red-600 hover:underline"
                >
                  Delete
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default AddProjects;
