import Link from "next/link";
import { KavenixGoogleSearchConsoleSyncButton } from "@/components/kavenix-google-search-console-sync-button";
import type { GoogleSearchConsoleAnalytics } from "@/lib/google-search-console";

const X_PADDING = "px-3 sm:px-4 lg:px-8";

function formatDateTime(value: string | null) {
  if (!value) {
    return "아직 동기화되지 않았습니다.";
  }

  return new Intl.DateTimeFormat("ko-KR", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  }).format(new Date(value));
}

function formatPercent(value: number) {
  return `${(value * 100).toFixed(1)}%`;
}

function formatPosition(value: number) {
  return value > 0 ? value.toFixed(1) : "-";
}

function statusMessage(status: string | null) {
  if (status === "connected") {
    return "Google Search Console을 연결했습니다. 최근 확정 데이터부터 자동 수집합니다.";
  }

  if (status === "site-access") {
    return "연결한 Google 계정에 https://officialsite.kr/ URL 속성 권한이 없습니다. 소유자 또는 전체 권한 계정으로 다시 연결해 주세요.";
  }

  if (status === "denied") {
    return "Google 계정 권한 승인이 취소되었습니다.";
  }

  if (status === "not-configured") {
    return "Google Cloud OAuth 앱 설정 후 연결할 수 있습니다.";
  }

  if (status === "connection-error" || status === "invalid-state") {
    return "연결 처리에 실패했습니다. OAuth 콜백 URL과 Search Console 속성 권한을 확인해 주세요.";
  }

  if (status === "forbidden") {
    return "최고관리자 계정에서만 Google Search Console을 연결할 수 있습니다.";
  }

  return null;
}

function MetricRail({ analytics }: { analytics: GoogleSearchConsoleAnalytics }) {
  const items = [
    ["검색 클릭", analytics.metrics.clicks.toLocaleString("ko-KR")],
    ["노출", analytics.metrics.impressions.toLocaleString("ko-KR")],
    ["평균 클릭률", formatPercent(analytics.metrics.ctr)],
    ["평균 게재순위", formatPosition(analytics.metrics.position)],
  ] as const;

  return (
    <div className="border-b border-[#edf1f6]">
      <div className={`flex overflow-x-auto ${X_PADDING}`}>
        {items.map(([label, value], index) => (
          <div key={label} className={`min-w-[154px] shrink-0 py-4 pr-6 ${index > 0 ? "border-l border-[#edf2fb] pl-6" : ""}`}>
            <p className="text-[12px] font-medium text-[#7c879b]">{label}</p>
            <p className="mt-1.5 text-[24px] font-semibold tracking-[-0.05em] text-[#16233c]">{value}</p>
            <p className="mt-1 text-[11px] text-[#7183a1]">최근 28일 확정 데이터</p>
          </div>
        ))}
      </div>
    </div>
  );
}

