"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { useTranslation } from "@/hooks/useTranslation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchProfile } from "@/store/slices/profileSlice";
import { isAuthenticatedClient } from "@/lib/utils/persistAuth";
import SettingsModal from "./SettingsModal";

interface ProfileHeaderProps {
  locale: string;
}

function getInitials(fullName: string): string {
  const parts = fullName.trim().split(" ").filter(Boolean);
  if (parts.length === 0) return "?";
  if (parts.length === 1) return parts[0][0].toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

function formatMonthYear(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString("en-US", { month: "short", year: "numeric" });
}

export function ProfileHeader({ locale: _locale }: ProfileHeaderProps) {
  const [settingsOpen, setSettingsOpen] = useState(false);
  const { t } = useTranslation("profile");
  const dispatch = useAppDispatch();
  const { user, isLoading } = useAppSelector((s) => s.profile);

  useEffect(() => {
    if (isAuthenticatedClient()) {
      dispatch(fetchProfile());
    }
  }, [dispatch]);

  const initials = user ? getInitials(user.full_name) : "?";
  const joinDate = user ? formatMonthYear(user.created_at) : "";
  const lastActive = user ? formatMonthYear(user.updated_at) : "";
  const location = user?.country_name || "";

  return (
    <>
      <header className="pf-header">
        <div className="wrap pf-header-row">
          <div
            className="pf-av"
            style={{ position: "relative", overflow: "visible" }}
          >
            {user?.image ? (
              <div
                style={{
                  position: "absolute",
                  inset: 0,
                  borderRadius: "50%",
                  overflow: "hidden",
                }}
              >
                <Image
                  src={user.image}
                  alt={user.full_name}
                  fill
                  sizes="80px"
                  style={{ objectFit: "cover" }}
                  unoptimized
                />
              </div>
            ) : isLoading ? (
              "…"
            ) : (
              initials
            )}
            <span className="verified" title={t("verified_title")}>
              <svg viewBox="0 0 24 24">
                <path d="M5 12l5 5L20 7" />
              </svg>
            </span>
          </div>

          <div className="pf-info">
            <h1 className="pf-name">
              {isLoading ? "Loading…" : (user?.full_name ?? "—")}{" "}
              <span className="badge">{t("dtnews_plus_badge")}</span>
            </h1>
            <div className="pf-handle">
              {user?.user_name ?? ""}
              {user?.user_name ? " · " : ""}joined {joinDate}
            </div>
            <p className="pf-bio">{user?.bio || "No bio yet."}</p>
            <div className="pf-meta">
              {location && (
                <span className="item">
                  <svg viewBox="0 0 24 24">
                    <path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0 1 18 0z" />
                    <circle cx="12" cy="10" r="3" />
                  </svg>
                  <b>{location}</b>
                </span>
              )}
              <span className="item">
                <svg viewBox="0 0 24 24">
                  <rect x="3" y="6" width="18" height="14" rx="2" />
                  <path d="M16 2v4M8 2v4M3 10h18" />
                </svg>
                Member since <b>{joinDate}</b>
              </span>
              <span className="item">
                <svg viewBox="0 0 24 24">
                  <circle cx="12" cy="12" r="9" />
                  <path d="M12 7v5l3 2" />
                </svg>
                Last active <b>{lastActive}</b>
              </span>
            </div>
          </div>

          <div className="pf-actions">
            {/* Edit Profile */}
            <a
              href="/profile/edit"
              className="btn secondary"
              style={{ textDecoration: "none" }}
            >
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
              >
                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
              </svg>
              Edit Profile
            </a>
            <button
              className="btn primary"
              type="button"
              onClick={() => setSettingsOpen(true)}
            >
              <svg viewBox="0 0 24 24">
                <circle cx="12" cy="12" r="3" />
                <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
              </svg>
              {t("settings")}
            </button>
          </div>
        </div>

        <div className="wrap">
          <div className="pf-stats">
            <div className="pf-stat">
              <span className="n">{user?.total_feed ?? 0}</span>
              <span className="l">{t("stats.articles_read")}</span>
            </div>
            <div className="pf-stat">
              <span className="n">0</span>
              <span className="l">{t("stats.saved")}</span>
            </div>
            <div className="pf-stat">
              <span className="n">0</span>
              <span className="l">{t("stats.topics_followed")}</span>
            </div>
            <div className="pf-stat">
              <span className="n">0</span>
              <span className="l">{t("stats.journalists_followed")}</span>
            </div>
            <div className="pf-stat">
              <span className="n">—</span>
              <span className="l">{t("stats.read_streak")}</span>
            </div>
          </div>
        </div>
      </header>

      <SettingsModal
        open={settingsOpen}
        onClose={() => setSettingsOpen(false)}
      />
    </>
  );
}
