"use client";

import { useEffect, useState } from "react";
import { HelpCircle } from "lucide-react";
import type { Profile } from "@/lib/constants";
import {
  acceptTerms,
  deleteMyComment,
  dismissOnboarding,
  getReferralState,
  listMyComments,
  pinMyComment,
} from "@/app/dashboard/settings-actions";
import { useToast } from "@/components/Toast";

export function HelpTip({ text }: { text: string }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center" }}>
      <button
        type="button"
        aria-label={text}
        title={text}
        onClick={(event) => {
          event.preventDefault();
          const el = event.currentTarget;
          el.setAttribute("aria-label", el.getAttribute("aria-label") === text ? `${text} (close)` : text);
        }}
        style={{ background: "none", border: 0, padding: 2, color: "#6e2121", cursor: "help" }}
      >
        <HelpCircle size={14} />
      </button>
    </span>
  );
}

export function TosCard({ p }: { p: Profile }) {
  const toast = useToast();
  const [accepted, setAccepted] = useState(!!p.tos_accepted_at);
  const [busy, setBusy] = useState(false);

  async function accept() {
    setBusy(true);
    const res = await acceptTerms();
    setBusy(false);
    if (res.error) return toast.show(res.error, "error");
    setAccepted(true);
    toast.show("Terms accepted", "success");
  }

  return (
    <section className="card2">
      <div className="cardHead2">
        <h2>Terms of Service <HelpTip text="You must read and accept the rules before your profile is fully set up." /></h2>
        <p>Accepting confirms you agree to the site rules.</p>
      </div>
      {accepted ? (
        <p className="helpText2" role="status">✅ Accepted. Thanks for reading the rules.</p>
      ) : (
        <div style={{ display: "grid", gap: 10 }}>
          <p className="helpText2" style={{ color: "#f1adad" }}>You have not accepted the Terms yet. Read <a href="/terms" target="_blank" rel="noreferrer">the rules</a>, then accept.</p>
          <button type="button" className="primaryBtn soft" onClick={() => void accept()} disabled={busy}>
            {busy ? "Saving…" : "I have read and accept the Terms"}
          </button>
        </div>
      )}
    </section>
  );
}

