"use client";

import { useEffect, useState, FormEvent } from "react";
import { Mail, Lock, Building2, User as UserIcon, Phone, FileText, MapPin, Save } from "lucide-react";
import Swal from "sweetalert2";

interface Profile {
  USER_ID: string;
  USER_NAME: string;
  EMAIL: string;
  CELL_PHONE: string;
  TEL: string;
  ADDRESS: string;
  CEO_NAME: string;
  BIZ_NO: string;
  USER_TYPE: string;
}

export default function ProfilePage() {
  const [profile, setProfile] = useState<Profile | null>(null);
  const [pwForm, setPwForm] = useState({ current: "", next: "", confirm: "" });
  const [loading, setLoading] = useState(false);

  const load = async () => {
    const res = await fetch("/api/auth/profile");
    const j = await res.json();
    if (j.success) setProfile(j.data);
  };
  useEffect(() => { load(); }, []);

  const onSaveInfo = async (e: FormEvent) => {
    e.preventDefault();
    if (!profile) return;
    setLoading(true);
    try {
      const res = await fetch("/api/auth/profile", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          userName: profile.USER_NAME,
          email: profile.EMAIL,
          cellPhone: profile.CELL_PHONE,
          tel: profile.TEL,
          address: profile.ADDRESS,
          ceoName: profile.CEO_NAME,
          bizNo: profile.BIZ_NO,
        }),
      });
      const j = await res.json();
      if (j.success) Swal.fire({ icon: "success", title: "저장되었습니다", timer: 1200, showConfirmButton: false });
      else Swal.fire({ icon: "error", title: "저장 실패", text: j.message });
    } finally {
      setLoading(false);
    }
  };

  const onChangePassword = async (e: FormEvent) => {
    e.preventDefault();
    if (!pwForm.current || !pwForm.next) {
      Swal.fire({ icon: "warning", title: "현재 비밀번호와 새 비밀번호를 입력하세요." });
      return;
    }
    if (pwForm.next !== pwForm.confirm) {
      Swal.fire({ icon: "warning", title: "새 비밀번호 확인이 일치하지 않습니다." });
      return;
    }
    if (pwForm.next.length < 4) {
      Swal.fire({ icon: "warning", title: "비밀번호는 4자 이상이어야 합니다." });
      return;
    }
    setLoading(true);
    try {
      const res = await fetch("/api/auth/profile", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          currentPassword: pwForm.current,
          newPassword: pwForm.next,
        }),
      });
      const j = await res.json();
      if (j.success) {
        Swal.fire({ icon: "success", title: "비밀번호가 변경되었습니다.", timer: 1500, showConfirmButton: false });
        setPwForm({ current: "", next: "", confirm: "" });
      } else {
        Swal.fire({ icon: "error", title: "변경 실패", text: j.message });
      }
    } finally {
      setLoading(false);
    }
  };

  if (!profile) {
    return <div className="text-slate-400 text-center py-12">불러오는 중...</div>;
  }

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      <h2 className="text-lg font-bold text-gray-800">회원정보 수정</h2>

      {/* 기본 정보 */}
      <form onSubmit={onSaveInfo} className="bg-white border border-slate-200 rounded-xl p-6 space-y-4">
        <h3 className="font-bold text-slate-700 mb-3 border-b pb-2">기본 정보</h3>

        <div className="grid sm:grid-cols-2 gap-4">
          <Field icon={<UserIcon size={14} />} label="아이디">
            <input value={profile.USER_ID} disabled
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm bg-slate-50 text-slate-500" />
          </Field>
          <Field icon={<Building2 size={14} />} label={profile.USER_TYPE === "A" ? "이름" : "업체명/이름"}>
            <input value={profile.USER_NAME ?? ""}
              onChange={(e) => setProfile({ ...profile, USER_NAME: e.target.value })}
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm" />
          </Field>
          <Field icon={<Mail size={14} />} label="이메일">
            <input type="email" value={profile.EMAIL ?? ""}
              onChange={(e) => setProfile({ ...profile, EMAIL: e.target.value })}
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm" />
          </Field>
          <Field icon={<Phone size={14} />} label="휴대폰">
            <input value={profile.CELL_PHONE ?? ""}
              onChange={(e) => setProfile({ ...profile, CELL_PHONE: e.target.value })}
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm" />
          </Field>
          <Field icon={<Phone size={14} />} label="전화번호">
            <input value={profile.TEL ?? ""}
              onChange={(e) => setProfile({ ...profile, TEL: e.target.value })}
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm" />
          </Field>
          <Field icon={<UserIcon size={14} />} label="대표자">
            <input value={profile.CEO_NAME ?? ""}
              onChange={(e) => setProfile({ ...profile, CEO_NAME: e.target.value })}
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm" />
          </Field>
          <Field icon={<FileText size={14} />} label="사업자번호">
            <input value={profile.BIZ_NO ?? ""}
              onChange={(e) => setProfile({ ...profile, BIZ_NO: e.target.value })}
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm" />
          </Field>
          <div className="sm:col-span-2">
            <Field icon={<MapPin size={14} />} label="주소">
              <input value={profile.ADDRESS ?? ""}
                onChange={(e) => setProfile({ ...profile, ADDRESS: e.target.value })}
                className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm" />
            </Field>
          </div>
        </div>

        <div className="flex justify-end pt-2">
          <button type="submit" disabled={loading}
            className="inline-flex items-center gap-2 px-5 h-10 rounded-lg bg-emerald-700 text-white text-sm font-bold hover:bg-emerald-800 disabled:opacity-50">
            <Save size={14} /> 정보 저장
          </button>
        </div>
      </form>

      {/* 비밀번호 변경 */}
      <form onSubmit={onChangePassword} className="bg-white border border-slate-200 rounded-xl p-6 space-y-4">
        <h3 className="font-bold text-slate-700 mb-3 border-b pb-2">비밀번호 변경</h3>
        <div className="grid sm:grid-cols-3 gap-4">
          <Field icon={<Lock size={14} />} label="현재 비밀번호">
            <input type="password" value={pwForm.current}
              onChange={(e) => setPwForm({ ...pwForm, current: e.target.value })}
              autoComplete="current-password"
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm" />
          </Field>
          <Field icon={<Lock size={14} />} label="새 비밀번호">
            <input type="password" value={pwForm.next}
              onChange={(e) => setPwForm({ ...pwForm, next: e.target.value })}
              autoComplete="new-password"
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm" />
          </Field>
          <Field icon={<Lock size={14} />} label="새 비밀번호 확인">
            <input type="password" value={pwForm.confirm}
              onChange={(e) => setPwForm({ ...pwForm, confirm: e.target.value })}
              autoComplete="new-password"
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm" />
          </Field>
        </div>
        <div className="flex justify-end pt-2">
          <button type="submit" disabled={loading}
            className="inline-flex items-center gap-2 px-5 h-10 rounded-lg bg-slate-700 text-white text-sm font-bold hover:bg-slate-800 disabled:opacity-50">
            <Lock size={14} /> 비밀번호 변경
          </button>
        </div>
      </form>
    </div>
  );
}

function Field({ icon, label, children }: { icon: React.ReactNode; label: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-xs font-semibold text-slate-600 mb-1.5">{label}</label>
      <div className="relative">
        <span className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400">{icon}</span>
        {children}
      </div>
    </div>
  );
}
