"use client";
import React from "react";
import { Modal } from "@/app/components/ui/Modal";
import { ProfileImageEditor } from "@/app/components/ProfileImageEditor";
import { useToast } from "@/app/components/ui/ToastProvider";
import { UserAvatar } from "@/app/components/UserAvatar";

type Props = {
  open: boolean;
  onClose: () => void;
  initialProfileImageUrl?: string | null;
};

export function ProfileEditModal({ open, onClose, initialProfileImageUrl }: Props) {
  const { show } = useToast();
  const [previewUrl, setPreviewUrl] = React.useState<string | null>(initialProfileImageUrl || null);
  const [currentPassword, setCurrentPassword] = React.useState("");
  const [newPassword, setNewPassword] = React.useState("");
  const [confirmPassword, setConfirmPassword] = React.useState("");
  const [saving, setSaving] = React.useState(false);

  async function changePassword(e: React.FormEvent) {
    e.preventDefault();
    if (saving) return;
    if (!currentPassword || !newPassword || !confirmPassword) {
      show("모든 비밀번호 입력란을 채워주세요");
      return;
    }
    if (newPassword.length < 8 || newPassword.length > 100) {
      show("새 비밀번호는 8~100자여야 합니다");
      return;
    }
    if (newPassword !== confirmPassword) {
      show("새 비밀번호와 확인이 일치하지 않습니다");
      return;
    }
    try {
      setSaving(true);
      const res = await fetch("/api/me/password", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          currentPassword,
          newPassword,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        throw new Error(data?.error || "비밀번호 변경에 실패했습니다");
      }
      show("비밀번호가 변경되었습니다");
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
    } catch (e: any) {
      show(e?.message || "비밀번호 변경에 실패했습니다");
    } finally {
      setSaving(false);
    }
  }

  return (
    <Modal open={open} onClose={onClose}>
      <div className="w-[720px] max-w-[92vw]">
        <div className="p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-bold">프로필 수정</h2>
            <button
              type="button"
              onClick={onClose}
              className="px-2 py-1 text-sm text-neutral-500 hover:text-neutral-800"
              aria-label="닫기"
            >
              닫기
            </button>
          </div>

          <div className="space-y-8">
            <section>
              <h3 className="text-sm font-semibold text-neutral-700 mb-3">프로필 이미지</h3>
              <div className="rounded-md border border-neutral-200 p-3">
                {/* 원형 미리보기 */}
                <div className="flex items-center justify-center mb-3">
                  <div className="relative w-[112px] h-[112px]">
                    <div className="absolute inset-0 flex items-center justify-center">
                      <svg className="w-full h-full" viewBox="0 0 160 160" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                        <circle cx="80" cy="80" r="79" stroke="#8c8c8c" strokeWidth="2" fill="none" />
                      </svg>
                    </div>
                    <div className="absolute inset-[8px] flex items-center justify-center">
                      <UserAvatar
                        src={previewUrl || null}
                        alt="프로필 미리보기"
                        width={140}
                        height={140}
                        className="rounded-full w-full h-full object-cover"
                      />
                    </div>
                  </div>
                </div>
                {/* 업로드/제거 컨트롤 (경로 텍스트 숨김) */}
                <ProfileImageEditor
                  initialUrl={initialProfileImageUrl || null}
                  onUrlChange={(u) => setPreviewUrl(u || null)}
                  hideUrlText
                />
              </div>
            </section>

            <section>
              <h3 className="text-sm font-semibold text-neutral-700 mb-3">비밀번호 변경</h3>
              <form onSubmit={changePassword} className="rounded-md border border-neutral-200 p-3 space-y-3">
                <div className="space-y-1">
                  <label className="block text-xs font-medium text-neutral-600">현재 비밀번호</label>
                  <input
                    type="password"
                    className="w-full border border-neutral-300 rounded-md px-3 py-2 text-sm"
                    value={currentPassword}
                    onChange={(e) => setCurrentPassword(e.target.value)}
                    placeholder="현재 비밀번호"
                    autoComplete="current-password"
                  />
                </div>
                <div className="space-y-1">
                  <label className="block text-xs font-medium text-neutral-600">새 비밀번호</label>
                  <input
                    type="password"
                    className="w-full border border-neutral-300 rounded-md px-3 py-2 text-sm"
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    placeholder="새 비밀번호 (8~100자)"
                    autoComplete="new-password"
                  />
                </div>
                <div className="space-y-1">
                  <label className="block text-xs font-medium text-neutral-600">새 비밀번호 확인</label>
                  <input
                    type="password"
                    className="w-full border border-neutral-300 rounded-md px-3 py-2 text-sm"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    placeholder="새 비밀번호 확인"
                    autoComplete="new-password"
                  />
                </div>
                <div className="flex justify-end gap-2 pt-1">
                  <button
                    type="button"
                    onClick={onClose}
                    className="h-9 px-3 rounded-md border border-neutral-300 text-sm text-neutral-700 hover:bg-neutral-100"
                  >
                    닫기
                  </button>
                  <button
                    type="submit"
                    disabled={saving}
                    className="h-9 px-4 rounded-md bg-neutral-900 text-white text-sm hover:bg-neutral-800 disabled:opacity-60"
                  >
                    {saving ? "처리 중..." : "비밀번호 변경"}
                  </button>
                </div>
              </form>
            </section>
          </div>
        </div>
      </div>
    </Modal>
  );
}