export function CommentsManager({ p, update }: { p: Profile; update: (patch: Partial<Profile>) => void }) {
  const toast = useToast();
  const [comments, setComments] = useState<{ id: string; author_username: string; content: string; created_at: string }[]>([]);
  const [pinnedId, setPinnedId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  async function load() {
    setLoading(true);
    const res = await listMyComments();
    if (!("error" in res && res.error)) {
      setComments((res as { comments: never[] }).comments || []);
      setPinnedId((res as { pinnedId: string | null }).pinnedId || null);
    }
    setLoading(false);
  }

  useEffect(() => {
    void load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function remove(id: string) {
    const res = await deleteMyComment(id);
    if (res.error) return toast.show(res.error, "error");
    setComments((current) => current.filter((c) => c.id !== id));
    if (pinnedId === id) setPinnedId(null);
    toast.show("Comment deleted", "success");
  }

  async function pin(id: string | null) {
    const res = await pinMyComment(id);
    if (res.error) return toast.show(res.error, "error");
    setPinnedId(id);
    toast.show(id ? "Comment pinned" : "Comment unpinned", "success");
  }

  return (
    <section className="card2">
      <div className="cardHead2">
        <h2>Comments <HelpTip text="Comments appear on your public profile. You can delete or pin any of them here." /></h2>
        <p>Manage comments on your profile.</p>
      </div>
      <label className="toggle2" style={{ marginBottom: 14 }}>
        <span>Allow comments on my profile</span>
        <input type="checkbox" checked={p.comments_enabled !== false} onChange={(e) => update({ comments_enabled: e.target.checked })} />
        <i />
      </label>
      {loading ? (
        <p className="helpText2">Loading comments…</p>
      ) : comments.length === 0 ? (
        <p className="helpText2">No comments yet. Share your profile link to get the first one.</p>
      ) : (
        <ul style={{ display: "grid", gap: 8, listStyle: "none", margin: 0, padding: 0 }}>
          {comments.map((comment) => (
            <li key={comment.id} style={{ border: "1px solid #4d3535", borderRadius: 10, padding: "10px 12px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                <strong style={{ fontSize: 13 }}>@{comment.author_username}</strong>
                <small style={{ color: "#661a1a" }}>{new Date(comment.created_at).toLocaleDateString()}</small>
              </div>
              <p style={{ margin: "6px 0 10px", fontSize: 13, lineHeight: 1.5, wordBreak: "break-word" }}>{comment.content}</p>
              <div style={{ display: "flex", gap: 8 }}>
                <button type="button" className="ghostBtn" onClick={() => void pin(pinnedId === comment.id ? null : comment.id)}>
                  {pinnedId === comment.id ? "Unpin" : "Pin"}
                </button>
                <button type="button" className="ghostBtn" onClick={() => void remove(comment.id)}>Delete</button>
              </div>
            </li>
          ))}
        </ul>
      )}
    </section>
  );
}

export function AboutMeCard({ p, update }: { p: Profile; update: (patch: Partial<Profile>) => void }) {
  return (
    <section className="card2">
      <div className="cardHead2">
        <h2>Scroll / About me <HelpTip text="When enabled, visitors can scroll below your card to read a longer About Me section." /></h2>
        <p>Let visitors scroll past your main card to a longer intro.</p>
      </div>
      <label className="toggle2" style={{ marginBottom: 12 }}>
        <span>Enable long-form profile scroll</span>
        <input type="checkbox" checked={!!p.scroll_enabled} onChange={(e) => update({ scroll_enabled: e.target.checked })} />
        <i />
      </label>
      <label>
        About Me
        <textarea
          value={p.about_me || ""}
          onChange={(e) => update({ about_me: e.target.value.slice(0, 5000) })}
          rows={6}
          maxLength={5000}
          placeholder="Tell visitors more about yourself…"
          style={{ width: "100%" }}
        />
      </label>
      <p className="helpText2">Shown below your profile card when the toggle is on.</p>
    </section>
  );
}

export function EmbedPresetCard({ p, update }: { p: Profile; update: (patch: Partial<Profile>) => void }) {
  const presets = [
    { id: "classic", name: "Classic", desc: "Avatar, title, and bio." },
    { id: "minimal", name: "Minimal", desc: "Light, avatar-first layout." },
    { id: "banner", name: "Banner", desc: "Full-width image with title overlay." },
  ];
  return (
    <section className="card2">
      <div className="cardHead2">
        <h2>Embed preset <HelpTip text="Choose how your card looks when your profile URL is shared on Discord, X, and elsewhere." /></h2>
        <p>Pick the style used for your share embed.</p>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 10 }}>
        {presets.map((preset) => (
          <button
            key={preset.id}
            type="button"
            onClick={() => update({ embed_preset: preset.id })}
            style={{
              textAlign: "left",
              padding: 12,
              borderRadius: 12,
              border: `1px solid ${p.embed_preset === preset.id || (!p.embed_preset && preset.id === "classic") ? "#d87878" : "#4a3131"}`,
              background: p.embed_preset === preset.id || (!p.embed_preset && preset.id === "classic") ? "rgba(216, 120, 120, .08)" : "#0a0f1d",
              color: "#000",
              cursor: "pointer",
            }}
          >
            <strong style={{ display: "block", fontSize: 14 }}>{preset.name}</strong>
            <small style={{ color: "#571313" }}>{preset.desc}</small>
          </button>
        ))}
      </div>
    </section>
  );
}

export function ReferralCard() {
  const toast = useToast();
  const [state, setState] = useState<null | {
    code: string | null;
    validReferrals: number;
    progress: number;
    target: number;
    rewards: { days: number; granted_at: string; expires_at: string | null }[];
    premiumUntil: string | null;
  }>(null);

  useEffect(() => {
    getReferralState().then((res) => {
      if (!("error" in res && res.error)) setState(res as never);
    });
  }, []);

  if (!state) return null;

  return (
    <section className="card2">
      <div className="cardHead2">
        <h2>Referrals <HelpTip text="Share your code. Every 5 valid referrals earns 7 days of Premium." /></h2>
        <p>Invite friends and earn Premium.</p>
      </div>
      <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
        <code style={{ fontSize: 18, letterSpacing: 2, padding: "8px 12px", background: "#0e1526", borderRadius: 8 }}>{state.code || "—"}</code>
        <button type="button" className="ghostBtn" onClick={() => {
          if (state.code) {
            navigator.clipboard.writeText(state.code).then(() => toast.show("Referral code copied", "success")).catch(() => toast.show("Could not copy", "error"));
          }
        }}>
          Copy code
        </button>
      </div>
      <p className="helpText2" style={{ marginTop: 12 }}>
        {state.validReferrals} valid referral{state.validReferrals === 1 ? "" : "s"} · {state.progress}/{state.target} toward your next reward.
      </p>
      {state.rewards.length === 0 ? (
        <p className="helpText2">No rewards yet — keep inviting!</p>
      ) : (
        <ul style={{ margin: "8px 0 0", paddingLeft: 18, color: "#340606", fontSize: 13 }}>
          {state.rewards.map((reward) => (
            <li key={reward.granted_at}>+{reward.days} days Premium (expires {reward.expires_at ? new Date(reward.expires_at).toLocaleDateString() : "—"})</li>
          ))}
        </ul>
      )}
      {state.premiumUntil && <p className="helpText2" style={{ marginTop: 8 }}>Premium active until {new Date(state.premiumUntil).toLocaleString()}.</p>}
    </section>
  );
}

const TIPS = [
  "Add a profile picture.",
  "Add more links.",
  "Write an About Me.",
  "Customize your profile appearance.",
  "Add a social link.",
  "Enable comments.",
  "Add a custom badge.",
  "Complete your profile information.",
];

export function TipsCard() {
  const [tip, setTip] = useState("");
  useEffect(() => {
    setTip(TIPS[Math.floor(Math.random() * TIPS.length)]);
  }, []);
  return (
    <section className="card2">
      <div className="cardHead2"><h2>Tips for your profile</h2></div>
      <p className="helpText2" style={{ margin: 0 }}>{tip}</p>
    </section>
  );
}

export function OnboardingDismissCard() {
  const [hidden, setHidden] = useState(false);
  if (hidden) return null;
  return (
    <button
      type="button"
      className="ghostBtn"
      onClick={async () => {
        await dismissOnboarding();
        setHidden(true);
      }}
      style={{ alignSelf: "start" }}
    >
      Hide checklist
    </button>
  );
}