function PerformanceList({
  emptyText,
  heading,
  rows,
  type,
}: {
  emptyText: string;
  heading: string;
  rows: GoogleSearchConsoleAnalytics["topPages"] | GoogleSearchConsoleAnalytics["topQueries"];
  type: "page" | "query";
}) {
  return (
    <section className="min-w-0">
      <div className="border-b border-[#edf1f6] px-3 py-3 sm:px-4 lg:px-8">
        <h2 className="text-[14px] font-semibold tracking-[-0.03em] text-[#16233c]">{heading}</h2>
      </div>
      {rows.length > 0 ? (
        <div>
          {rows.map((row, index) => {
            const label = type === "page" ? (row as GoogleSearchConsoleAnalytics["topPages"][number]).page : (row as GoogleSearchConsoleAnalytics["topQueries"][number]).query;

            return (
              <div key={`${label}-${index}`} className="border-b border-[#edf1f6] px-3 py-3 last:border-b-0 sm:px-4 lg:px-8">
                <p className="truncate text-[13px] font-medium text-[#30425f]" title={label}>{label}</p>
                <div className="mt-1.5 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-[#74849f]">
                  <span>클릭 {row.clicks.toLocaleString("ko-KR")}</span>
                  <span>노출 {row.impressions.toLocaleString("ko-KR")}</span>
                  <span>CTR {formatPercent(row.ctr)}</span>
                  <span>순위 {formatPosition(row.position)}</span>
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <p className="px-3 py-8 text-[13px] leading-6 text-[#7284a4] sm:px-4 lg:px-8">{emptyText}</p>
      )}
    </section>
  );
}

export function KavenixGoogleSearchConsoleDashboard({
  analytics,
  status,
}: {
  analytics: GoogleSearchConsoleAnalytics;
  status: string | null;
}) {
  const message = statusMessage(status);

  if (!analytics.configured) {
    return (
      <div className="border-t border-[#edf1f6]">
        <div className={`${X_PADDING} py-6 sm:py-8`}>
          <p className="text-[15px] font-semibold text-[#16233c]">Google Search Console 연결 준비</p>
          <p className="mt-2 max-w-[700px] text-[13px] leading-6 text-[#6f809d]">
            Google Cloud OAuth 웹 클라이언트의 Client ID와 Client Secret을 서버 환경변수에 등록하면, 최고관리자 계정으로 Search Console 권한을 한 번 승인해 검색 성과를 자동 수집할 수 있습니다.
          </p>
          <div className="mt-5 border-y border-[#edf1f6] py-4 text-[12px] leading-6 text-[#536681]">
            <p><span className="font-semibold text-[#263a5a]">필수 환경변수</span> `GOOGLE_SEARCH_CONSOLE_CLIENT_ID`, `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET`</p>
            <p><span className="font-semibold text-[#263a5a]">대상 속성</span> `https://officialsite.kr/`</p>
            <p><span className="font-semibold text-[#263a5a]">OAuth 콜백</span> `https://mail.officialsite.kr/api/integrations/google-search-console/callback`</p>
          </div>
          {message ? <p className="mt-4 text-[12px] text-[#9a5e2e]">{message}</p> : null}
        </div>
      </div>
    );
  }

  if (!analytics.connection) {
    const reconnectRequired = analytics.reconnectRequired;

    return (
      <div className="border-t border-[#edf1f6]">
        <div className={`${X_PADDING} py-6 sm:py-8`}>
          <div className="flex flex-col justify-between gap-5 sm:flex-row sm:items-end">
            <div>
              <p className="text-[15px] font-semibold text-[#16233c]">
                {reconnectRequired ? "URL 접두어 속성으로 다시 연결하세요" : "Google Search Console을 연결하세요"}
              </p>
              <p className="mt-2 max-w-[650px] text-[13px] leading-6 text-[#6f809d]">
                {reconnectRequired
                  ? `기존 도메인 속성은 mail 등 서브도메인까지 포함합니다. ${analytics.targetSiteUrl} URL 접두어 속성으로 다시 인증하면 공개 사이트 데이터만 수집합니다.`
                  : `오피셜메일 공개 페이지의 검색 클릭, 노출, 검색어와 페이지 성과를 매일 수집합니다. 대상은 ${analytics.targetSiteUrl}이며 Google 계정 비밀번호는 저장하지 않습니다.`}
              </p>
            </div>
            <Link href="/api/integrations/google-search-console/authorize" className="om-btn-primary h-10 shrink-0 rounded-[10px] px-4 text-[13px] shadow-none">
              {reconnectRequired ? "URL 속성 다시 연결" : "Google 계정 연결"}
            </Link>
          </div>
          <p className="mt-5 border-t border-[#edf1f6] pt-4 text-[12px] leading-6 text-[#7284a4]">
            기존 도메인 속성 데이터는 재연결 시 제거되며, URL 속성의 데이터는 Google Search Console 확정 기준으로 보통 2~3일 뒤 반영됩니다.
          </p>
          {message ? <p className="mt-2 text-[12px] text-[#9a5e2e]">{message}</p> : null}
        </div>
      </div>
    );
  }

  return (
    <div className="border-t border-[#edf1f6]">
      <div className={`flex flex-col justify-between gap-4 border-b border-[#edf1f6] py-4 sm:flex-row sm:items-start ${X_PADDING}`}>
        <div className="min-w-0">
          <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
            <p className="truncate text-[14px] font-semibold text-[#16233c]">{analytics.connection.siteUrl}</p>
            <span className="om-badge om-badge-sm om-badge-success">연결됨</span>
          </div>
          <p className="mt-1.5 text-[12px] text-[#7284a4]">
            계정 {analytics.connection.accountEmail} · 마지막 수집 {formatDateTime(analytics.connection.lastSyncedAt)}
          </p>
          {analytics.connection.lastSyncError ? <p className="mt-2 text-[12px] text-[#bc4b55]">최근 오류: {analytics.connection.lastSyncError}</p> : null}
          {message ? <p className="mt-2 text-[12px] text-[#2f6df6]">{message}</p> : null}
        </div>
        <KavenixGoogleSearchConsoleSyncButton />
      </div>

      <MetricRail analytics={analytics} />

      <div className="grid border-b border-[#edf1f6] lg:grid-cols-2">
        <PerformanceList type="query" heading="상위 검색어" rows={analytics.topQueries} emptyText="동기화 후 검색어 성과가 표시됩니다." />
        <div className="border-t border-[#edf1f6] lg:border-l lg:border-t-0">
          <PerformanceList type="page" heading="상위 유입 페이지" rows={analytics.topPages} emptyText="동기화 후 페이지 성과가 표시됩니다." />
        </div>
      </div>

      <section>
        <div className="border-b border-[#edf1f6] px-3 py-3 sm:px-4 lg:px-8">
          <h2 className="text-[14px] font-semibold tracking-[-0.03em] text-[#16233c]">개선 후보 검색어</h2>
          <p className="mt-1 text-[12px] text-[#7284a4]">노출은 충분하지만 평균 순위가 6~20위인 검색어입니다.</p>
        </div>
        {analytics.opportunityQueries.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[620px] border-collapse text-left">
              <thead className="border-b border-[#edf1f6] text-[12px] font-semibold text-[#7c879b]">
                <tr>
                  <th className="px-3 py-2.5 sm:px-4 lg:px-8">검색어</th>
                  <th className="px-3 py-2.5 text-right">노출</th>
                  <th className="px-3 py-2.5 text-right">클릭</th>
                  <th className="px-3 py-2.5 text-right">CTR</th>
                  <th className="px-3 py-2.5 text-right sm:px-4 lg:px-8">평균 순위</th>
                </tr>
              </thead>
              <tbody>
                {analytics.opportunityQueries.map((row) => (
                  <tr key={row.query} className="border-b border-[#edf1f6] text-[13px] text-[#33445f] last:border-b-0">
                    <td className="max-w-[360px] truncate px-3 py-3 font-medium sm:px-4 lg:px-8" title={row.query}>{row.query}</td>
                    <td className="px-3 py-3 text-right">{row.impressions.toLocaleString("ko-KR")}</td>
                    <td className="px-3 py-3 text-right">{row.clicks.toLocaleString("ko-KR")}</td>
                    <td className="px-3 py-3 text-right">{formatPercent(row.ctr)}</td>
                    <td className="px-3 py-3 text-right font-semibold text-[#2f6df6] sm:px-4 lg:px-8">{formatPosition(row.position)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="px-3 py-8 text-[13px] leading-6 text-[#7284a4] sm:px-4 lg:px-8">충분한 검색 데이터가 쌓이면 개선 후보를 표시합니다.</p>
        )}
      </section>
    </div>
  );
}
