"use client";

import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import InstagramSignInButton from "@/components/auth/InstagramSignInButton";
import useAxios from "@/hooks/useAxios";
import React, { useCallback, useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type InstagramStatus = {
  linked: boolean;
  connected: boolean;
  instagram_username: string | null;
  instagram_account_type: string | null;
  connected_at: string | null;
};

export default function InstagramImportSettingsPage() {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [status, setStatus] = useState<InstagramStatus | null>(null);
  const [clientId, setClientId] = useState("");
  const [loading, setLoading] = useState(true);
  const [disconnecting, setDisconnecting] = useState(false);

  const loadStatus = useCallback(async () => {
    setLoading(true);
    try {
      const data = (await request("GET", "/auth/instagram/status")) as InstagramStatus;
      setStatus(data);
    } catch {
      toast.error(t("settings.edit.instagramImport.loadError"));
    } finally {
      setLoading(false);
    }
  }, [request, t]);

  useEffect(() => {
    loadStatus();
  }, [loadStatus]);

  useEffect(() => {
    let cancelled = false;
    fetch("/api/auth/config", { cache: "no-store" })
      .then((res) => (res.ok ? res.json() : null))
      .then((data: { instagramClientId?: string } | null) => {
        if (!cancelled && data?.instagramClientId) {
          setClientId(data.instagramClientId);
        }
      })
      .catch(() => {});
    return () => {
      cancelled = true;
    };
  }, []);

  const handleDisconnect = async () => {
    setDisconnecting(true);
    try {
      await request("POST", "/auth/instagram/disconnect", {});
      toast.success(t("settings.edit.instagramImport.disconnectSuccess"));
      await loadStatus();
    } catch {
      toast.error(t("settings.edit.instagramImport.disconnectError"));
    } finally {
      setDisconnecting(false);
    }
  };

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("settings.edit.nav.instagramImport")}</PageTitle>
        <div className="mx-auto flex max-w-md flex-col items-center py-8 text-center">
          {loading ? (
            <p className="text-sm text-neutral-500">{t("common.loading")}</p>
          ) : status?.connected ? (
            <>
              <p className="text-sm text-neutral-600 dark:text-neutral-300">
                {t("settings.edit.instagramImport.linkedHint")}
              </p>
              {status.instagram_username ? (
                <p className="mt-3 text-sm font-semibold" dir="ltr">
                  @{status.instagram_username}
                </p>
              ) : null}
              <button
                type="button"
                onClick={handleDisconnect}
                disabled={disconnecting}
                className="mt-6 rounded-2xl border-2 border-red-200 px-4 py-2 text-sm font-semibold text-red-600 disabled:opacity-60"
              >
                {t("settings.edit.instagramImport.disconnectButton")}
              </button>
            </>
          ) : (
            <>
              <p className="mb-6 text-sm text-neutral-600 dark:text-neutral-300">
                {t("settings.edit.instagramImport.unlinkedHint")}
              </p>
              <InstagramSignInButton mode="link" clientId={clientId} />
            </>
          )}
        </div>
      </Container>
    </LocalePageShell>
  );
}
