"use client";

import { useState, useEffect, useRef } from "react";
import { api } from "@/services/api";

const DRAFT_KEY = "tinix_create_draft";

const DEFAULT_FORM = {
  title: "",
  genre: "",
  sub_genres: [] as string[],
  style: "",
  character_setting: "",
  world_setting: "",
  plot_idea: "",
  custom_outline_prompt: "",
  total_chapters: 20
};

function loadDraft(): { form: typeof DEFAULT_FORM; outline: string } {
  try {
    const raw = localStorage.getItem(DRAFT_KEY);
    if (raw) {
      const parsed = JSON.parse(raw);
      return {
        form: { ...DEFAULT_FORM, ...(parsed.form || {}) },
        outline: parsed.outline || ""
      };
    }
  } catch {
    // ignore corrupted draft
  }
  return { form: { ...DEFAULT_FORM }, outline: "" };
}

export default function CreatePage() {
  const initial = useRef(loadDraft()).current;

  const [genres, setGenres] = useState<string[]>([]);
  const [subGenres, setSubGenres] = useState<string[]>([]);
  const [styles, setStyles] = useState<string[]>([]);

  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState(initial.form);
  const [outline, setOutline] = useState<string>(initial.outline);
  const [statusMsg, setStatusMsg] = useState<string>("");

  // Per-field AI suggestion UI state
  const [suggestPrompt, setSuggestPrompt] = useState({
    title: "",
    char: "",
    world: "",
    plot: ""
  });
  const [suggesting, setSuggesting] = useState<{ [k: string]: boolean }>({});

  // Persist to localStorage on every change (fixes reload content loss)
  useEffect(() => {
    localStorage.setItem(DRAFT_KEY, JSON.stringify({ form: formData, outline }));
  }, [formData, outline]);

  // Fetch genres / styles on mount (do NOT overwrite persisted selections)
  useEffect(() => {
    api.getGenres().then((data) => {
      const names = (data || []).map((g: any) => g.name ?? g);
      setGenres(names);
      if (!formData.genre && names.length > 0) {
        setFormData((prev) => ({ ...prev, genre: names[0] }));
      }
    }).catch((err) => console.error("Error fetching genres:", err));

    api.getStyles().then((data) => {
      const names = (data || []).map((s: any) => s.name ?? s);
      setStyles(names);
      if (!formData.style && names.length > 0) {
        setFormData((prev) => ({ ...prev, style: names[0] }));
      }
    }).catch((err) => console.error("Error fetching styles:", err));
  }, []);

  // Load sub-genres when genre changes
  useEffect(() => {
    if (!formData.genre) return;
    api.getSubGenres(formData.genre).then((data) => {
      const names = (data || []).map((s: any) => s.name ?? s);
      setSubGenres(names);
      setFormData((prev) => ({
        ...prev,
        sub_genres: prev.sub_genres.filter((sg) => names.includes(sg))
      }));
    }).catch(() => setSubGenres([]));
  }, [formData.genre]);

  const toggleSubGenre = (sg: string) => {
    setFormData((prev) => {
      const has = prev.sub_genres.includes(sg);
      return {
        ...prev,
        sub_genres: has
          ? prev.sub_genres.filter((x) => x !== sg)
          : [...prev.sub_genres, sg]
      };
    });
  };

  const handleSuggest = async (
    type: 'title' | 'char' | 'world' | 'plot'
  ) => {
    setSuggesting((s) => ({ ...s, [type]: true }));
    setStatusMsg("");
    try {
      const res = await api.suggest({
        type,
        genre: formData.genre,
        sub_genres: formData.sub_genres,
        title: formData.title,
        character_setting: formData.character_setting,
        world_setting: formData.world_setting,
        custom_prompt: suggestPrompt[type],
        num_main_chars: 2,
        num_sub_chars: 3
      });

      const content = res.content || "";
      if (type === 'title') {
        // suggestion returns a list of titles -> pick the first
        const first = content.split("\n").map((s: string) => s.trim()).filter(Boolean)[0] || content;
        setFormData((prev) => ({ ...prev, title: first }));
      } else if (type === 'char') {
        setFormData((prev) => ({ ...prev, character_setting: content }));
      } else if (type === 'world') {
        setFormData((prev) => ({ ...prev, world_setting: content }));
      } else if (type === 'plot') {
        setFormData((prev) => ({ ...prev, plot_idea: content }));
      }
      setStatusMsg(res.message || "Gợi ý đã được điền.");
    } catch (err: any) {
      setStatusMsg("Lỗi gợi ý: " + err.message);
    } finally {
      setSuggesting((s) => ({ ...s, [type]: false }));
    }
  };

  const handleGenerateOutline = async () => {
    try {
      setLoading(true);
      setStatusMsg("Generating outline. Please wait...");
      setOutline("");

      const res = await api.generateOutline({
        title: formData.title,
        genre: formData.genre,
        sub_genres: formData.sub_genres,
        total_chapters: formData.total_chapters,
        character_setting: formData.character_setting,
        world_setting: formData.world_setting,
        plot_idea: formData.plot_idea,
        custom_outline_prompt: formData.custom_outline_prompt
      });

      setOutline(res.content || "");
      setStatusMsg(res.message || "Success");
    } catch (err: any) {
      setStatusMsg("Error: " + err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleClearDraft = () => {
    localStorage.removeItem(DRAFT_KEY);
    setFormData({ ...DEFAULT_FORM, genre: formData.genre, style: formData.style });
    setOutline("");
    setSuggestPrompt({ title: "", char: "", world: "", plot: "" });
    setStatusMsg("");
  };

  return (
    <div className="flex flex-col flex-1 p-8">
      <div className="mb-8 flex items-start justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Create Story</h1>
          <p className="text-zinc-500 mt-2">Design your novel settings and generate an outline.</p>
        </div>
        <button
          onClick={handleClearDraft}
          className="text-xs px-3 py-2 rounded-md border border-border-glass text-zinc-400 hover:text-white hover:border-brand-primary transition-colors"
        >
          Clear draft
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* Form Column */}
        <div className="space-y-6">
          <div className="space-y-2">
            <label className="text-sm font-medium text-zinc-300">Genre</label>
            <select
              className="w-full bg-background-card border border-border-glass rounded-md p-2 text-sm focus:border-brand-primary outline-none text-white"
              value={formData.genre}
              onChange={(e) => setFormData({ ...formData, genre: e.target.value })}
            >
              {genres.length === 0 && <option value="">-- no genres --</option>}
              {genres.map((g) => (
                <option key={g} value={g}>{g}</option>
              ))}
            </select>
          </div>

          {subGenres.length > 0 && (
            <div className="space-y-2">
              <label className="text-sm font-medium text-zinc-300">Sub-genres</label>
              <div className="flex flex-wrap gap-2">
                {subGenres.map((sg) => {
                  const active = formData.sub_genres.includes(sg);
                  return (
                    <button
                      key={sg}
                      onClick={() => toggleSubGenre(sg)}
                      className={`px-3 py-1 rounded-full text-xs border transition-colors ${
                        active
                          ? "bg-brand-primary text-black border-brand-primary"
                          : "border-border-glass text-zinc-400 hover:text-white"
                      }`}
                    >
                      {sg}
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          <div className="space-y-2">
            <label className="text-sm font-medium text-zinc-300">Writing Style</label>
            <select
              className="w-full bg-background-card border border-border-glass rounded-md p-2 text-sm focus:border-brand-primary outline-none text-white"
              value={formData.style}
              onChange={(e) => setFormData({ ...formData, style: e.target.value })}
            >
              {styles.length === 0 && <option value="">-- no styles --</option>}
              {styles.map((s) => (
                <option key={s} value={s}>{s}</option>
              ))}
            </select>
          </div>

          <AiField
            label="Novel Title"
            placeholder="Enter your novel title..."
            value={formData.title}
            onChange={(v) => setFormData({ ...formData, title: v })}
            promptValue={suggestPrompt.title}
            onPromptChange={(v) => setSuggestPrompt((p) => ({ ...p, title: v }))}
            onSuggest={() => handleSuggest("title")}
            suggesting={suggesting.title}
            promptPlaceholder="Optional prompt for AI title suggestion..."
          />

          <AiField
            label="Character Settings"
            placeholder="Describe main characters, personalities..."
            value={formData.character_setting}
            onChange={(v) => setFormData({ ...formData, character_setting: v })}
            promptValue={suggestPrompt.char}
            onPromptChange={(v) => setSuggestPrompt((p) => ({ ...p, char: v }))}
            onSuggest={() => handleSuggest("char")}
            suggesting={suggesting.char}
            promptPlaceholder="Optional prompt for AI character suggestion..."
            textarea
          />

          <AiField
            label="World Setting"
            placeholder="Describe the world, magic system, laws..."
            value={formData.world_setting}
            onChange={(v) => setFormData({ ...formData, world_setting: v })}
            promptValue={suggestPrompt.world}
            onPromptChange={(v) => setSuggestPrompt((p) => ({ ...p, world: v }))}
            onSuggest={() => handleSuggest("world")}
            suggesting={suggesting.world}
            promptPlaceholder="Optional prompt for AI world suggestion..."
            textarea
          />

          <AiField
            label="Plot Idea"
            placeholder="Main conflict, goals, and ending idea..."
            value={formData.plot_idea}
            onChange={(v) => setFormData({ ...formData, plot_idea: v })}
            promptValue={suggestPrompt.plot}
            onPromptChange={(v) => setSuggestPrompt((p) => ({ ...p, plot: v }))}
            onSuggest={() => handleSuggest("plot")}
            suggesting={suggesting.plot}
            promptPlaceholder="Optional prompt for AI plot suggestion..."
            textarea
          />

          <div className="space-y-2">
            <label className="text-sm font-medium text-zinc-300">Custom Outline Prompt (optional)</label>
            <textarea
              className="w-full bg-background-card border border-border-glass rounded-md p-2 text-sm min-h-[80px] focus:border-brand-primary outline-none text-white"
              value={formData.custom_outline_prompt}
              onChange={(e) => setFormData({ ...formData, custom_outline_prompt: e.target.value })}
              placeholder="Extra instructions for the outline..."
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium text-zinc-300">Total Chapters</label>
            <input
              type="number"
              min={1}
              max={200}
              className="w-32 bg-background-card border border-border-glass rounded-md p-2 text-sm focus:border-brand-primary outline-none text-white"
              value={formData.total_chapters}
              onChange={(e) => setFormData({ ...formData, total_chapters: Number(e.target.value) })}
            />
          </div>

          <button
            disabled={loading || !formData.title || !formData.genre}
            onClick={handleGenerateOutline}
            className="w-full py-3 bg-brand-primary text-black font-semibold rounded-md hover:bg-brand-secondary transition-colors disabled:opacity-50"
          >
            {loading ? "Generating..." : "Generate Outline"}
          </button>
        </div>

        {/* Outline / Results Column */}
        <div className="space-y-4">
          <h2 className="text-xl font-semibold text-foreground">Generated Outline</h2>

          {statusMsg && (
            <div className="p-3 bg-blue-900/30 border border-blue-500/30 text-blue-300 rounded-md text-sm">
              {statusMsg}
            </div>
          )}

          <textarea
            className="w-full bg-black/40 border border-border-glass rounded-md p-4 text-sm h-[600px] font-mono text-zinc-300 focus:border-brand-primary outline-none resize-none"
            value={outline}
            readOnly
            placeholder="Your generated outline will appear here..."
          />
        </div>
      </div>
    </div>
  );
}

interface AiFieldProps {
  label: string;
  placeholder: string;
  value: string;
  onChange: (v: string) => void;
  promptValue: string;
  onPromptChange: (v: string) => void;
  onSuggest: () => void;
  suggesting: boolean;
  promptPlaceholder: string;
  textarea?: boolean;
}

function AiField({
  label, placeholder, value, onChange,
  promptValue, onPromptChange, onSuggest, suggesting, promptPlaceholder, textarea
}: AiFieldProps) {
  return (
    <div className="space-y-2">
      <label className="text-sm font-medium text-zinc-300">{label}</label>
      {textarea ? (
        <textarea
          className="w-full bg-background-card border border-border-glass rounded-md p-2 text-sm min-h-[100px] focus:border-brand-primary outline-none text-white"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
        />
      ) : (
        <input
          className="w-full bg-background-card border border-border-glass rounded-md p-2 text-sm focus:border-brand-primary outline-none text-white"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
        />
      )}
      <div className="flex gap-2 items-center">
        <input
          className="flex-1 bg-background-card border border-border-glass rounded-md p-2 text-xs focus:border-brand-primary outline-none text-zinc-300"
          value={promptValue}
          onChange={(e) => onPromptChange(e.target.value)}
          placeholder={promptPlaceholder}
        />
        <button
          onClick={onSuggest}
          disabled={suggesting}
          className="px-3 py-2 text-xs rounded-md bg-brand-primary text-black font-medium hover:bg-brand-secondary transition-colors disabled:opacity-50 whitespace-nowrap"
        >
          {suggesting ? "AI..." : "AI gợi ý"}
        </button>
      </div>
    </div>
  );
}
