/**
 * Service Detail Page.
 * Shows NyxID service details: name, description, proxy URL, proxied OpenAPI spec URL.
 * @module pages/ServiceDetailPage
 */

import { useState, useEffect } from "react";
import { useParams, useNavigate, useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { PageTransition } from "@/components/layout/PageTransition";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { useAuthStore, isAdmin as checkIsAdmin, useCurrentUser } from "@/stores/authStore";
import { GenerateSkillModal } from "@/components/skill/GenerateSkillModal";
import { config } from "@/config";
import { translateError } from "@/utils/translateError";

const NYXID_API_BASE = config.nyxidApiBaseUrl;

interface ServiceDetail {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  proxyUrl: string;
  openapiProxyUrl: string | null;
  serviceCategory: string;
  isActive: boolean;
  repositoryUrl: string | null;
  homepageUrl: string | null;
}

export function ServiceDetailPage() {
  const { t } = useTranslation();
  const { id } = useParams<{ id: string }>();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const source = searchParams.get("source") ?? "admin";

  const [service, setService] = useState<ServiceDetail | null>(null);
  const accessToken = useAuthStore((s) => s.accessToken);
  const [isLoading, setIsLoading] = useState<boolean>(Boolean(accessToken && id));
  const [error, setError] = useState<string | null>(null);
  const [showGenerateModal, setShowGenerateModal] = useState(false);
  const user = useCurrentUser();
  const isAdminUser = checkIsAdmin(user);

  useEffect(() => {
    if (!accessToken || !id) return;

    fetch(`${NYXID_API_BASE}/api/v1/services/${id}`, {
      headers: { Authorization: `Bearer ${accessToken}` },
    })
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then((data) => {
        const s = data.service ?? data;
        const hasSpec = !!(s.openapi_spec_url || s.api_spec_url);
        setService({
          id: s.id,
          name: s.name ?? s.slug ?? "Unknown",
          slug: s.slug ?? "",
          description: s.description ?? null,
          proxyUrl: s.slug ? `${NYXID_API_BASE}/api/v1/proxy/s/${s.slug}/{path}` : "",
          openapiProxyUrl: hasSpec && s.slug ? `${NYXID_API_BASE}/api/v1/proxy/s/${s.slug}/api/openapi.json` : null,
          serviceCategory: s.service_category ?? "unknown",
          isActive: s.is_active ?? false,
          repositoryUrl: s.repository_url ?? null,
          homepageUrl: s.homepage_url ?? null,
        });
        setIsLoading(false);
      })
      .catch((err) => {
        console.error("[ServiceDetail]", err);
        setError(translateError(err));
        setIsLoading(false);
      });
  }, [accessToken, id]);

  if (isLoading) {
    return (
      <PageTransition>
        <div className="py-4">
          <p className="font-text text-sm text-meta">Loading...</p>
        </div>
      </PageTransition>
    );
  }

  if (error || !service) {
    return (
      <PageTransition>
        <div className="py-4">
          <p className="font-text text-sm text-danger">{t("serviceDetail.failedToLoad", { error: error ?? t("serviceDetail.notFound") })}</p>
          <Button variant="secondary" className="mt-4" onClick={() => navigate(-1)}>{t("serviceDetail.back")}</Button>
        </div>
      </PageTransition>
    );
  }

  return (
    <PageTransition>
      <div className="py-4">
        <button
          onClick={() => navigate(source === "my" ? "/services/my" : "/services/admin")}
          className="flex items-center gap-2 font-text text-sm text-meta hover:text-accent transition-colors mb-4 cursor-pointer"
        >
          <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          {source === "my" ? t("serviceDetail.backToMy") : t("serviceDetail.backToAdmin")}
        </button>

        <div className="mb-6">
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-3">
              <h1 className="font-display text-2xl tracking-wider text-strong">{service.name}</h1>
              <Badge color={service.isActive ? "green" : "muted"}>
                {service.isActive ? t("serviceDetail.statusActive") : t("serviceDetail.statusInactive")}
              </Badge>
              <Badge color="yellow">{service.serviceCategory}</Badge>
            </div>
            {isAdminUser && (
              <Button onClick={() => setShowGenerateModal(true)}>
                {t("serviceDetail.generateSkillBtn")}
              </Button>
            )}
          </div>
          {service.description && (
            <p className="font-text text-sm text-meta">{service.description}</p>
          )}
        </div>

        <div className="space-y-4">
          <Card>
            <h3 className="font-display text-[10px] font-700 tracking-widest uppercase text-meta mb-2">{t("serviceDetail.proxyUrlHeading")}</h3>
            <p className="font-mono text-xs text-accent break-all">{service.proxyUrl}</p>
          </Card>

          <Card>
            <h3 className="font-display text-[10px] font-700 tracking-widest uppercase text-meta mb-2">{t("serviceDetail.openapiHeading")}</h3>
            {service.openapiProxyUrl ? (
              <a href={service.openapiProxyUrl} target="_blank" rel="noopener noreferrer" className="font-mono text-xs text-accent hover:underline break-all">
                {service.openapiProxyUrl}
              </a>
            ) : (
              <p className="font-text text-xs text-meta italic">{t("serviceDetail.openapiNotConfigured")}</p>
            )}
          </Card>

          <Card>
            <h3 className="font-display text-[10px] font-700 tracking-widest uppercase text-meta mb-2">{t("serviceDetail.sourceCodeHeading")}</h3>
            {service.repositoryUrl ? (
              <a href={service.repositoryUrl} target="_blank" rel="noopener noreferrer" className="font-mono text-xs text-accent hover:underline break-all">
                {service.repositoryUrl}
              </a>
            ) : (
              <p className="font-text text-xs text-meta italic">{t("serviceDetail.notConfigured")}</p>
            )}
          </Card>

          <Card>
            <h3 className="font-display text-[10px] font-700 tracking-widest uppercase text-meta mb-2">{t("serviceDetail.homepageHeading")}</h3>
            {service.homepageUrl ? (
              <a href={service.homepageUrl} target="_blank" rel="noopener noreferrer" className="font-mono text-xs text-accent hover:underline break-all">
                {service.homepageUrl}
              </a>
            ) : (
              <p className="font-text text-xs text-meta italic">{t("serviceDetail.notConfigured")}</p>
            )}
          </Card>
        </div>
        {showGenerateModal && service && (
          <GenerateSkillModal
            isOpen={showGenerateModal}
            onClose={() => setShowGenerateModal(false)}
            onSuccess={() => {
              setShowGenerateModal(false);
              navigate("/registry?tab=system");
            }}
            serviceId={service.id}
            serviceName={service.name}
            proxyUrl={service.proxyUrl}
            openapiSpecUrl={service.openapiProxyUrl}
            repositoryUrl={service.repositoryUrl}
            homepageUrl={service.homepageUrl}
          />
        )}
      </div>
    </PageTransition>
  );
}
