"use client";

import Link from "next/link";
import { useState } from "react";
import { saveAiAssistSettingsAction } from "@/app/actions/session";
import { StaticUiLocalizer } from "@/components/static-ui-localizer";
import { SubmitButton } from "@/components/submit-button";
import type { MailPlanSummary } from "@/lib/mail-billing";
import type { MailAiAssistOverview } from "@/lib/mail-automation";

const aiAssistFlowSteps = [
  {
    title: "수신 감지",
    description: "새 메일이 들어오면 요약 대상만 먼저 선별합니다.",
  },
  {
    title: "요약 릴레이",
    description: "핵심 요청, 의심 포인트, 답장 방향을 외부 메일로 보냅니다.",
  },
  {
    title: "답장 연결",
    description: "릴레이 메일 답장이 원래 보낸 사람에게 이어집니다.",
  },
];

function formatDateLabel(value: string | null) {
  if (!value) {
    return "아직 없음";
  }

  const date = new Date(value);
  return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, "0")}.${String(
    date.getDate(),
  ).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(
    date.getMinutes(),
  ).padStart(2, "0")}`;
}

export function MailAiAssistPanel({
  overview,
  planSummary,
  canManageBilling,
  embedded = false,
}: {
  overview: MailAiAssistOverview | null;
  planSummary: MailPlanSummary;
  canManageBilling: boolean;
  embedded?: boolean;
}) {
  const [enabled, setEnabled] = useState(Boolean(overview?.enabled));
  const aiAssistUnlocked = planSummary.aiAssistAvailable;
  const controlsDisabled = !aiAssistUnlocked;
  const representativeMailbox = overview?.representativeMailbox ?? "대표 메일함";
  const notificationEmail = overview?.notificationEmail ?? "";

  const pageContent = (
    <StaticUiLocalizer>
      <>
      <div className="om-setup-header lg:flex-row lg:items-start lg:justify-between lg:gap-5">
        <div className="om-setup-header-copy">
          <h1 className="om-page-title text-[#16233c]">
            AI 어시스트 브릿지
          </h1>
          <p className="om-setup-header-description">
            메일함을 열기 전에 핵심 요약, 확인할 사항, 답장 방향을 먼저 받아보고 바로 판단하세요.
          </p>
        </div>
        <div
          className={`text-[13px] font-semibold ${
            aiAssistUnlocked ? "text-[#2f6df6]" : "text-[#8a97ad]"
          }`}
        >
          {aiAssistUnlocked ? `${planSummary.label} 이용 중` : "성장 플랜 필요"}
        </div>
      </div>

      <div className="om-setup-content">
        <form
          action={saveAiAssistSettingsAction}
          className="overflow-hidden border-b border-[#dfe7f4] bg-white"
        >
          {controlsDisabled ? (
            <div className="border-b border-[#edf1f6] bg-[#f8fbff] px-3 py-3 sm:px-4 lg:px-5">
              <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
                <div className="min-w-0">
                  <p className="text-[15px] font-semibold text-[#16233c]">
                    성장 플랜에서 AI 요약 릴레이가 열립니다.
                  </p>
                  <p className="mt-1 text-[13px] leading-6 text-[#6a7b98]">
                    {canManageBilling
                      ? "긴 문의, 광고성 메일, 제휴 제안을 먼저 요약해서 놓칠 메일과 버릴 메일을 빠르게 구분합니다."
                      : "대표 관리자 계정의 성장 플랜이 활성화되면 멤버도 각자 설정해서 사용할 수 있습니다."}
                  </p>
                </div>
                {canManageBilling ? (
                  <Link
                    href="/mail?panel=setup&section=billing"
                    prefetch={false}
                    className="om-btn-primary h-10 rounded-[10px] px-4 text-[13px] shadow-none hover:shadow-none"
                  >
                    성장 플랜 시작하기
                  </Link>
                ) : null}
              </div>
            </div>
          ) : null}

          <div className="grid gap-0 xl:grid-cols-[minmax(0,0.84fr)_minmax(380px,0.92fr)]">
            <div className="flex min-w-0 flex-col border-b border-[#edf1f6] px-3 py-4 sm:px-4 lg:px-5 xl:border-b-0 xl:border-r">
              <div className="flex flex-col gap-5 lg:flex-row lg:items-start lg:justify-between">
                <div className="min-w-0">
                  <p className="text-[25px] font-semibold leading-[1.2] tracking-[-0.06em] text-[#16233c] sm:text-[31px]">
                    새 메일이 오면,
                    <br className="hidden sm:block" /> 판단할 내용만 먼저 도착합니다.
                  </p>
                  <p className="mt-4 max-w-[620px] text-[14px] leading-7 text-[#63748f]">
                    본문을 다 열어보기 전에 핵심 요청, 의심 포인트, 추천 답장까지 한 번에 정리합니다.
                    답장은 릴레이 메일에서 그대로 이어집니다.
                  </p>
                </div>

                <button
                  type="button"
                  role="switch"
                  aria-checked={enabled}
                  aria-label={enabled ? "AI 어시스트 활성화됨" : "AI 어시스트 비활성화"}
                  disabled={controlsDisabled}
                  onClick={() => setEnabled((current) => !current)}
                  className={`relative inline-flex h-9 w-[66px] shrink-0 items-center rounded-full p-1 transition-colors duration-200 ${
                    enabled ? "bg-[#2f6df6]" : "bg-[#d9e2f1]"
                  } ${controlsDisabled ? "cursor-not-allowed opacity-60" : "cursor-pointer"}`}
                >
                  <span
                    className={`h-7 w-7 rounded-full bg-white shadow-[0_6px_16px_rgba(24,39,74,0.18)] transition-transform duration-200 ${
                      enabled ? "translate-x-[30px]" : "translate-x-0"
                    }`}
                  />
                </button>
              </div>

              <div className="mt-8 border-t border-[#edf1f6] pt-4">
                <p className="text-[12px] font-semibold uppercase tracking-[0.14em] text-[#8a99b4]">
                  Bridge Flow
                </p>
                <ol className="mt-3 space-y-3 border-l border-[#dfe7f4] pl-4">
                  {aiAssistFlowSteps.map((step, index) => (
                    <li key={step.title} className="relative">
                      <span className="absolute -left-[25px] top-0.5 flex h-[18px] w-[18px] items-center justify-center rounded-full border border-[#d7e4ff] bg-white text-[10px] font-semibold text-[#2f6df6]">
                        {index + 1}
                      </span>
                      <p className="text-[13px] font-semibold tracking-[-0.02em] text-[#16233c]">
                        {step.title}
                      </p>
                      <p className="mt-1 text-[12px] leading-5 text-[#71829d]">
                        {step.description}
                      </p>
                    </li>
                  ))}
                </ol>
              </div>

              <input type="hidden" name="enabled" value={enabled ? "1" : "0"} />
            </div>

            <div className="bg-[linear-gradient(180deg,#f8fbff_0%,#ffffff_100%)] px-0 py-4 sm:px-4 lg:px-5">
              <div className="mx-auto max-w-[620px] border-y border-[#dfe8f8] bg-white p-3 text-[#16233c] sm:rounded-[10px] sm:border sm:p-5 sm:shadow-[0_18px_44px_rgba(24,39,74,0.08)]">
                <div className="flex items-center gap-2.5 text-[#2f6df6]">
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="1.8"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="h-[22px] w-[22px]"
                    aria-hidden="true"
                  >
                    <rect x="3.5" y="5.5" width="17" height="13" rx="2.5" />
                    <path d="m4.8 7 7.2 5.6L19.2 7" />
                  </svg>
                  <span className="text-[20px] font-extrabold tracking-[-0.08em]">오피셜메일</span>
                </div>

                <h2 className="mt-5 text-[20px] font-semibold leading-7 tracking-[-0.04em] text-[#0f1d35] sm:text-[22px]">
                  카베닉스 대표 메일로 새 메일이 도착했습니다.
                </h2>

                <div className="mt-5 rounded-[10px] bg-[#f4f7fc] px-4 py-3 text-[13px] leading-6 text-[#21304a]">
                  <p><strong>보낸 사람</strong> 고객 담당자 &lt;customer@gmail.com&gt;</p>
                  <p><strong>받는 사람</strong> {representativeMailbox}</p>
                  <p><strong>제목</strong> 광고성 제안 메일로 보임</p>
                </div>

                <div className="mt-5 space-y-5 text-[14px] leading-7 text-[#23324d]">
                  <section>
                    <h3 className="text-[15px] font-semibold text-[#0f1d35]">핵심 요약</h3>
                    <p className="mt-2">광고성 제안 메일이며, 링크와 이미지가 포함되어 있습니다.</p>
                  </section>
                  <section>
                    <h3 className="text-[15px] font-semibold text-[#0f1d35]">확인할 사항</h3>
                    <p className="mt-2">발신자 신뢰도와 첨부 링크 안전성을 먼저 확인해야 합니다.</p>
                  </section>
                  <section>
                    <h3 className="text-[15px] font-semibold text-[#0f1d35]">추천 답장 방향</h3>
                    <p className="mt-2">불필요한 광고라면 정중히 거절하고, 업무 관련 요청이면 추가 정보를 요청하세요.</p>
                  </section>
                </div>

                <div className="mt-6 rounded-[10px] bg-[#eef4ff] px-4 py-4 text-[13px] leading-6 text-[#2f4c83]">
                  <p>이 메일에 답장하면 원본 발신자에게 그대로 전달됩니다.</p>
                  <span className="mt-3 inline-flex h-10 items-center justify-center rounded-[10px] bg-[#2f6df6] px-4 text-[13px] font-semibold text-white">
                    메일원본 확인
                  </span>
                </div>
              </div>
            </div>
          </div>

          <div className="border-t border-[#edf1f6] px-3 py-4 sm:px-4 lg:px-5">
            <div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-end">
              <label className="block min-w-0">
                <span className="mb-2 block text-[13px] font-semibold text-[#4f6284]">
                  요약을 받을 외부 메일
                </span>
                <input
                  name="notificationEmail"
                  type="email"
                  defaultValue={notificationEmail}
                  placeholder="예: founder@gmail.com"
                  disabled={!enabled || controlsDisabled}
                  className="h-[52px] w-full rounded-[10px] border border-[#dbe5f7] bg-white px-4 text-[15px] text-[#1a2943] outline-none transition-colors placeholder:text-[#97a7c2] focus:border-[#bcd1ff] disabled:cursor-not-allowed disabled:bg-[#f5f7fb] disabled:text-[#97a7c2]"
                />
              </label>
              <SubmitButton
                label="설정 저장"
                pendingLabel="저장 중..."
                className="om-btn-primary h-[52px] rounded-[10px] px-5 text-[14px] shadow-none hover:shadow-none"
                disabled={controlsDisabled}
              />
            </div>

            <div className="mt-4 grid gap-0 border-t border-[#edf1f6] text-[13px] sm:grid-cols-3">
              <div className="py-4 sm:pr-4">
                <p className="font-semibold text-[#7183a2]">대표 메일함</p>
                <p className="mt-2 truncate text-[15px] font-semibold text-[#16233c]">{representativeMailbox}</p>
              </div>
              <div className="border-t border-[#edf1f6] py-4 sm:border-l sm:border-t-0 sm:px-4">
                <p className="font-semibold text-[#7183a2]">전송된 요약</p>
                <p className="mt-2 text-[15px] font-semibold text-[#2f6df6]">
                  {(overview?.sentSummaryCount ?? 0).toLocaleString("ko-KR")}건
                </p>
                <p className="mt-1 text-[12px] text-[#7b8ca8]">
                  마지막 {formatDateLabel(overview?.lastSummarizedAt ?? null)}
                </p>
              </div>
              <div className="border-t border-[#edf1f6] py-4 sm:border-l sm:border-t-0 sm:pl-4">
                <p className="font-semibold text-[#7183a2]">릴레이 답장</p>
                <p className="mt-2 text-[15px] font-semibold text-[#16233c]">
                  {(overview?.relayedCount ?? 0).toLocaleString("ko-KR")}건
                </p>
                <p className="mt-1 text-[12px] text-[#7b8ca8]">
                  마지막 {formatDateLabel(overview?.lastRelayedAt ?? null)}
                </p>
              </div>
            </div>

            <p className="mt-4 text-[13px] leading-6 text-[#7384a0]">
              {aiAssistUnlocked
                ? "활성화 이후 새로 들어오는 메일부터 요약 알림과 답장 릴레이가 동작합니다."
                : "성장 플랜 활성화 후 새로 들어오는 메일부터 요약 알림과 답장 릴레이가 동작합니다."}
            </p>
          </div>
        </form>

        <section className="border-b border-[#edf1f6] px-3 py-3 sm:px-4 lg:px-5">
          <p className="text-[13px] leading-6 text-[#7384a0]">
            메일 원문과 첨부는 보존하고, 요약에 실패해도 원본은 전달됩니다. 실제 발송 전 최종 답장 내용은 사용자가 직접 확인해야 합니다.
          </p>
        </section>
      </div>
      </>
    </StaticUiLocalizer>
  );

  if (embedded) {
    return pageContent;
  }

  return (
    <div className="om-setup-page h-full overflow-y-auto">
      <div className="om-setup-shell">{pageContent}</div>
    </div>
  );
}
