<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Card from 'primevue/card'
import InputText from 'primevue/inputtext'
import Password from 'primevue/password'
import Button from 'primevue/button'
import Message from 'primevue/message'

const props = defineProps<{
  needsConfirmation: boolean
  errorMessage?: string
}>()

const emit = defineEmits<{
  authenticate: [password: string, confirmPassword?: string, newPassword?: string, confirmNewPassword?: string]
}>()

const password = ref('')
const confirmPassword = ref('')
const newPassword = ref('')
const confirmNewPassword = ref('')
const isLoading = ref(false)
const isChangingPassword = ref(false)
const passwordInput = ref<InstanceType<typeof Password> | null>(null)

const canSubmit = computed(() => {
  if (!password.value || isLoading.value) return false
  if (props.needsConfirmation && password.value !== confirmPassword.value) return false
  if (isChangingPassword.value) {
    if (!newPassword.value || !confirmNewPassword.value) return false
    if (newPassword.value !== confirmNewPassword.value) return false
  }
  return true
})

const handleSubmit = () => {
  if (!canSubmit.value) return

  // Prevent double-submit
  if (isLoading.value) return

  isLoading.value = true

  if (props.needsConfirmation) {
    emit('authenticate', password.value, confirmPassword.value)
  } else if (isChangingPassword.value) {
    emit('authenticate', password.value, undefined, newPassword.value, confirmNewPassword.value)
  } else {
    emit('authenticate', password.value)
  }

  // Reset loading state after a timeout (parent will handle actual auth)
  setTimeout(() => {
    isLoading.value = false
  }, 5000)
}

const handleKeypress = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && canSubmit.value) {
    event.preventDefault() // Prevent form submission if this is in a form
    handleSubmit()
  }
}

const togglePasswordChange = () => {
  isChangingPassword.value = !isChangingPassword.value
  newPassword.value = ''
  confirmNewPassword.value = ''
}

onMounted(() => {
  // Focus on the password input when component mounts
  if (passwordInput.value?.$el) {
    const inputElement = passwordInput.value.$el.querySelector('input') as HTMLInputElement
    if (inputElement) {
      inputElement.focus()
    }
  }
})
</script>

<template>
  <div class="login-screen">
    <div class="login-container">
      <Card class="login-card">
        <template #title>
          <div class="login-title">
            <i class="pi pi-lock" style="font-size: 2rem; margin-bottom: 0.5rem;"></i>
            <h2>{{ needsConfirmation ? 'Welcome' : 'Authentication' }}</h2>
          </div>
        </template>
        <template #content>
          <div class="login-content">
            <p v-if="needsConfirmation" class="welcome-message">
              This is your first time connecting. Please create a password to secure your workspace.
            </p>
            <p v-else-if="isChangingPassword" class="welcome-message">
              Enter your current password and choose a new one.
            </p>
            <p v-else class="welcome-message">
              Enter your password to connect.
            </p>

            <Message v-if="errorMessage" severity="error" :closable="false">
              {{ errorMessage }}
            </Message>

            <div class="form-field">
              <label for="password">{{ isChangingPassword ? 'Current Password' : 'Password' }}</label>
              <Password
                ref="passwordInput"
                id="password"
                v-model="password"
                :feedback="needsConfirmation"
                toggleMask
                placeholder="Enter password"
                class="password-input"
                @keypress="handleKeypress"
                :disabled="isLoading"
                autocomplete="current-password"
              />
            </div>

            <div v-if="needsConfirmation" class="form-field">
              <label for="confirm-password">Confirm Password</label>
              <Password
                id="confirm-password"
                v-model="confirmPassword"
                :feedback="false"
                toggleMask
                placeholder="Confirm password"
                class="password-input"
                @keypress="handleKeypress"
                :disabled="isLoading"
                autocomplete="new-password"
              />
              <small v-if="confirmPassword && password !== confirmPassword" class="p-error">
                Passwords do not match
              </small>
            </div>

            <!-- Password change fields -->
            <div v-if="isChangingPassword" class="password-change-section">
              <div class="form-field">
                <label for="new-password">New Password</label>
                <Password
                  id="new-password"
                  v-model="newPassword"
                  :feedback="true"
                  toggleMask
                  placeholder="Enter new password"
                  class="password-input"
                  @keypress="handleKeypress"
                  :disabled="isLoading"
                  autocomplete="new-password"
                />
              </div>

              <div class="form-field">
                <label for="confirm-new-password">Confirm New Password</label>
                <Password
                  id="confirm-new-password"
                  v-model="confirmNewPassword"
                  :feedback="false"
                  toggleMask
                  placeholder="Confirm new password"
                  class="password-input"
                  @keypress="handleKeypress"
                  :disabled="isLoading"
                  autocomplete="new-password"
                />
                <small v-if="confirmNewPassword && newPassword !== confirmNewPassword" class="p-error">
                  Passwords do not match
                </small>
              </div>
            </div>

            <Button
              :label="needsConfirmation ? 'Create & Connect' : isChangingPassword ? 'Change Password & Connect' : 'Connect'"
              :icon="isChangingPassword ? 'pi pi-key' : 'pi pi-sign-in'"
              @click="handleSubmit"
              :disabled="!canSubmit"
              :loading="isLoading"
              class="connect-button"
            />

            <!-- Toggle password change link -->
            <div v-if="!needsConfirmation" class="change-password-link">
              <a @click="togglePasswordChange" href="#">
                {{ isChangingPassword ? 'Cancel password change' : 'Change password' }}
              </a>
            </div>
          </div>
        </template>
      </Card>
    </div>
  </div>
</template>

<style scoped>
.login-screen {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, var(--p-surface-0) 0%, var(--p-surface-100) 100%);
}

.login-container {
  width: 100%;
  max-width: 450px;
  padding: 2rem;
}

.login-card {
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.login-title {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  color: var(--p-primary-color);
}

.login-title h2 {
  margin: 0;
  font-size: 1.75rem;
  font-weight: 600;
}

.login-content {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.welcome-message {
  text-align: center;
  color: var(--p-text-secondary-color);
  margin: 0;
  line-height: 1.6;
}

.form-field {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-field label {
  font-weight: 600;
  color: var(--p-text-color);
}

.password-input {
  width: 100%;
}

.password-input :deep(.p-inputtext) {
  width: 100%;
}

.connect-button {
  width: 100%;
  padding: 0.75rem;
  font-size: 1.1rem;
  margin-top: 0.5rem;
}

.p-error {
  color: var(--p-red-500);
  font-size: 0.875rem;
}

.password-change-section {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  padding-top: 0.5rem;
  border-top: 1px solid var(--p-surface-border);
  margin-top: 0.5rem;
}

.change-password-link {
  text-align: center;
  margin-top: -0.5rem;
}

.change-password-link a {
  color: var(--p-primary-color);
  text-decoration: none;
  font-size: 0.9rem;
  cursor: pointer;
  transition: opacity 0.2s;
}

.change-password-link a:hover {
  opacity: 0.8;
  text-decoration: underline;
}
</style>
