"use client";

import { useState, useEffect } from "react";

interface Story {
  title: string;
  photo_url: string;
  description: string;
}

const emptyStory: Story = { title: "", photo_url: "", description: "" };

export default function ManageStoriesPage() {
  const [stories, setStories] = useState<Story[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    // /api/stories now reads user_id from session when the param is absent;
    // no need for the round-trip through /api/user.
    fetch("/api/stories")
      .then((res) => res.json())
      .then((data) => {
        if (data.stories && data.stories.length > 0) {
          setStories(data.stories);
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  function addStory() {
    if (stories.length >= 20) return;
    setStories([...stories, { ...emptyStory }]);
  }

  function removeStory(index: number) {
    setStories(stories.filter((_, i) => i !== index));
  }

  function updateStory(index: number, field: keyof Story, value: string) {
    const updated = [...stories];
    updated[index] = { ...updated[index], [field]: value };
    setStories(updated);
  }

  function moveStory(index: number, direction: -1 | 1) {
    const newIndex = index + direction;
    if (newIndex < 0 || newIndex >= stories.length) return;
    const updated = [...stories];
    [updated[index], updated[newIndex]] = [updated[newIndex], updated[index]];
    setStories(updated);
  }

  async function handleSave() {
    setSaving(true);
    setMessage("");
    setError("");

    // Filter out empty stories
    const validStories = stories.filter((s) => s.title && s.photo_url);

    try {
      const res = await fetch("/api/stories", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ stories: validStories }),
      });

      if (!res.ok) {
        const data = await res.json();
        setError(data.error || "Failed to save");
        return;
      }

      setStories(validStories);
      setMessage("Stories saved successfully!");
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="max-w-3xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <svg className="w-6 h-6 text-pink-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
          </svg>
          <div>
            <h1 className="text-2xl font-bold">A Day in My Life</h1>
            <p className="text-text-muted text-sm">Create story slides that visitors see on your profile</p>
          </div>
        </div>
        <button
          onClick={handleSave}
          disabled={saving}
          className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50"
        >
          {saving ? "Saving..." : "Save Stories"}
        </button>
      </div>

      {message && (
        <div className="bg-green-500/10 border border-green-500/20 text-green-400 px-4 py-3 rounded-lg mb-4 text-sm">
          {message}
        </div>
      )}
      {error && (
        <div className="bg-red-500/10 border border-red-500/20 text-red-400 px-4 py-3 rounded-lg mb-4 text-sm">
          {error}
        </div>
      )}

      {loading ? (
        <div className="space-y-4">
          {[1, 2].map((i) => (
            <div key={i} className="h-48 bg-surface rounded-lg animate-pulse" />
          ))}
        </div>
      ) : (
        <div className="space-y-4">
          {stories.map((story, idx) => (
            <div key={idx} className="bg-surface rounded-lg p-5 border border-white/5">
              <div className="flex items-center justify-between mb-4">
                <span className="text-sm font-medium text-text-muted">Slide {idx + 1}</span>
                <div className="flex items-center gap-1">
                  <button
                    onClick={() => moveStory(idx, -1)}
                    disabled={idx === 0}
                    className="p-1.5 text-text-muted hover:text-white disabled:opacity-30 transition-colors"
                    title="Move up"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
                    </svg>
                  </button>
                  <button
                    onClick={() => moveStory(idx, 1)}
                    disabled={idx === stories.length - 1}
                    className="p-1.5 text-text-muted hover:text-white disabled:opacity-30 transition-colors"
                    title="Move down"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </button>
                  <button
                    onClick={() => removeStory(idx)}
                    className="p-1.5 text-text-muted hover:text-red-400 transition-colors"
                    title="Remove slide"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-3">
                  <div>
                    <label className="block text-sm font-medium text-text mb-1">Title</label>
                    <input
                      type="text"
                      value={story.title}
                      onChange={(e) => updateStory(idx, "title", e.target.value)}
                      placeholder="Morning Routine"
                      maxLength={100}
                      className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-text mb-1">Photo URL</label>
                    <input
                      type="url"
                      value={story.photo_url}
                      onChange={(e) => updateStory(idx, "photo_url", e.target.value)}
                      placeholder="https://example.com/photo.jpg"
                      maxLength={500}
                      className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-text mb-1">Description</label>
                    <textarea
                      value={story.description}
                      onChange={(e) => updateStory(idx, "description", e.target.value)}
                      placeholder="Tell your story..."
                      maxLength={500}
                      rows={3}
                      className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary text-sm"
                    />
                  </div>
                </div>

                {/* Preview */}
                <div className="flex items-center justify-center">
                  {story.photo_url ? (
                    <div className="relative w-full aspect-square rounded-lg overflow-hidden bg-surface-light">
                      <img
                        src={story.photo_url}
                        alt={story.title || "Preview"}
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          (e.target as HTMLImageElement).style.display = "none";
                        }}
                      />
                      {story.title && (
                        <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-3">
                          <p className="text-white text-sm font-semibold">{story.title}</p>
                        </div>
                      )}
                    </div>
                  ) : (
                    <div className="w-full aspect-square rounded-lg bg-surface-light flex items-center justify-center">
                      <p className="text-text-muted text-sm">Add a photo URL to preview</p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}

          {/* Add Story Button */}
          <button
            onClick={addStory}
            disabled={stories.length >= 20}
            className="w-full py-4 border-2 border-dashed border-surface-light hover:border-primary/50 rounded-lg text-text-muted hover:text-primary transition-colors disabled:opacity-30"
          >
            <div className="flex items-center justify-center gap-2">
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
              </svg>
              Add Story Slide ({stories.length}/20)
            </div>
          </button>
        </div>
      )}
    </div>
  );
}
