"use client";
import { useState, useEffect } from "react";
import { FormButton } from "@/app/components/form/forms";
import type { StepComponentProps } from "./../wizardTypes";

interface InputField {
  id: number;
  value: string;
}

const limit = 5;
const STORAGE_KEY = "more_inspiration_links";

export default function MoreInspiration({ jumpToNext }: StepComponentProps) {
  // 👇 Use local storage value at initialization
  const [inputs, setInputs] = useState<InputField[]>(() => {
    if (typeof window !== "undefined") {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) {
        try {
          const parsed: InputField[] = JSON.parse(saved);
          if (parsed && parsed.length > 0) return parsed;
        } catch (e) {
          console.error("Failed to parse local storage data", e);
        }
      }
    }
    return [{ id: 1, value: "" }];
  });

  // Save to local storage when inputs change
  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(inputs));
  }, [inputs]);

  const addInput = () => {
    if (inputs.length < limit) {
      const newInput: InputField = { id: Date.now(), value: "" };
      setInputs((prev) => [...prev, newInput]);
    }
  };

  const removeInput = (id: number) => {
    if (id === 1) return; // Prevent removing first input
    setInputs((prev) => prev.filter((input) => input.id !== id));
  };

  const handleChange = (id: number, value: string) => {
    setInputs((prev) =>
      prev.map((input) => (input.id === id ? { ...input, value } : input))
    );
  };

  const ReferenceSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    jumpToNext();
  };

  return (
    <>
      <div className="mx-auto flex w-full flex-col items-center justify-center gap-10">
        <div className="mx-auto flex w-full flex-col items-center justify-center gap-2 text-center md:w-[50%]">
          <h2 className="vision">
            Have <span className="font-medium">more inspiration</span> to share?
          </h2>
          <p className="text-xs/4 md:text-sm font-light">
            Upload any reference images and/or links (e.g., Pinterest board) that might help us understand your style or vision better.
          </p>
        </div>

        <div className="cc-vision-wrap">
          <div className="ccvision-scrollcontent">
            <div className="mx-auto mt-10 flex w-full flex-col md:w-[50%]">
              <div className="flex w-full flex-col gap-4 text-sm">
                {inputs.map((input, index) => (
                  <div key={input.id} className="flex items-center gap-4">
                    <input
                      type="text"
                      value={input.value}
                      onChange={(e) => handleChange(input.id, e.target.value)}
                      placeholder={`Add reference link ${index + 1}`}
                      className="w-full border-b border-y-gray-950/50 py-2"
                    />
                    {index !== 0 && (
                      <button
                        type="button"
                        onClick={() => removeInput(input.id)}
                        className="btn-link"
                      >
                        Remove
                      </button>
                    )}
                  </div>
                ))}

                <div className="flex w-full flex-col items-start justify-start">
                  {inputs.length >= limit ? (
                    <p className="text-red-700">You have reached max {limit} limit.</p>
                  ) : (
                    <button type="button" onClick={addInput} className="btn-link">
                      Add more links
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>

          <div className="ccBottomBtnWrap">
            <FormButton
              id="btn_cc_save_reference_link"
              label="Save Links"
              type="submit"
              color="gray"
              hairline="blue"
              onClick={ReferenceSubmit}
            />
          </div>
        </div>
      </div>
    </>
  );
}
