"use client";

import { useState, FormEvent } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Swal from "sweetalert2";
import { Mail, Lock, Building2, User as UserIcon, Phone, FileText, MapPin, ArrowRight, Eye, EyeOff } from "lucide-react";

export default function SignupPage() {
  const router = useRouter();
  const [form, setForm] = useState({
    email: "",
    password: "",
    passwordConfirm: "",
    companyName: "",
    ceoName: "",
    bizNo: "",
    phone: "",
    address: "",
  });
  const [showPw, setShowPw] = useState(false);
  const [loading, setLoading] = useState(false);

  const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) =>
    setForm({ ...form, [k]: e.target.value });

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    if (!form.email || !form.password || !form.companyName || !form.phone || !form.address) {
      Swal.fire({ icon: "warning", title: "필수 항목을 입력하세요.", text: "이메일·비밀번호·업체명·전화번호·주소는 필수입니다." });
      return;
    }
    if (form.password.length < 8) {
      Swal.fire({ icon: "warning", title: "비밀번호는 8자 이상이어야 합니다." });
      return;
    }
    if (form.password !== form.passwordConfirm) {
      Swal.fire({ icon: "warning", title: "비밀번호가 일치하지 않습니다." });
      return;
    }
    setLoading(true);
    try {
      const res = await fetch("/api/auth/signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: form.email,
          password: form.password,
          companyName: form.companyName,
          ceoName: form.ceoName,
          bizNo: form.bizNo,
          phone: form.phone,
          address: form.address,
        }),
      });
      const data = await res.json();
      if (data.success) {
        await Swal.fire({
          icon: "success",
          title: "가입이 완료되었습니다",
          text: "이제 발주를 시작하실 수 있습니다.",
          confirmButtonColor: "#0f766e",
        });
        // 거래처 가입 직후 — 출고 요청 화면으로
        router.push("/m/orders/new");
      } else {
        Swal.fire({ icon: "error", title: "가입 실패", text: data.message });
      }
    } catch {
      Swal.fire({ icon: "error", title: "서버 오류", text: "잠시 후 다시 시도하세요." });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex flex-col lg:flex-row bg-white">
      {/* 좌측 브랜드 */}
      <div className="relative lg:flex-1 lg:min-h-screen overflow-hidden bg-gradient-to-br from-[#0d3b24] via-[#1b5e3a] to-[#0f4a2a] px-10 py-16 lg:py-0 flex flex-col justify-center">
        <div
          className="absolute inset-0 pointer-events-none opacity-30"
          style={{
            backgroundImage:
              "radial-gradient(circle at 20% 30%, rgba(126,217,167,0.25) 0, transparent 40%), radial-gradient(circle at 80% 70%, rgba(46,139,87,0.3) 0, transparent 45%)",
          }}
        />
        <div className="relative z-10">
          <Link href="/" className="inline-flex items-center gap-2.5 mb-12 hover:opacity-80 transition">
            <img src="/momo-icon.svg" alt="" className="w-9 h-9" />
            <span className="text-white/95 text-sm font-bold tracking-widest">MOMO DISTRIBUTION</span>
          </Link>
          <h2 className="text-white text-4xl font-bold mb-4 tracking-tight">
            지금 가입하고<br />
            <span className="text-emerald-200">발주를 시작하세요</span>
          </h2>
          <p className="text-emerald-100/80 leading-relaxed max-w-md mb-8">
            이메일과 업체명만 입력하면 바로 사용 가능합니다. 가입 즉시 모모유통의 모든 품목을 검색하고 발주할 수 있습니다.
          </p>
          <ul className="space-y-2 text-emerald-100/80 text-sm">
            <li>· 가입비 · 월 사용료 없음</li>
            <li>· 안드로이드 앱 무료 제공 (APK)</li>
            <li>· 거래명세표 자동 발송 (메일 + 엑셀)</li>
          </ul>
        </div>
      </div>

      {/* 우측 가입 폼 */}
      <div className="lg:flex-1 flex items-center justify-center px-6 py-12 lg:py-16 bg-slate-50">
        <div className="w-full max-w-md">
          <div className="mb-8">
            <div className="inline-flex items-center gap-2 text-emerald-700 text-xs font-bold tracking-widest mb-3">
              <span className="w-6 h-[2px] bg-emerald-600" />
              SIGN UP
            </div>
            <h1 className="text-3xl font-bold text-slate-900 mb-2">회원가입</h1>
            <p className="text-slate-500 text-sm">
              이미 계정이 있으신가요?{" "}
              <Link href="/login" className="text-emerald-700 font-semibold hover:underline">로그인</Link>
            </p>
          </div>

          <form onSubmit={submit} className="space-y-4">
            <Field icon={<Mail size={16} />} label="이메일 *" type="email" value={form.email} onChange={set("email")} placeholder="you@company.com" autoComplete="email" autoFocus />
            <div>
              <label className="block text-[12px] font-semibold text-slate-600 mb-2 tracking-wide">비밀번호 *</label>
              <div className="relative group">
                <Lock size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-emerald-600 transition" />
                <input
                  type={showPw ? "text" : "password"}
                  value={form.password}
                  onChange={set("password")}
                  placeholder="8자 이상"
                  autoComplete="new-password"
                  className="w-full h-11 pl-11 pr-12 rounded-xl border border-slate-200 bg-white text-sm text-slate-900 placeholder-slate-400 shadow-sm focus:outline-none focus:border-emerald-500 focus:ring-4 focus:ring-emerald-500/10 transition"
                />
                <button type="button" onClick={() => setShowPw((v) => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 p-1.5 text-slate-400 hover:text-slate-700" tabIndex={-1}>
                  {showPw ? <EyeOff size={16} /> : <Eye size={16} />}
                </button>
              </div>
            </div>
            <Field icon={<Lock size={16} />} label="비밀번호 확인 *" type={showPw ? "text" : "password"} value={form.passwordConfirm} onChange={set("passwordConfirm")} placeholder="비밀번호 재입력" autoComplete="new-password" />
            <Field icon={<Building2 size={16} />} label="업체명 *" value={form.companyName} onChange={set("companyName")} placeholder="(주)거래처 또는 매장명" />
            <div className="grid grid-cols-2 gap-3">
              <Field icon={<UserIcon size={16} />} label="대표자" value={form.ceoName} onChange={set("ceoName")} placeholder="홍길동" />
              <Field icon={<Phone size={16} />} label="연락처 *" value={form.phone} onChange={set("phone")} placeholder="010-0000-0000" />
            </div>
            <Field icon={<MapPin size={16} />} label="주소 *" value={form.address} onChange={set("address")} placeholder="배송지 주소를 입력하세요" />
            <Field icon={<FileText size={16} />} label="사업자등록번호" value={form.bizNo} onChange={set("bizNo")} placeholder="000-00-00000 (선택)" />

            <button
              type="submit"
              disabled={loading}
              className="group relative w-full h-12 mt-2 rounded-xl bg-gradient-to-r from-emerald-700 to-emerald-600 text-white text-sm font-bold tracking-wide shadow-lg shadow-emerald-600/25 hover:shadow-emerald-600/40 hover:-translate-y-0.5 active:translate-y-0 transition-all disabled:opacity-60 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <span className="w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin" />
                  처리 중...
                </>
              ) : (
                <>
                  가입하기 <ArrowRight size={16} className="group-hover:translate-x-0.5 transition-transform" />
                </>
              )}
            </button>

            <p className="text-[11px] text-slate-400 text-center pt-2">
              가입하시면 <Link href="/" className="underline hover:text-slate-600">서비스 이용약관</Link>에 동의하시는 것으로 간주됩니다.
            </p>
          </form>
        </div>
      </div>
    </div>
  );
}

function Field(props: {
  icon: React.ReactNode;
  label: string;
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  type?: string;
  placeholder?: string;
  autoComplete?: string;
  autoFocus?: boolean;
}) {
  return (
    <div>
      <label className="block text-[12px] font-semibold text-slate-600 mb-2 tracking-wide">{props.label}</label>
      <div className="relative group">
        <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-emerald-600 transition">
          {props.icon}
        </span>
        <input
          type={props.type ?? "text"}
          value={props.value}
          onChange={props.onChange}
          placeholder={props.placeholder}
          autoComplete={props.autoComplete}
          autoFocus={props.autoFocus}
          className="w-full h-11 pl-11 pr-4 rounded-xl border border-slate-200 bg-white text-sm text-slate-900 placeholder-slate-400 shadow-sm focus:outline-none focus:border-emerald-500 focus:ring-4 focus:ring-emerald-500/10 transition"
        />
      </div>
    </div>
  );
}
