"use client";

import { FormEvent, useState } from "react";
import { StaticUiLocalizer } from "@/components/static-ui-localizer";
import { useI18n } from "@/components/i18n-provider";
import { translateStaticUiText } from "@/lib/i18n-dictionaries";
import { getLocalizedPublicPath } from "@/lib/i18n-urls";

const platformOptions = [
  { value: "", label: "제휴 플랫폼을 선택해주세요" },
  { value: "coworking", label: "공유오피스·비즈니스센터" },
  { value: "incubator", label: "창업보육센터·공공 지원기관" },
  { value: "accelerator", label: "액셀러레이터·VC·창업 프로그램" },
  { value: "domain-hosting", label: "도메인 등록·호스팅 사업자" },
  { value: "web-commerce", label: "웹빌더·쇼핑몰·커머스 플랫폼" },
  { value: "education-community", label: "교육기관·창업 커뮤니티" },
  { value: "saas-api", label: "SaaS·API·솔루션 연동" },
  { value: "other", label: "기타·직접 입력" },
] as const;

const inputClass =
  "h-12 w-full rounded-[12px] border border-[#dce5f3] bg-white px-4 text-[14px] text-[#17243c] outline-none transition focus:border-[#8db4ff] focus:ring-4 focus:ring-[#edf4ff]";

