import { useState, useEffect } from "react";
import SectionCard from "./SectionCard";
import { getAjaxUrl, getNonce } from "../../utils/api";
import { getAdminConfig } from "../../utils/helpers";

export default function ImageSizesSection() {
  const config = getAdminConfig();
  const [sizes, setSizes] = useState(config.image_sizes || []);
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    width: "",
    height: "",
    crop: false,
  });
  const [message, setMessage] = useState({ type: null, text: "" });

  const handleAdd = async (e) => {
    e.preventDefault();
    setMessage({ type: null, text: "" });

    if (!formData.name.trim() || !formData.width || !formData.height) {
      setMessage({ type: "error", text: "Please fill all fields." });
      return;
    }

    // Validate reserved WordPress names
    const reserved = ["thumbnail", "medium", "medium_large", "medium-large", "large"];
    const sanitizedName = formData.name.trim().toLowerCase().replace(/[^a-z0-9_-]/g, "-");
    if (reserved.includes(sanitizedName)) {
      setMessage({ type: "error", text: "This name is reserved by WordPress. Please use a different name." });
      return;
    }

    // Check for duplicate names
    if (sizes.some(size => size.name === sanitizedName)) {
      setMessage({ type: "error", text: "A size with this name already exists. Please use a different name." });
      return;
    }

    // Validate maximum dimensions
    if (parseInt(formData.width) > 1920) {
      setMessage({ type: "error", text: "Width must not exceed 1920 pixels." });
      return;
    }
    if (parseInt(formData.height) > 3000) {
      setMessage({ type: "error", text: "Height must not exceed 3000 pixels." });
      return;
    }

    setLoading(true);
    try {
      const fd = new FormData();
      fd.append("action", "ai_image_add_custom_size");
      fd.append("nonce", getNonce());
      fd.append("name", formData.name.trim());
      fd.append("width", formData.width);
      fd.append("height", formData.height);
      fd.append("crop", formData.crop ? "1" : "0");

      const res = await fetch(getAjaxUrl(), { method: "POST", body: fd });
      const data = await res.json();

      if (data.success) {
        setMessage({ type: "success", text: data.data?.message || "Size added." });
        setSizes(data.data?.sizes || []);
        setFormData({ name: "", width: "", height: "", crop: false });
      } else {
        setMessage({ type: "error", text: data.data?.message || "Failed to add size." });
      }
    } catch (error) {
      setMessage({ type: "error", text: error?.message || "Failed to add size." });
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (name) => {
    if (!confirm(`Delete image size "${name}"?`)) return;

    setLoading(true);
    setMessage({ type: null, text: "" });
    try {
      const fd = new FormData();
      fd.append("action", "ai_image_delete_custom_size");
      fd.append("nonce", getNonce());
      fd.append("name", name);

      const res = await fetch(getAjaxUrl(), { method: "POST", body: fd });
      const data = await res.json();

      if (data.success) {
        setMessage({ type: "success", text: data.data?.message || "Size deleted." });
        setSizes(data.data?.sizes || []);
      } else {
        setMessage({ type: "error", text: data.data?.message || "Failed to delete size." });
      }
    } catch (error) {
      setMessage({ type: "error", text: error?.message || "Failed to delete size." });
    } finally {
      setLoading(false);
    }
  };

  // Auto-hide success message after 3 seconds
  useEffect(() => {
    if (message.type === "success") {
      const timer = setTimeout(() => {
        setMessage({ type: null, text: "" });
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [message]);

  return (
    <div className="space-y-6">
      <SectionCard
        title="Add Image Size"
        description="Enter a name, width, and height for your custom image size."
      >
        <form onSubmit={handleAdd} className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
            <div>
              <label htmlFor="size-name" className="block text-sm font-medium text-gray-700 mb-1.5">
                Name
              </label>
              <input
                id="size-name"
                type="text"
                value={formData.name}
                onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
                placeholder="custom-size"
                disabled={loading}
                className="block w-full rounded-md border border-gray-200 px-3 py-2 text-sm outline-none focus:border-gray-400 focus:ring-0 disabled:opacity-50 transition-colors"
              />
            </div>
            <div>
              <label htmlFor="size-width" className="block text-sm font-medium text-gray-700 mb-1.5">
                Width (px)
              </label>
              <input
                id="size-width"
                type="number"
                min={1}
                max={1920}
                value={formData.width}
                onChange={(e) => setFormData((prev) => ({ ...prev, width: e.target.value }))}
                placeholder="1200"
                disabled={loading}
                className="block w-full rounded-md border border-gray-200 px-3 py-2 text-sm outline-none focus:border-gray-400 focus:ring-0 disabled:opacity-50 transition-colors"
              />
            </div>
            <div>
              <label htmlFor="size-height" className="block text-sm font-medium text-gray-700 mb-1.5">
                Height (px)
              </label>
              <input
                id="size-height"
                type="number"
                min={1}
                max={3000}
                value={formData.height}
                onChange={(e) => setFormData((prev) => ({ ...prev, height: e.target.value }))}
                placeholder="900"
                disabled={loading}
                className="block w-full rounded-md border border-gray-200 px-3 py-2 text-sm outline-none focus:border-gray-400 focus:ring-0 disabled:opacity-50 transition-colors"
              />
            </div>
            <div>
              <label htmlFor="size-crop" className="block text-sm font-medium text-gray-700 mb-1.5">
                Crop
              </label>
              <select
                id="size-crop"
                value={formData.crop ? "yes" : "no"}
                onChange={(e) => setFormData((prev) => ({ ...prev, crop: e.target.value === "yes" }))}
                disabled={loading}
                className="block w-full rounded-md border border-gray-200 px-3 py-2 text-sm outline-none focus:border-gray-400 focus:ring-0 disabled:opacity-50 transition-colors"
              >
                <option value="no">No</option>
                <option value="yes">Yes</option>
              </select>
            </div>
          </div>
          <div className="flex items-center gap-3 pt-1">
            <button
              type="submit"
              disabled={loading}
              className="inline-flex items-center px-5 py-2.5 bg-gray-800 text-white text-sm font-medium rounded-md hover:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-gray-600 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {loading ? "Adding…" : "Add Image Size"}
            </button>
            {message.text && (
              <span className={`text-sm font-medium ${message.type === "success" ? "text-green-600" : "text-red-600"}`}>
                {message.text}
              </span>
            )}
          </div>
          <div className="mt-4 p-3.5 bg-gray-50 rounded-md border border-gray-100">
            <div className="flex gap-2">
              <svg className="w-4 h-4 text-gray-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <div className="flex-1 space-y-1 text-xs text-gray-600">
                <p><span className="font-medium text-gray-700">Name:</span> Lowercase letters, numbers, hyphens, or underscores. Avoid reserved names (thumbnail, medium, large).</p>
                <p><span className="font-medium text-gray-700">Width:</span> Max 1920px. <span className="font-medium text-gray-700">Height:</span> Max 3000px.</p>
                <p><span className="font-medium text-gray-700">Crop:</span> Yes = crop to exact dimensions. No = resize proportionally (may be smaller).</p>
              </div>
            </div>
          </div>
        </form>
      </SectionCard>

      <SectionCard
        title="Current Image Sizes"
        description="Image sizes listed below are currently enabled on your site."
      >
        <div className="overflow-x-auto rounded-lg border border-gray-100">
          <table className="min-w-full divide-y divide-gray-100">
            <thead>
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Label</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Width</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Height</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Crop</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {sizes.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-4 py-5 text-sm text-gray-500 text-center">
                    No image sizes found.
                  </td>
                </tr>
              ) : (
                sizes.map((size) => (
                  <tr key={size.name} className="hover:bg-gray-50/50 transition-colors">
                    <td className="px-4 py-3 text-sm font-medium text-gray-800">{size.label}</td>
                    <td className="px-4 py-3 text-xs text-gray-600 font-mono">{size.name}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{size.width || "—"}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{size.height || "—"}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{size.crop ? "Yes" : "No"}</td>
                    <td className="px-4 py-3 text-sm">
                      {size.source === "custom" ? (
                        <button
                          type="button"
                          onClick={() => handleDelete(size.name)}
                          disabled={loading}
                          className="text-red-600 hover:text-red-700 font-medium disabled:opacity-50 transition-colors"
                        >
                          Delete
                        </button>
                      ) : (
                        <span className="inline-flex items-center px-2 py-0.5 rounded bg-gray-100 text-gray-500 text-xs font-medium">
                          WordPress
                        </span>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </SectionCard>
    </div>
  );
}
