"use client";

import { FormEvent, useRef, useState } from "react";

const CONTACT_EMAIL = "info@kouzoudesk.com";
const MAX_TOTAL_FILE_BYTES = 4 * 1024 * 1024;

const requestedServices = [
  {
    label: "構造計算（建物上部のみ）",
    note: "基礎検討・構造図作成・構造審査質疑対応は含みません。",
  },
  {
    label: "構造計算＋構造図作成",
    note: "構造計算、基礎検討、構造図作成、通常範囲の構造審査質疑対応まで含みます。",
  },
  {
    label: "相談して決めたい",
    note: "案件内容を確認し、適切な業務範囲をご案内します。",
  },
];

type FormStatus = {
  type: "success" | "error";
  message: string;
} | null;

export default function InquiryForm() {
  const formRef = useRef<HTMLFormElement>(null);
  const [status, setStatus] = useState<FormStatus>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (isSubmitting) return;

    const form = event.currentTarget;
    const formData = new FormData(form);
    const selectedFiles = formData
      .getAll("documents")
      .filter((item): item is File => item instanceof File && item.size > 0);
    const totalFileBytes = selectedFiles.reduce((total, file) => total + file.size, 0);

    if (totalFileBytes > MAX_TOTAL_FILE_BYTES) {
      setStatus({
        type: "error",
        message: "添付資料の合計サイズを4MB以内にしてください。容量が大きい場合は、相談内容欄に資料共有方法をご記入ください。",
      });
      return;
    }

    formData.set("submission-id", crypto.randomUUID());
    setIsSubmitting(true);
    setStatus(null);

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        body: formData,
        headers: {
          Accept: "application/json",
        },
      });
      const result = (await response.json().catch(() => null)) as
        | { message?: string }
        | null;

      if (!response.ok) {
        throw new Error(result?.message || "送信できませんでした。時間をおいて再度お試しください。");
      }

      formRef.current?.reset();
      setStatus({
        type: "success",
        message: "案件内容を送信しました。内容を確認後、入力いただいたメールアドレスへご連絡します。",
      });
    } catch (error) {
      setStatus({
        type: "error",
        message:
          error instanceof Error
            ? error.message
            : "送信できませんでした。時間をおいて再度お試しください。",
      });
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <form ref={formRef} className="inquiry-form" onSubmit={handleSubmit}>
      <div className="form-honeypot" aria-hidden="true">
        <label>
          ウェブサイト
          <input type="text" name="website" tabIndex={-1} autoComplete="off" />
        </label>
      </div>

      <div className="form-section">
        <div className="form-section-title">
          <span>01</span>
          <div><h3>ご連絡先</h3></div>
        </div>
        <div className="form-grid">
          <label className="form-field"><span>会社名 <b>必須</b></span><input type="text" name="company" autoComplete="organization" maxLength={120} placeholder="例：株式会社○○設計" required /></label>
          <label className="form-field"><span>担当者名 <b>必須</b></span><input type="text" name="name" autoComplete="name" maxLength={80} placeholder="例：山田 太郎" required /></label>
          <label className="form-field"><span>メールアドレス <b>必須</b></span><input type="email" name="email" autoComplete="email" maxLength={254} placeholder="example@company.jp" required /></label>
          <label className="form-field"><span>電話番号 <small>任意</small></span><input type="tel" name="phone" autoComplete="tel" inputMode="tel" maxLength={50} placeholder="06-0000-0000" /></label>
        </div>
      </div>

      <div className="form-section">
        <div className="form-section-title">
          <span>02</span>
          <div><h3>建物概要</h3></div>
        </div>
        <div className="form-grid form-grid-three">
          <label className="form-field"><span>建物用途 <b>必須</b></span><select name="building-use" required defaultValue=""><option value="" disabled>選択してください</option><option>戸建住宅</option><option>共同住宅</option><option>店舗</option><option>店舗併用住宅</option><option>その他</option></select></label>
          <label className="form-field"><span>階数 <b>必須</b></span><select name="floors" required defaultValue=""><option value="" disabled>選択してください</option><option>平屋</option><option>2階建</option><option>3階建</option><option>その他</option></select></label>
          <label className="form-field"><span>延べ面積 <b>必須</b></span><div className="input-unit"><input type="number" name="area" min="1" max="100000" step="0.01" inputMode="decimal" placeholder="例：110" required /><span>㎡</span></div></label>
          <label className="form-field"><span>耐震等級 <b>必須</b></span><select name="seismic-grade" required defaultValue=""><option value="" disabled>選択してください</option><option>未定</option><option>等級1</option><option>等級2</option><option>等級3</option></select></label>
          <label className="form-field"><span>耐風等級 <b>必須</b></span><select name="wind-grade" required defaultValue=""><option value="" disabled>選択してください</option><option>未定</option><option>等級1</option><option>等級2</option></select></label>
        </div>
      </div>

      <div className="form-section">
        <div className="form-section-title">
          <span>03</span>
          <div><h3>ご希望内容</h3></div>
        </div>
        <div className="form-wide">
          <fieldset className="form-field service-choice-field">
            <legend>希望業務 <b>必須</b></legend>
            <div className="service-choice-grid">
              {requestedServices.map((item) => (
                <label className="service-choice" key={item.label}>
                  <input type="radio" name="requested-service" value={item.label} required />
                  <span><strong>{item.label}</strong><small>{item.note}</small></span>
                </label>
              ))}
            </div>
          </fieldset>
          <label className="form-field deadline-field"><span>初回構造図送付希望日 <b>必須</b></span><span className="date-input-wrap"><input type="date" name="deadline" required /></span><small>構造計算書・構造図一式の初回提出を希望される日をご入力ください。確認済証の交付予定日ではありません。未定の場合は目安となる日付を選び、相談内容欄に「未定」とご記入ください。</small></label>
          <label className="form-field file-field"><span>資料添付 <small>任意</small></span><input type="file" name="documents" accept=".pdf,.jww,.dwg,.dxf,.zip" multiple /><small>対応形式：PDF・JWW・DWG・DXF・ZIP（合計4MBまで）。その他の形式や容量が大きい資料は、相談内容欄に共有方法をご記入ください。</small></label>
          <label className="form-field textarea-field"><span>案件概要・相談内容 <b>必須</b></span><textarea name="message" rows={7} maxLength={5000} placeholder="建物の特徴、構造上気になっている点、ご希望の対応範囲、初回成果物の希望時期などをご記入ください。" required /></label>
        </div>
      </div>

      <div className="form-submit">
        <label className="privacy-check"><input type="checkbox" name="privacy-consent" value="agreed" required /><span><a href="/privacy">プライバシーポリシー</a>を確認し、同意します。</span></label>
        <button type="submit" disabled={isSubmitting} aria-busy={isSubmitting}>
          {isSubmitting ? "送信しています…" : "案件内容を送信する"}
        </button>
        <p>送信先：<a href={`mailto:${CONTACT_EMAIL}`}>{CONTACT_EMAIL}</a></p>
        {status ? (
          <p className={`form-status form-status-${status.type}`} role="status" aria-live="polite">
            {status.message}
          </p>
        ) : null}
      </div>
    </form>
  );
}
