import { useState } from 'react';
import { changePasswordApi, updateUserApi, type UserListItem, type OrgItem, type RoleWithPermissions } from '@common/services/authApi';
import { statusLabels } from '../adminConstants';
import { formatDate } from '../UsersPanel';

interface UserDetailModalProps {
  user: UserListItem;
  allRoles: RoleWithPermissions[];
  allOrgs: OrgItem[];
  onClose: () => void;
  onUpdated: () => void;
}

export function UserDetailModal({ user, allOrgs, onClose, onUpdated }: UserDetailModalProps) {
  const [name, setName] = useState(user.name);
  const [rank, setRank] = useState(user.rank || '');
  const [orgSn, setOrgSn] = useState<number | ''>(user.orgSn ?? '');
  const [saving, setSaving] = useState(false);
  const [newPassword, setNewPassword] = useState('');
  const [resetPwLoading, setResetPwLoading] = useState(false);
  const [resetPwDone, setResetPwDone] = useState(false);
  const [unlockLoading, setUnlockLoading] = useState(false);
  const [message, setMessage] = useState<{ text: string; type: 'success' | 'error' } | null>(null);

  const handleSaveInfo = async () => {
    setSaving(true);
    setMessage(null);
    try {
      await updateUserApi(user.id, {
        name: name.trim(),
        rank: rank.trim() || undefined,
        orgSn: orgSn !== '' ? orgSn : null,
      });
      setMessage({ text: '사용자 정보가 수정되었습니다.', type: 'success' });
      onUpdated();
    } catch {
      setMessage({ text: '사용자 정보 수정에 실패했습니다.', type: 'error' });
    } finally {
      setSaving(false);
    }
  };

  const handleResetPassword = async () => {
    if (!newPassword.trim()) {
      setMessage({ text: '새 비밀번호를 입력하세요.', type: 'error' });
      return;
    }
    setResetPwLoading(true);
    setMessage(null);
    try {
      await changePasswordApi(user.id, newPassword);
      setMessage({ text: '비밀번호가 초기화되었습니다.', type: 'success' });
      setResetPwDone(true);
      setNewPassword('');
    } catch {
      setMessage({ text: '비밀번호 초기화에 실패했습니다.', type: 'error' });
    } finally {
      setResetPwLoading(false);
    }
  };

  const handleUnlock = async () => {
    setUnlockLoading(true);
    setMessage(null);
    try {
      await updateUserApi(user.id, { status: 'ACTIVE' });
      setMessage({ text: '계정 잠금이 해제되었습니다.', type: 'success' });
      onUpdated();
    } catch {
      setMessage({ text: '잠금 해제에 실패했습니다.', type: 'error' });
    } finally {
      setUnlockLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
      <div className="bg-bg-surface border border-stroke rounded-lg shadow-lg w-[480px] max-h-[90vh] flex flex-col">
        {/* 헤더 */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-stroke">
          <div>
            <h2 className="text-body-2 font-bold text-fg font-korean">사용자 정보</h2>
            <p className="text-caption text-fg-disabled font-mono mt-0.5">{user.account}</p>
          </div>
          <button onClick={onClose} className="text-fg-disabled hover:text-fg transition-colors">
            <svg
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2.5"
            >
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-4 space-y-5">
          {/* 기본 정보 수정 */}
          <div>
            <h3 className="text-label-2 font-semibold text-fg-sub font-korean mb-3">
              기본 정보 수정
            </h3>
            <div className="space-y-3">
              <div>
                <label className="block text-caption text-fg-disabled font-korean mb-1">
                  사용자명
                </label>
                <input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  className="w-full px-3 py-1.5 text-caption bg-bg-elevated border border-stroke rounded-md text-fg focus:border-color-accent focus:outline-none font-korean"
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-caption text-fg-disabled font-korean mb-1">
                    직급
                  </label>
                  <input
                    type="text"
                    value={rank}
                    onChange={(e) => setRank(e.target.value)}
                    placeholder="예: 팀장"
                    className="w-full px-3 py-1.5 text-caption bg-bg-elevated border border-stroke rounded-md text-fg placeholder-fg-disabled focus:border-color-accent focus:outline-none font-korean"
                  />
                </div>
                <div>
                  <label className="block text-caption text-fg-disabled font-korean mb-1">
                    소속
                  </label>
                  <select
                    value={orgSn}
                    onChange={(e) => setOrgSn(e.target.value !== '' ? Number(e.target.value) : '')}
                    className="w-full px-3 py-1.5 text-caption bg-bg-elevated border border-stroke rounded-md text-fg focus:border-color-accent focus:outline-none font-korean"
                  >
                    <option value="">소속 없음</option>
                    {allOrgs.map((org) => (
                      <option key={org.orgSn} value={org.orgSn}>
                        {org.orgNm}
                        {org.orgAbbrNm ? ` (${org.orgAbbrNm})` : ''}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              <button
                onClick={handleSaveInfo}
                disabled={saving || !name.trim()}
                className="px-4 py-1.5 text-label-2 font-semibold rounded-md bg-color-accent text-bg-0 hover:shadow-[0_0_12px_rgba(6,182,212,0.3)] transition-all disabled:opacity-50 font-korean"
              >
                {saving ? '저장 중...' : '정보 저장'}
              </button>
            </div>
          </div>

          {/* 구분선 */}
          <div className="border-t border-stroke" />

          {/* 비밀번호 초기화 */}
          <div>
            <h3 className="text-label-2 font-semibold text-fg-sub font-korean mb-3">
              비밀번호 초기화
            </h3>
            <div className="flex items-end gap-2">
              <div className="flex-1">
                <label className="block text-caption text-fg-disabled font-korean mb-1">
                  새 비밀번호
                </label>
                <input
                  type="password"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  placeholder="새 비밀번호 입력"
                  className="w-full px-3 py-1.5 text-caption bg-bg-elevated border border-stroke rounded-md text-fg placeholder-fg-disabled focus:border-color-accent focus:outline-none font-mono"
                />
              </div>
              <button
                onClick={handleResetPassword}
                disabled={resetPwLoading || !newPassword.trim()}
                className="px-4 py-1.5 text-label-2 font-semibold rounded-md border border-color-caution text-color-caution hover:bg-[rgba(234,179,8,0.12)] transition-all disabled:opacity-50 font-korean flex-shrink-0"
              >
                {resetPwLoading ? '초기화 중...' : resetPwDone ? '초기화 완료' : '비밀번호 초기화'}
              </button>
              <button
                onClick={handleUnlock}
                disabled={unlockLoading || user.status !== 'LOCKED'}
                className="px-4 py-1.5 text-label-2 font-semibold rounded-md border border-color-success text-color-success hover:bg-[rgba(34,197,94,0.12)] transition-all disabled:opacity-50 font-korean flex-shrink-0"
                title={user.status !== 'LOCKED' ? '잠금 상태가 아닙니다' : ''}
              >
                {unlockLoading ? '해제 중...' : '패스워드잠금해제'}
              </button>
            </div>
            <p className="text-caption text-fg-disabled font-korean mt-1.5">
              초기화 후 사용자에게 새 비밀번호를 전달하세요.
            </p>
          </div>

          {/* 구분선 */}
          <div className="border-t border-stroke" />

          {/* 계정 잠금 해제 */}
          <div>
            <h3 className="text-label-2 font-semibold text-fg-sub font-korean mb-2">계정 상태</h3>
            <div className="flex items-center justify-between bg-bg-elevated border border-stroke rounded-md px-4 py-3">
              <div>
                <div className="flex items-center gap-2">
                  <span
                    className={`inline-flex items-center gap-1.5 text-label-2 font-semibold font-korean ${(statusLabels[user.status] || statusLabels.INACTIVE).color}`}
                  >
                    <span
                      className={`w-1.5 h-1.5 rounded-full ${(statusLabels[user.status] || statusLabels.INACTIVE).dot}`}
                    />
                    {(statusLabels[user.status] || statusLabels.INACTIVE).label}
                  </span>
                  {user.failCount > 0 && (
                    <span className="text-caption text-color-danger font-korean">
                      (로그인 실패 {user.failCount}회)
                    </span>
                  )}
                </div>
                {user.status === 'LOCKED' && (
                  <p className="text-caption text-fg-disabled font-korean mt-1">
                    비밀번호 5회 이상 오류로 잠금 처리됨
                  </p>
                )}
              </div>
              {user.status === 'LOCKED' && (
                <button
                  onClick={handleUnlock}
                  disabled={unlockLoading}
                  className="px-4 py-1.5 text-label-2 font-semibold rounded-md border border-color-success text-color-success hover:bg-[rgba(34,197,94,0.12)] transition-all disabled:opacity-50 font-korean flex-shrink-0"
                >
                  {unlockLoading ? '해제 중...' : '잠금 해제'}
                </button>
              )}
            </div>
          </div>

          {/* 기타 정보 (읽기 전용) */}
          <div>
            <h3 className="text-label-2 font-semibold text-fg-sub font-korean mb-2">기타 정보</h3>
            <div className="grid grid-cols-2 gap-2 text-caption font-korean">
              <div className="bg-bg-elevated border border-stroke rounded px-3 py-2">
                <span className="text-fg-disabled">이메일: </span>
                <span className="text-fg-sub font-mono">{user.email || '-'}</span>
              </div>
              <div className="bg-bg-elevated border border-stroke rounded px-3 py-2">
                <span className="text-fg-disabled">OAuth: </span>
                <span className="text-fg-sub">{user.oauthProvider || '-'}</span>
              </div>
              <div className="bg-bg-elevated border border-stroke rounded px-3 py-2">
                <span className="text-fg-disabled">최종 로그인: </span>
                <span className="text-fg-sub">
                  {user.lastLogin ? formatDate(user.lastLogin) : '-'}
                </span>
              </div>
              <div className="bg-bg-elevated border border-stroke rounded px-3 py-2">
                <span className="text-fg-disabled">등록일: </span>
                <span className="text-fg-sub">{formatDate(user.regDtm)}</span>
              </div>
            </div>
          </div>

          {/* 메시지 */}
          {message && (
            <div
              className={`px-3 py-2 text-label-2 rounded-md font-korean ${
                message.type === 'success'
                  ? 'text-color-success bg-[rgba(34,197,94,0.08)] border border-[rgba(34,197,94,0.3)]'
                  : 'text-color-danger bg-[rgba(239,68,68,0.08)] border border-[rgba(239,68,68,0.2)]'
              }`}
            >
              {message.text}
            </div>
          )}
        </div>

        {/* 푸터 */}
        <div className="flex items-center justify-end px-6 py-3 border-t border-stroke">
          <button
            onClick={onClose}
            className="px-4 py-2 text-caption border border-stroke text-fg-sub rounded-md hover:bg-[rgba(6,182,212,0.08)] transition-all font-korean"
          >
            닫기
          </button>
        </div>
      </div>
    </div>
  );
}
