"use client";

import { useState } from "react";
import { updateGenericSettings } from "@/app/actions/settings";

export default function AboutSettingsForm({ initialSettings }: { initialSettings: Record<string, string> }) {
  const [settings, setSettings] = useState({
    about_hero_image: initialSettings.about_hero_image || "/images/gallery/img_7.jpg",
    about_hero_title: initialSettings.about_hero_title || "Our Story",
    about_hero_desc: initialSettings.about_hero_desc || "Escape to the tranquil shores of Lazuli Hotel for a rejuvenating getaway in Marsa Alam.",
    about_content_title: initialSettings.about_content_title || "A Sanctuary by the Red Sea",
    about_content_p1: initialSettings.about_content_p1 || "Located on the pristine coastline of Marsa Alam, Lazuli Hotel is a 5-star beachfront property designed for ultimate relaxation and adventure. With our Moroccan-inspired architecture blending seamlessly into the natural beauty of the Red Sea, we offer an unforgettable experience.",
    about_content_p2: initialSettings.about_content_p2 || "Whether you're exploring our vibrant house reef, unwinding in our lavish infinity pools, or indulging in world-class dining, every moment at Lazuli is crafted to perfection."
  });

  const [images, setImages] = useState<string[]>(
    initialSettings.about_content_images ? JSON.parse(initialSettings.about_content_images) : ["/images/gallery/img_5.jpg", "/images/gallery/img_6.jpg"]
  );

  const [loading, setLoading] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setSettings({ ...settings, [e.target.name]: e.target.value });
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>, targetKey: string | null = null) => {
    const file = e.target.files?.[0];
    if (!file) return;

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

    try {
      const res = await fetch("/api/upload", { method: "POST", body: formData });
      const data = await res.json();
      if (data.success) {
        if (targetKey) {
          setSettings({ ...settings, [targetKey]: data.url });
        } else {
          setImages([...images, data.url]);
        }
      } else {
        alert("Upload failed: " + data.message);
      }
    } catch (error) {
      console.error(error);
      alert("Error uploading file");
    } finally {
      setLoading(false);
      e.target.value = '';
    }
  };

  const handleRemoveImage = (idx: number) => {
    setImages(images.filter((_, i) => i !== idx));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const updates = Object.entries(settings).map(([key, value]) => ({ key, value }));
      updates.push({ key: "about_content_images", value: JSON.stringify(images) });
      
      await updateGenericSettings(updates);
      alert("About page settings saved successfully!");
    } catch (error) {
      alert("Error saving settings.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
      <div>
        <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "500", color: "#475569" }}>Hero Image</label>
        <div style={{ display: "flex", gap: "1rem", alignItems: "center", marginBottom: "1rem" }}>
          <img src={settings.about_hero_image} alt="Hero Preview" style={{ width: "100px", height: "60px", objectFit: "cover", borderRadius: "0.25rem" }} />
          <label style={{ padding: "0.5rem 1rem", backgroundColor: "#e2e8f0", border: "1px dashed #94a3b8", borderRadius: "0.375rem", cursor: loading ? "not-allowed" : "pointer" }}>
            Upload New Image
            <input type="file" accept="image/*" onChange={(e) => handleFileUpload(e, "about_hero_image")} style={{ display: "none" }} disabled={loading} />
          </label>
        </div>
      </div>

      <div>
        <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "500", color: "#475569" }}>Hero Title</label>
        <input type="text" name="about_hero_title" value={settings.about_hero_title} onChange={handleChange} required style={{ width: "100%", padding: "0.75rem", borderRadius: "0.375rem", border: "1px solid #cbd5e1" }} />
      </div>

      <div>
        <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "500", color: "#475569" }}>Hero Description</label>
        <textarea name="about_hero_desc" value={settings.about_hero_desc} onChange={handleChange} rows={2} required style={{ width: "100%", padding: "0.75rem", borderRadius: "0.375rem", border: "1px solid #cbd5e1" }}></textarea>
      </div>

      <hr style={{ borderTop: "1px solid #e2e8f0" }} />

      <div>
        <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "500", color: "#475569" }}>Content Title</label>
        <input type="text" name="about_content_title" value={settings.about_content_title} onChange={handleChange} required style={{ width: "100%", padding: "0.75rem", borderRadius: "0.375rem", border: "1px solid #cbd5e1" }} />
      </div>

      <div>
        <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "500", color: "#475569" }}>Content Paragraph 1</label>
        <textarea name="about_content_p1" value={settings.about_content_p1} onChange={handleChange} rows={4} required style={{ width: "100%", padding: "0.75rem", borderRadius: "0.375rem", border: "1px solid #cbd5e1" }}></textarea>
      </div>

      <div>
        <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "500", color: "#475569" }}>Content Paragraph 2</label>
        <textarea name="about_content_p2" value={settings.about_content_p2} onChange={handleChange} rows={4} required style={{ width: "100%", padding: "0.75rem", borderRadius: "0.375rem", border: "1px solid #cbd5e1" }}></textarea>
      </div>

      <div>
        <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "500", color: "#475569" }}>Content Images</label>
        <div style={{ display: "flex", flexWrap: "wrap", gap: "0.5rem", marginBottom: "1rem" }}>
          {images.map((img, i) => (
            <div key={i} style={{ position: "relative", width: "100px", height: "100px" }}>
              <img src={img} alt={`Img ${i}`} style={{ width: "100%", height: "100%", objectFit: "cover", borderRadius: "0.25rem" }} />
              <button type="button" onClick={() => handleRemoveImage(i)} style={{ position: "absolute", top: 0, right: 0, background: "red", color: "white", border: "none", cursor: "pointer", padding: "0.2rem 0.4rem" }}>X</button>
            </div>
          ))}
        </div>
        <label style={{ padding: "0.75rem", backgroundColor: "#e2e8f0", border: "1px dashed #94a3b8", borderRadius: "0.375rem", display: "inline-block", cursor: loading ? "not-allowed" : "pointer" }}>
          {loading ? "Uploading..." : "Upload New Image"}
          <input type="file" accept="image/*" onChange={(e) => handleFileUpload(e, null)} disabled={loading} style={{ display: "none" }} />
        </label>
      </div>

      <button type="submit" disabled={loading} className="btn btn-primary" style={{ padding: "0.75rem 1.5rem", alignSelf: "flex-start", backgroundColor: "#1e293b", color: "white", border: "none", borderRadius: "0.375rem", cursor: "pointer", marginTop: "1rem" }}>
        Save About Settings
      </button>
    </form>
  );
}
