<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { KsTextField, KsSelect, KsButton } from '../../../shared/ui/components'
import type { UiSelectOption } from '../../../shared/ui/adapter/contracts'
import type { Identity, IdentityFormData, RegisterIdentityRequest } from '../types/identitySchema'
import { identityFormSchema } from '../types/identitySchema'
import { useIdentityApi } from '../composables/useIdentityApi'

// State
const showForm = ref(false)
const loading = ref(false)
const errorMessage = ref<string | null>(null)
const successMessage = ref<string | null>(null)
const formErrors = ref<Record<string, string>>({})
const searchQuery = ref('')
const filterState = ref('ALL')

const formData = reactive<IdentityFormData>({
  email: '',
  displayName: '',
})

// Mock data (replace with API)
const identities = ref<Identity[]>([
  {
    id: '1',
    email: 'admin@example.com',
    displayName: 'Admin User',
    state: 'ACTIVE',
    mfaRequired: true,
    createdAt: '2026-08-17T10:00:00Z',
    updatedAt: '2026-08-17T10:00:00Z',
  },
  {
    id: '2',
    email: 'trader@example.com',
    displayName: 'Trader',
    state: 'REQUIRES_MFA_SETUP',
    mfaRequired: true,
    createdAt: '2026-08-17T11:00:00Z',
    updatedAt: '2026-08-17T11:00:00Z',
  },
])

const { registerIdentity, error } = useIdentityApi()

const stateOptions: UiSelectOption[] = [
  { label: '전체', value: 'ALL' },
  { label: '활성', value: 'ACTIVE' },
  { label: 'MFA 설정 필요', value: 'REQUIRES_MFA_SETUP' },
  { label: 'MFA 설정 완료', value: 'MFA_CONFIGURED' },
]

// Computed
const filtered = computed(() =>
  identities.value.filter((i) => {
    const matchesSearch = i.email.includes(searchQuery.value) || i.displayName.includes(searchQuery.value)
    const matchesState = filterState.value === 'ALL' || i.state === filterState.value
    return matchesSearch && matchesState
  })
)

// Methods
const validateForm = () => {
  formErrors.value = {}
  const result = identityFormSchema.safeParse(formData)
  if (!result.success) {
    result.error.issues.forEach((issue) => {
      const field = String(issue.path[0])
      formErrors.value[field] = issue.message
    })
  }
  return result.success
}

const handleSubmit = async () => {
  if (!validateForm()) return
  loading.value = true
  errorMessage.value = null
  successMessage.value = null

  const request: RegisterIdentityRequest = {
    email: formData.email,
    displayName: formData.displayName,
  }

  const response = await registerIdentity(request)
  if (response) {
    identities.value.unshift({
      id: response.id,
      email: response.email,
      displayName: formData.displayName,
      state: response.state,
      mfaRequired: false,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    })
    successMessage.value = `${formData.email} 생성 완료`
    formData.email = ''
    formData.displayName = ''
    showForm.value = false
  } else {
    errorMessage.value = error.value || '생성 실패'
  }
  loading.value = false
}