export function PartnerInquiryForm() {
  const { locale } = useI18n();
  const ui = (source: string) => translateStaticUiText(locale, source);
  const [platformType, setPlatformType] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [message, setMessage] = useState("");
  const [success, setSuccess] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setMessage("");
    setSubmitting(true);

    const form = event.currentTarget;
    const data = new FormData(form);
    const payload = Object.fromEntries(data.entries());
    const response = await fetch("/api/partner-inquiries", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        ...payload,
        consented: data.get("consented") === "on",
      }),
    }).catch(() => null);
    const result = response ? await response.json().catch(() => null) : null;

    setSubmitting(false);

    if (!response?.ok || !result?.ok) {
      setMessage(locale === "ko" && result?.message ? result.message : ui("문의 접수 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요."));
      return;
    }

    setSuccess(true);
    form.reset();
    setPlatformType("");
  }

  if (success) {
    return (
      <StaticUiLocalizer>
      <div className="flex min-h-[420px] flex-col justify-center border-y border-[#dce8fb] bg-[linear-gradient(135deg,#f5f8ff_0%,#ffffff_58%,#edf5ff_100%)] px-5 py-16 sm:px-10">
        <span className="inline-flex h-12 w-12 items-center justify-center rounded-full bg-[#2f6df6] text-white">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="h-6 w-6" aria-hidden="true">
            <path d="m5 12 4.2 4.2L19 6.8" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </span>
        <h2 className="mt-7 text-[28px] font-semibold tracking-[-0.055em] text-[#14213a] sm:text-[34px]">제휴 문의가 접수되었습니다.</h2>
        <p className="mt-4 max-w-[560px] text-[15px] leading-7 text-[#63738e]">기관 특성과 지원 대상에 맞는 협업 가능 여부와 다음 논의 사항을 검토한 뒤 담당자 이메일로 회신드리겠습니다.</p>
        <button type="button" onClick={() => setSuccess(false)} className="mt-8 inline-flex h-11 w-fit cursor-pointer items-center rounded-[11px] border border-[#cfe0ff] px-5 text-[13px] font-semibold text-[#2f6df6] transition hover:bg-white">
          문의 내용 다시 작성
        </button>
      </div>
      </StaticUiLocalizer>
    );
  }

  return (
    <StaticUiLocalizer>
    <form onSubmit={handleSubmit} className="grid gap-x-5 gap-y-5" noValidate>
      <div className="hidden" aria-hidden="true">
        <label htmlFor="partner-website">웹사이트</label>
        <input id="partner-website" name="website" tabIndex={-1} autoComplete="off" />
      </div>

      <div className="grid gap-5 sm:grid-cols-2">
        <label className="grid gap-2 text-[13px] font-semibold text-[#30415e]">
          기관·회사명 <span className="sr-only">필수</span>
          <input name="organizationName" required maxLength={191} className={inputClass} placeholder="예: OO 창업보육센터" />
        </label>
        <label className="grid gap-2 text-[13px] font-semibold text-[#30415e]">
          담당자명 <span className="sr-only">필수</span>
          <input name="contactName" required maxLength={120} className={inputClass} placeholder="성함을 입력해주세요" />
        </label>
      </div>

      <div className="grid gap-5 sm:grid-cols-2">
        <label className="grid gap-2 text-[13px] font-semibold text-[#30415e]">
          담당자 이메일 <span className="sr-only">필수</span>
          <input name="contactEmail" type="email" required maxLength={320} className={inputClass} placeholder="contact@내도메인.com" />
        </label>
        <label className="grid gap-2 text-[13px] font-semibold text-[#30415e]">
          연락처 <span className="font-normal text-[#8a98ae]">선택</span>
          <input name="contactPhone" type="tel" maxLength={40} className={inputClass} placeholder="02-0000-0000" />
        </label>
      </div>

      <div className="grid gap-5 sm:grid-cols-2">
        <label className="grid gap-2 text-[13px] font-semibold text-[#30415e]">
          제휴 플랫폼 <span className="sr-only">필수</span>
          <select name="platformType" required value={platformType} onChange={(event) => setPlatformType(event.target.value)} className={`${inputClass} cursor-pointer appearance-none bg-[linear-gradient(45deg,transparent_50%,#7889a4_50%),linear-gradient(135deg,#7889a4_50%,transparent_50%)] bg-[position:calc(100%-18px)_21px,calc(100%-13px)_21px] bg-[size:5px_5px,5px_5px] bg-no-repeat pr-10`}>
            {platformOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
          </select>
        </label>
        <label className="grid gap-2 text-[13px] font-semibold text-[#30415e]">
          예상 지원 규모 <span className="font-normal text-[#8a98ae]">선택</span>
          <select name="estimatedMembers" className={`${inputClass} cursor-pointer`} defaultValue="">
            <option value="">규모를 선택해주세요</option>
            <option value="under-50">50개사 미만</option>
            <option value="50-199">50~199개사</option>
            <option value="200-499">200~499개사</option>
            <option value="500-plus">500개사 이상</option>
            <option value="unknown">아직 정해지지 않음</option>
          </select>
        </label>
      </div>

      <div aria-hidden={platformType !== "other"} className={`grid overflow-hidden transition-[grid-template-rows,opacity] duration-300 ${platformType === "other" ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"}`}>
        <label className="grid min-h-0 gap-2 text-[13px] font-semibold text-[#30415e]">
          플랫폼 유형 직접 입력
          <input name="platformTypeCustom" disabled={platformType !== "other"} required={platformType === "other"} maxLength={120} className={inputClass} placeholder="예: 지역 창업자 커뮤니티" />
        </label>
      </div>

      <label className="grid gap-2 text-[13px] font-semibold text-[#30415e]">
        제휴 목적·운영 방식 <span className="font-normal text-[#8a98ae]">선택</span>
        <textarea name="message" maxLength={3000} className="min-h-[148px] w-full resize-y rounded-[12px] border border-[#dce5f3] bg-white px-4 py-3.5 text-[14px] leading-6 text-[#17243c] outline-none transition focus:border-[#8db4ff] focus:ring-4 focus:ring-[#edf4ff]" placeholder="지원 대상, 희망 일정, 콘텐츠 협업 또는 API 연동 등 검토 중인 방식을 알려주세요." />
      </label>

      <label className="flex cursor-pointer items-start gap-3 border-t border-[#e8eef8] pt-5 text-[12px] leading-5 text-[#6c7c96]">
        <input name="consented" type="checkbox" required className="mt-0.5 h-4 w-4 shrink-0 rounded border-[#cdd8e8] text-[#2f6df6]" />
        <span>제휴 상담을 위해 기관명, 담당자 정보와 문의 내용을 수집·이용하는 데 동의합니다. 문의 처리 완료 후 3년간 보관하며 삭제를 요청할 수 있습니다. <a href={getLocalizedPublicPath("/privacy", locale)} target="_blank" rel="noreferrer" className="font-semibold text-[#2f6df6] hover:underline">개인정보처리방침 보기</a></span>
      </label>

      {message ? <p role="alert" className="text-[13px] font-medium text-[#d44747]">{message}</p> : null}

      <button type="submit" disabled={submitting} className="inline-flex h-12 w-full cursor-pointer items-center justify-center rounded-[12px] bg-[#2f6df6] px-6 text-[14px] font-semibold text-white transition hover:bg-[#245ddd] disabled:cursor-wait disabled:bg-[#9ab8f9] sm:w-fit sm:min-w-[180px]">
        {submitting ? "접수 중..." : "제휴 문의 보내기"}
      </button>
    </form>
    </StaticUiLocalizer>
  );
}
