"use client";

import React, { useEffect, useState } from "react";
import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import LanguageSettingRow from "@/components/settings/LanguageSettingRow";
import AccountAnalyticsWidget from "@/components/settings/AccountAnalyticsWidget";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import useAxios from "@/hooks/useAxios";
import Link from "next/link";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { useAppLanguage } from "@/contexts/LanguageProvider";
import { isAppLanguage } from "@/lib/i18n/constants";
type PrivacyPatch = {
  allow_save_posts?: boolean;
  ghost_mode?: boolean;
  show_location?: boolean;
  post_location_enabled?: boolean;
  is_private?: boolean;
  preferred_language?: "fa" | "en";
};

type PrivacyResponse = {
  allow_save_posts: boolean;
  ghost_mode: boolean;
  show_location: boolean;
  post_location_enabled: boolean;
  is_private: boolean;
  preferred_language?: "fa" | "en";
};

export default function UserSettingsPage() {
  const { t } = useTranslation("common");
  const { language, setLanguage } = useAppLanguage();
  const { request } = useAxios();
  const [allowSave, setAllowSave] = useState(true);
  const [ghostMode, setGhostMode] = useState(false);
  const [showLocation, setShowLocation] = useState(false);
  const [postLocationEnabled, setPostLocationEnabled] = useState(false);
  const [isPrivate, setIsPrivate] = useState(false);
  const [loading, setLoading] = useState(true);
  const [accountStatus, setAccountStatus] = useState<string>("active");
  const [reactivationLockedUntil, setReactivationLockedUntil] = useState<string | null>(null);
  const [reactivating, setReactivating] = useState(false);

  const applyPrivacyState = (data: Partial<PrivacyResponse>) => {
    if (typeof data.allow_save_posts === "boolean") {
      setAllowSave(data.allow_save_posts);
    }
    if (typeof data.ghost_mode === "boolean") {
      setGhostMode(data.ghost_mode);
    }
    if (typeof data.show_location === "boolean") {
      setShowLocation(data.show_location);
    }
    if (typeof data.post_location_enabled === "boolean") {
      setPostLocationEnabled(data.post_location_enabled);
    }
    if (typeof data.is_private === "boolean") {
      setIsPrivate(data.is_private);
    }
    if (isAppLanguage(data.preferred_language)) {
      void setLanguage(data.preferred_language);
    }
  };

  useEffect(() => {
    (async () => {
      try {
        const res = await request<{
          account: PrivacyResponse & {
            account_status?: string;
            reactivation_locked_until?: string;
          };
        }>("GET", "/account/status", null, { noToast: true });
        applyPrivacyState({
          allow_save_posts: res?.account?.allow_save_posts !== false,
          ghost_mode: Boolean(res?.account?.ghost_mode),
          show_location: res?.account?.show_location === true,
          post_location_enabled: res?.account?.post_location_enabled === true,
          is_private: res?.account?.is_private === true,
          preferred_language: res?.account?.preferred_language,
        });
        setAccountStatus(res?.account?.account_status || "active");
        setReactivationLockedUntil(res?.account?.reactivation_locked_until || null);
      } finally {
        setLoading(false);
      }
    })();
  }, [request]); // eslint-disable-line react-hooks/exhaustive-deps

  const savePrivacy = async (patch: PrivacyPatch) => {
    try {
      const res = await request<PrivacyResponse>(
        "PATCH",
        "/account/privacy",
        patch,
        { noToast: true }
      );
      applyPrivacyState(res);
      toast.success(t("common.save"));
    } catch {
      toast.error(t("common.saveError"));
    }
  };

  const reactivate = async () => {
    setReactivating(true);
    try {
      await request("POST", "/account/reactivate", {});
      setAccountStatus("active");
      toast.success(t("settings.reactivated"));
    } catch (err) {
      toast.error(
        err instanceof Error ? err.message : t("settings.reactivateError")
      );
    } finally {
      setReactivating(false);
    }
  };

  const lockActive =
    accountStatus === "deactivated" &&
    reactivationLockedUntil &&
    new Date(reactivationLockedUntil) > new Date();

  const dateLocale = language === "fa" ? "fa-IR" : "en-US";

  return (
    <LocalePageShell>
      <Container>
      <PageTitle>{t("settings.userSettingsTitle")}</PageTitle>
      <div className="space-y-4 pb-8 text-sm">
        {accountStatus === "deactivated" && (
          <div className="rounded-xl border border-amber-300 bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-950/30">
            <p className="font-semibold text-amber-800 dark:text-amber-200">
              {t("settings.accountDeactivated")}
            </p>
            {lockActive ? (
              <p className="mt-1 text-xs text-amber-700 dark:text-amber-300">
                {t("settings.reactivateLocked", {
                  date: new Date(reactivationLockedUntil!).toLocaleDateString(
                    dateLocale
                  ),
                })}
              </p>
            ) : (
              <button
                type="button"
                disabled={reactivating}
                onClick={reactivate}
                className="mt-3 rounded-lg bg-[#0095f6] px-4 py-2 text-xs font-bold text-white disabled:opacity-50"
              >
                {reactivating ? "…" : t("settings.reactivate")}
              </button>
            )}
          </div>
        )}

        <AccountAnalyticsWidget />

        <LanguageSettingRow />

        <Link
          href="/settings/profile/visitors"
          className="flex items-center justify-between rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800"
        >
          <span className="font-semibold">{t("settings.profileVisitors")}</span>
          <span className="text-neutral-400">›</span>
        </Link>

        <Link
          href="/settings/booking"
          className="flex items-center justify-between rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800"
        >
          <span className="font-semibold">{t("settings.nav.booking")}</span>
          <span className="text-neutral-400">›</span>
        </Link>

        <label className="flex items-center justify-between rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800">
          <div>
            <p className="font-semibold">{t("settings.allowSavePosts")}</p>
            <p className="mt-0.5 text-xs text-neutral-500">
              {t("settings.allowSavePostsDesc")}
            </p>
          </div>
          <input
            type="checkbox"
            checked={allowSave}
            disabled={loading}
            onChange={(e) => savePrivacy({ allow_save_posts: e.target.checked })}
            className="h-5 w-5 accent-[#0095f6]"
          />
        </label>

        <label className="flex items-center justify-between rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800">
          <div>
            <p className="font-semibold">{t("settings.postLocation")}</p>
            <p className="mt-0.5 text-xs text-neutral-500">
              {t("settings.postLocationDesc")}
            </p>
          </div>
          <input
            type="checkbox"
            checked={postLocationEnabled}
            disabled={loading}
            onChange={(e) =>
              savePrivacy({ post_location_enabled: e.target.checked })
            }
            className="h-5 w-5 accent-[#0095f6]"
          />
        </label>

        <label className="flex items-center justify-between rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800">
          <div>
            <p className="font-semibold">{t("settings.showLocation")}</p>
            <p className="mt-0.5 text-xs text-neutral-500">
              {t("settings.showLocationDesc")}
            </p>
          </div>
          <input
            type="checkbox"
            checked={showLocation}
            disabled={loading}
            onChange={(e) => savePrivacy({ show_location: e.target.checked })}
            className="h-5 w-5 accent-[#0095f6]"
          />
        </label>

        <label className="flex items-center justify-between rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800">
          <div>
            <p className="font-semibold">{t("settings.privateProfile")}</p>
            <p className="mt-0.5 text-xs text-neutral-500">
              {t("settings.privateProfileDesc")}
            </p>
          </div>
          <input
            type="checkbox"
            checked={isPrivate}
            disabled={loading}
            onChange={(e) => savePrivacy({ is_private: e.target.checked })}
            className="h-5 w-5 accent-[#0095f6]"
          />
        </label>

        <label className="flex items-center justify-between rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800">
          <div>
            <p className="font-semibold">{t("settings.ghostMode")}</p>
            <p className="mt-0.5 text-xs text-neutral-500">
              {t("settings.ghostModeDesc")}
            </p>
          </div>
          <input
            type="checkbox"
            checked={ghostMode}
            disabled={loading}
            onChange={(e) => savePrivacy({ ghost_mode: e.target.checked })}
            className="h-5 w-5 accent-[#0095f6]"
          />
        </label>

      </div>
    </Container>
    </LocalePageShell>
  );
}
