"use client";

import { useState } from "react";
import { logout } from "@/services/auth";
import { useAuthStore } from "@/store/authStore";
import { useLocaleStore } from "@/store/uiStore";
import { useTenantStore } from "@/store/tenantStore";
import { t } from "@/lib/locale";
import PageHeader from "@/components/ui/PageHeader";
import FileUpload from "@/components/ui/FileUpload";

export default function SettingsPage() {
  const locale = useLocaleStore((s) => s.locale);
  const setLocale = useLocaleStore((s) => s.setLocale);
  const currentTenant = useTenantStore((s) => s.tenantId);
  const clearAuth = useAuthStore((s) => s.clearAuth);
  const [_, setUploadedFiles] = useState<string[]>([]);

  const authMode =
    process.env.NEXT_PUBLIC_AUTH_MODE?.toLowerCase?.() === "ldap" ? "LDAP" : "LOCAL";

  const handleLogout = async () => {
    await logout();
    clearAuth();
    window.location.replace("/login");
  };

  const onUpload = (files: File[]) => {
    setUploadedFiles(files.map((file) => file.name));
  };

  return (
    <main className="vstack gap-3">
      <PageHeader
        title={t("settings", locale)}
        breadcrumb={[
          { label: t("dashboard", locale), href: "/dashboard" },
          { label: t("settings", locale), href: "/dashboard/settings" }
        ]}
      />
      <section className="card page-card">
        <div className="card-body vstack gap-3">
          <div>
            <label className="form-label">Locale</label>
            <select
              className="form-select"
              value={locale}
              onChange={(e) => setLocale(e.target.value as "en" | "id")}
            >
              <option value="en">en-US</option>
              <option value="id">id-ID</option>
            </select>
          </div>
          <div>
            <strong>{t("tenant", locale)}:</strong> {currentTenant}
          </div>
          <div>
            <strong>Auth Mode:</strong> {authMode}
          </div>
          <div>
            <FileUpload
              label="Upload attachment (optional)"
              accept=".txt,.csv,.json"
              onFileSelect={onUpload}
              helperText="Optional local file preview upload for admin workflows."
            />
          </div>
          <button className="btn btn-outline-danger w-auto" onClick={handleLogout}>
            {t("logout", locale)}
          </button>
        </div>
      </section>
    </main>
  );
}
