import { useState } from 'react';
import { createUserApi, type RoleWithPermissions, type OrgItem } from '@common/services/authApi';
import { getRoleColor } from '../adminConstants';

interface RegisterModalProps {
  allRoles: RoleWithPermissions[];
  allOrgs: OrgItem[];
  onClose: () => void;
  onSuccess: () => void;
}

export function RegisterModal({ allRoles, allOrgs, onClose, onSuccess }: RegisterModalProps) {
  const [account, setAccount] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');
  const [rank, setRank] = useState('');
  const [orgSn, setOrgSn] = useState<number | ''>(() => {
    const defaultOrg = allOrgs.find((o) => o.orgNm === '기동방제과');
    return defaultOrg ? defaultOrg.orgSn : '';
  });
  const [email, setEmail] = useState('');
  const [roleSns, setRoleSns] = useState<number[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const toggleRole = (sn: number) => {
    setRoleSns((prev) => (prev.includes(sn) ? prev.filter((s) => s !== sn) : [...prev, sn]));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!account.trim() || !password.trim() || !name.trim()) {
      setError('계정, 비밀번호, 사용자명은 필수 항목입니다.');
      return;
    }
    setSubmitting(true);
    setError(null);
    try {
      await createUserApi({
        account: account.trim(),
        password,
        name: name.trim(),
        rank: rank.trim() || undefined,
        orgSn: orgSn !== '' ? orgSn : undefined,
        roleSns: roleSns.length > 0 ? roleSns : undefined,
      });
      onSuccess();
      onClose();
    } catch (err) {
      setError('사용자 등록에 실패했습니다.');
      console.error('사용자 등록 실패:', err);
    } finally {
      setSubmitting(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">
          <h2 className="text-body-2 font-bold text-fg font-korean">사용자 등록</h2>
          <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>

        {/* 폼 */}
        <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto">
          <div className="px-6 py-4 space-y-4">
            {/* 계정 */}
            <div>
              <label className="block text-label-2 font-semibold text-fg-sub font-korean mb-1.5">
                계정 <span className="text-color-danger">*</span>
              </label>
              <input
                type="text"
                value={account}
                onChange={(e) => setAccount(e.target.value)}
                placeholder="로그인 계정 ID"
                className="w-full px-3 py-2 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>

            {/* 비밀번호 */}
            <div>
              <label className="block text-label-2 font-semibold text-fg-sub font-korean mb-1.5">
                비밀번호 <span className="text-color-danger">*</span>
              </label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="초기 비밀번호"
                className="w-full px-3 py-2 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>

            {/* 사용자명 */}
            <div>
              <label className="block text-label-2 font-semibold text-fg-sub font-korean mb-1.5">
                사용자명 <span className="text-color-danger">*</span>
              </label>
              <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="실명"
                className="w-full px-3 py-2 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-label-2 font-semibold text-fg-sub font-korean mb-1.5">
                직급
              </label>
              <input
                type="text"
                value={rank}
                onChange={(e) => setRank(e.target.value)}
                placeholder="예: 팀장, 주임 등"
                className="w-full px-3 py-2 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-label-2 font-semibold text-fg-sub font-korean mb-1.5">
                소속
              </label>
              <select
                value={orgSn}
                onChange={(e) => setOrgSn(e.target.value !== '' ? Number(e.target.value) : '')}
                className="w-full px-3 py-2 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>
              <label className="block text-label-2 font-semibold text-fg-sub font-korean mb-1.5">
                이메일
              </label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="이메일 주소"
                className="w-full px-3 py-2 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>

            {/* 역할 */}
            <div>
              <label className="block text-label-2 font-semibold text-fg-sub font-korean mb-1.5">
                역할
              </label>
              <div className="bg-bg-elevated border border-stroke rounded-md p-2 space-y-1 max-h-[120px] overflow-y-auto">
                {allRoles.length === 0 ? (
                  <p className="text-caption text-fg-disabled font-korean px-1 py-1">역할 없음</p>
                ) : (
                  allRoles.map((role, idx) => {
                    const color = getRoleColor(role.code, idx);
                    return (
                      <label
                        key={role.sn}
                        className="flex items-center gap-2 px-2 py-1.5 hover:bg-[rgba(6,182,212,0.08)] rounded cursor-pointer"
                      >
                        <input
                          type="checkbox"
                          checked={roleSns.includes(role.sn)}
                          onChange={() => toggleRole(role.sn)}
                          style={{ accentColor: color }}
                        />
                        <span className="text-caption font-korean" style={{ color }}>
                          {role.name}
                        </span>
                        <span className="text-caption text-fg-disabled font-mono">{role.code}</span>
                      </label>
                    );
                  })
                )}
              </div>
            </div>

            {/* 에러 메시지 */}
            {error && <p className="text-label-2 text-color-danger font-korean">{error}</p>}
          </div>

          {/* 푸터 */}
          <div className="flex items-center justify-end gap-2 px-6 py-4 border-t border-stroke">
            <button
              type="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>
            <button
              type="submit"
              disabled={submitting}
              className="px-4 py-2 text-caption 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"
            >
              {submitting ? '등록 중...' : '등록'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
