"use client";
import useSWR from "swr";
import { useRef, useState } from "react";
import { Modal } from "@/app/components/ui/Modal";

const fetcher = (url: string) => fetch(url).then((r) => r.json());

export default function AdminBannersPage() {
  const { data, mutate } = useSWR<{ banners: any[] }>("/api/admin/banners", fetcher);
  const banners = data?.banners ?? [];
  const [form, setForm] = useState({ title: "", imageUrl: "", linkUrl: "", active: true, sortOrder: 0 });
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  async function onSelectFile(e: React.ChangeEvent<HTMLInputElement>) {
    const inputEl = e.currentTarget; // 이벤트 풀링 대비 사본 보관
    const file = inputEl.files?.[0];
    if (!file) return;
    try {
      setUploading(true);
      const fd = new FormData();
      fd.append("file", file);
      const r = await fetch("/api/uploads", { method: "POST", body: fd });
      const json = await r.json();
      if (!r.ok) throw new Error(json?.error || "upload_failed");
      setForm((f) => ({ ...f, imageUrl: json.url }));
    } catch (err) {
      console.error(err);
      alert("이미지 업로드 중 오류가 발생했습니다.");
    } finally {
      setUploading(false);
      if (inputEl) inputEl.value = "";
    }
  }
  async function create() {
    const r = await fetch("/api/admin/banners", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(form) });
    if (r.ok) { setForm({ title: "", imageUrl: "", linkUrl: "", active: true, sortOrder: 0 }); mutate(); setShowCreateModal(false); }
  }
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <h1>배너 관리</h1>
        <button
          type="button"
          onClick={() => setShowCreateModal(true)}
          className="h-9 px-4 rounded-md bg-neutral-900 text-white text-sm shadow cursor-pointer hover:bg-neutral-800 active:translate-y-px transition"
        >
          추가
        </button>
      </div>
      <Modal open={showCreateModal} onClose={() => setShowCreateModal(false)}>
        <div className="w-[720px] max-w-[90vw]">
          <div className="p-6">
            <h2 className="text-lg font-bold mb-4">배너 추가</h2>
            {(() => {
              const inputStyle: React.CSSProperties = { border: "1px solid #ddd", borderRadius: 6, padding: "8px 10px", width: "100%" };
              return (
                <div style={{ display: "grid", gridTemplateColumns: "repeat(6, minmax(0, 1fr))", gap: 12, alignItems: "end" }}>
                  <div style={{ gridColumn: "span 3" }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 6 }}>제목</label>
                    <input style={inputStyle} value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
                  </div>
                  <div style={{ gridColumn: "span 3" }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 6 }}>링크 URL(선택)</label>
                    <input style={inputStyle} value={form.linkUrl} onChange={(e) => setForm({ ...form, linkUrl: e.target.value })} />
                  </div>
                  <div style={{ gridColumn: "span 6" }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 6 }}>이미지 URL</label>
                    <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                      <input style={inputStyle} value={form.imageUrl} onChange={(e) => setForm({ ...form, imageUrl: e.target.value })} />
                      <button
                        type="button"
                        onClick={() => fileInputRef.current?.click()}
                        disabled={uploading}
                        className="h-9 px-4 w-36 rounded-md border border-neutral-300 text-sm cursor-pointer hover:bg-neutral-100 hover:border-neutral-400 active:translate-y-px transition"
                      >
                        업로드
                      </button>
                      <input ref={fileInputRef} type="file" accept="image/*" onChange={onSelectFile} style={{ display: "none" }} />
                      {uploading && <span style={{ fontSize: 12, opacity: .7 }}>업로드 중...</span>}
                    </div>
                  </div>
                  <div style={{ gridColumn: "span 3" }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 6 }}>활성</label>
                    <label className="inline-flex items-center gap-2 text-sm"><input type="checkbox" checked={form.active} onChange={(e) => setForm({ ...form, active: e.target.checked })} /> 활성화</label>
                  </div>
                  <div style={{ gridColumn: "span 3" }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 6 }}>정렬</label>
                    <input type="number" style={inputStyle} value={form.sortOrder} onChange={(e) => setForm({ ...form, sortOrder: Number(e.target.value) })} />
                  </div>
                  {form.imageUrl && (
                    <div style={{ gridColumn: "span 6" }}>
                      <div style={{ fontSize: 12, opacity: .7, marginBottom: 6 }}>미리보기</div>
                      <img src={form.imageUrl} alt="미리보기" style={{ width: 320, height: 160, objectFit: "cover", borderRadius: 6, border: "1px solid #eee" }} />
                    </div>
                  )}
                  <div style={{ gridColumn: "span 6", display: "flex", justifyContent: "flex-end", gap: 8 }}>
                    <button
                      onClick={create}
                      className="h-9 px-4 rounded-md bg-neutral-900 text-white text-sm shadow cursor-pointer hover:bg-neutral-800 active:translate-y-px transition"
                    >
                      저장
                    </button>
                    <button
                      type="button"
                      onClick={() => setShowCreateModal(false)}
                      className="h-9 px-4 rounded-md border border-neutral-300 text-sm cursor-pointer hover:bg-neutral-100 active:translate-y-px transition"
                    >
                      취소
                    </button>
                  </div>
                </div>
              );
            })()}
          </div>
        </div>
      </Modal>
      <ul style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {banners.map((b) => (
          <li key={b.id} style={{ border: "1px solid #eee", borderRadius: 8, padding: 12, display: "flex", gap: 12, alignItems: "center" }}>
            <img src={b.imageUrl} alt={b.title} style={{ width: 80, height: 48, objectFit: "cover", borderRadius: 6 }} />
            <div style={{ flex: 1 }}>
              <div><strong>{b.title}</strong> {b.linkUrl && <a style={{ marginLeft: 8 }} href={b.linkUrl}>링크</a>}</div>
              <div style={{ fontSize: 12, opacity: 0.7 }}>정렬 {b.sortOrder} · {b.active ? "활성" : "비활성"}</div>
            </div>
            <button onClick={async () => { await fetch(`/api/admin/banners/${b.id}`, { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ active: !b.active }) }); mutate(); }} className="h-8 px-3 rounded-md border border-neutral-300 text-sm cursor-pointer hover:bg-neutral-100 active:translate-y-px transition">{b.active ? "비활성" : "활성"}</button>
            <button onClick={async () => { await fetch(`/api/admin/banners/${b.id}`, { method: "DELETE" }); mutate(); }} className="h-8 px-3 rounded-md border border-red-200 text-red-600 text-sm cursor-pointer hover:bg-red-100 hover:border-red-300 hover:text-red-700 active:translate-y-px transition">삭제</button>
          </li>
        ))}
      </ul>
    </div>
  );
}