const handleDelete = (id: string) => {
  if (confirm('정말 삭제하시겠습니까?')) {
    identities.value = identities.value.filter((i) => i.id !== id)
  }
}
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1>항등성 관리</h1>
      <p>사용자 항등성을 생성하고 관리합니다</p>
    </div>

    <!-- Search & Filter -->
    <div class="search-bar">
      <KsTextField
        v-model="searchQuery"
        label="검색"
        placeholder="이메일 또는 이름..."
        clearable
      />
      <KsSelect
        v-model="filterState"
        label="상태"
        :options="stateOptions"
      />
      <KsButton @click="showForm = true">신규 생성</KsButton>
    </div>

    <!-- Message -->
    <div v-if="successMessage" class="message message-success">
      {{ successMessage }}
    </div>
    <div v-if="errorMessage" class="message message-error">
      {{ errorMessage }}
    </div>

    <!-- Form Modal -->
    <div v-if="showForm" class="modal-overlay">
      <div class="modal">
        <h2>신규 항등성</h2>
        <KsTextField
          v-model="formData.email"
          label="이메일"
          type="email"
          :error="formErrors.email"
          placeholder="user@example.com"
        />
        <KsTextField
          v-model="formData.displayName"
          label="표시명"
          :error="formErrors.displayName"
          placeholder="사용자 이름"
        />
        <div class="modal-actions">
          <KsButton @click="showForm = false">취소</KsButton>
          <KsButton @click="handleSubmit" :loading="loading">생성</KsButton>
        </div>
      </div>
    </div>

    <!-- List -->
    <div class="list-container">
      <table class="identity-table">
        <thead>
          <tr>
            <th>이메일</th>
            <th>표시명</th>
            <th>상태</th>
            <th>MFA</th>
            <th>생성일</th>
            <th>작업</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="identity in filtered" :key="identity.id">
            <td><code>{{ identity.email }}</code></td>
            <td>{{ identity.displayName }}</td>
            <td><span class="badge" :class="`badge-${identity.state.toLowerCase()}`">{{ identity.state }}</span></td>
            <td>{{ identity.mfaRequired ? '필수' : '선택' }}</td>
            <td>{{ new Date(identity.createdAt).toLocaleDateString('ko-KR') }}</td>
            <td>
              <KsButton size="sm" @click="handleDelete(identity.id)">삭제</KsButton>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<style scoped lang="css">
.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.page-header {
  margin-bottom: 2rem;
}

.page-header h1 {
  margin: 0 0 0.5rem 0;
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--ks-color-text-primary);
}

.page-header p {
  margin: 0;
  font-size: 0.95rem;
  color: var(--ks-color-text-secondary);
}

.search-bar {
  display: grid;
  grid-template-columns: 1fr 200px auto;
  gap: 1rem;
  margin-bottom: 2rem;
  align-items: flex-end;
}

.message {
  padding: 1rem;
  border-radius: 6px;
  margin-bottom: 1.5rem;
  font-size: 0.95rem;
}

.message-success {
  background: #dff0d8;
  color: #3c763d;
  border: 1px solid #d6e9c6;
}

.message-error {
  background: #f2dede;
  color: #a94442;
  border: 1px solid #ebccd1;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  max-width: 500px;
  width: 90%;
  padding: 2rem;
  max-height: 90vh;
  overflow-y: auto;
}

.modal h2 {
  margin: 0 0 1.5rem 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.modal :deep(input) {
  margin-bottom: 1.5rem;
}

.modal-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 2rem;
}

.list-container {
  overflow-x: auto;
}

.identity-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.95rem;
}

.identity-table thead {
  background: #f9fafb;
  border-bottom: 2px solid #e5e7eb;
}

.identity-table th {
  padding: 0.75rem 1rem;
  text-align: left;
  font-weight: 600;
  color: var(--ks-color-text-primary);
}

.identity-table td {
  padding: 0.75rem 1rem;
  border-bottom: 1px solid #e5e7eb;
  color: var(--ks-color-text-primary);
}

.identity-table tbody tr:hover {
  background: #f9fafb;
}

.identity-table code {
  background: #f3f4f6;
  padding: 0.25rem 0.5rem;
  border-radius: 3px;
  font-family: monospace;
  font-size: 0.85rem;
}

.badge {
  display: inline-block;
  padding: 0.35rem 0.7rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.badge-active {
  background: #d1fae5;
  color: #065f46;
}

.badge-requires_mfa_setup {
  background: #fed7aa;
  color: #b45309;
}

.badge-mfa_configured {
  background: #bfdbfe;
  color: #1e40af;
}

.badge-inactive {
  background: #e5e7eb;
  color: #374151;
}
</style>
