<template>
  <AppLayout>
    <div class="settings">
      <header class="page-header">
        <h1>Account Settings</h1>
        <p class="subtitle">Manage your account and preferences</p>
      </header>

      <div v-if="loading" class="loading">Loading...</div>

      <template v-else>
        <!-- Profile Section -->
        <section class="settings-section">
          <div class="section-header">
            <h2>Profile</h2>
          </div>
          <div class="section-content">
            <form @submit.prevent="updateProfile">
              <div class="form-group">
                <label for="email">Email Address</label>
                <input
                  id="email"
                  v-model="profile.email"
                  type="email"
                  required
                />
                <p v-if="!profile.isVerified" class="form-warning">
                  Your email is not verified.
                  <button type="button" class="link-btn" @click="resendVerification" :disabled="resendingVerification">
                    {{ resendingVerification ? 'Sending...' : 'Resend verification email' }}
                  </button>
                </p>
              </div>
              <div v-if="profileError" class="error-message">{{ profileError }}</div>
              <div v-if="profileSuccess" class="success-message">{{ profileSuccess }}</div>
              <button type="submit" class="btn btn-primary" :disabled="savingProfile">
                {{ savingProfile ? 'Saving...' : 'Save Changes' }}
              </button>
            </form>
          </div>
        </section>

        <!-- Password Section -->
        <section class="settings-section">
          <div class="section-header">
            <h2>Change Password</h2>
          </div>
          <div class="section-content">
            <form @submit.prevent="changePassword">
              <div class="form-group">
                <label for="currentPassword">Current Password</label>
                <input
                  id="currentPassword"
                  v-model="passwordForm.currentPassword"
                  type="password"
                  required
                />
              </div>
              <div class="form-group">
                <label for="newPassword">New Password</label>
                <input
                  id="newPassword"
                  v-model="passwordForm.newPassword"
                  type="password"
                  required
                  minlength="8"
                />
                <p class="form-hint">At least 8 characters</p>
              </div>
              <div class="form-group">
                <label for="confirmPassword">Confirm New Password</label>
                <input
                  id="confirmPassword"
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  required
                />
              </div>
              <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
              <div v-if="passwordSuccess" class="success-message">{{ passwordSuccess }}</div>
              <button type="submit" class="btn btn-primary" :disabled="changingPassword">
                {{ changingPassword ? 'Changing...' : 'Change Password' }}
              </button>
            </form>
          </div>
        </section>

        <!-- API Keys Section -->
        <section class="settings-section">
          <div class="section-header">
            <h2>API Keys</h2>
            <button class="btn btn-primary btn-sm" @click="showCreateKeyModal = true">
              Create Key
            </button>
          </div>
          <div class="section-content">
            <p class="section-description">Generate API keys to access TrakQR programmatically. Keys are scoped to your current workspace.</p>

            <div v-if="loadingKeys" class="loading-inline">Loading API keys...</div>

            <div v-else-if="apiKeys.length === 0" class="empty-state-inline">
              <p>No API keys yet. Create one to get started.</p>
            </div>

            <div v-else class="api-keys-list">
              <div v-for="key in apiKeys" :key="key.id" class="api-key-item">
                <div class="api-key-info">
                  <span class="api-key-name">{{ key.name }}</span>
                  <code class="api-key-prefix">{{ key.keyPrefix }}</code>
                </div>
                <div class="api-key-meta">
                  <span v-if="key.lastUsedAt" class="api-key-used">
                    Last used {{ formatDate(key.lastUsedAt) }}
                  </span>
                  <span v-else class="api-key-used">Never used</span>
                  <span v-if="key.expiresAt" :class="['api-key-expiry', { expired: isExpired(key.expiresAt) }]">
                    {{ isExpired(key.expiresAt) ? 'Expired' : `Expires ${formatDate(key.expiresAt)}` }}
                  </span>
                </div>
                <button class="btn btn-icon btn-danger-icon" @click="confirmDeleteKey(key)" title="Delete">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="3 6 5 6 21 6"/>
                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                  </svg>
                </button>
              </div>
            </div>
          </div>
        </section>

        <!-- Danger Zone -->
        <section class="settings-section danger-zone">
          <div class="section-header">
            <h2>Danger Zone</h2>
          </div>
          <div class="section-content">
            <div class="danger-item">
              <div>
                <h4>Delete Account</h4>
                <p>Permanently delete your account and all associated data. This action cannot be undone.</p>
              </div>
              <button class="btn btn-danger" @click="showDeleteModal = true">
                Delete Account
              </button>
            </div>
          </div>
        </section>
      </template>

      <!-- Create API Key Modal -->
      <div v-if="showCreateKeyModal" class="modal-overlay" @click.self="showCreateKeyModal = false">
        <div class="modal modal-sm">
          <div class="modal-header">
            <h2 class="modal-title-normal">Create API Key</h2>
            <button class="close-btn" @click="showCreateKeyModal = false">&times;</button>
          </div>
          <form @submit.prevent="createApiKey">
            <div class="modal-body">
              <div class="form-group">
                <label for="keyName">Key Name</label>
                <input
                  id="keyName"
                  v-model="newKeyName"
                  type="text"
                  required
                  placeholder="e.g., Production Server"
                />
              </div>
              <div class="form-group">
                <label for="keyExpiry">Expiration (optional)</label>
                <select id="keyExpiry" v-model="newKeyExpiry">
                  <option value="">Never expires</option>
                  <option value="30">30 days</option>
                  <option value="90">90 days</option>
                  <option value="365">1 year</option>
                </select>
              </div>
              <div v-if="createKeyError" class="error-message">{{ createKeyError }}</div>
            </div>
            <div class="modal-actions">
              <button type="button" class="btn btn-secondary" @click="showCreateKeyModal = false">Cancel</button>
              <button type="submit" class="btn btn-primary" :disabled="creatingKey">
                {{ creatingKey ? 'Creating...' : 'Create Key' }}
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Show New Key Modal -->
      <div v-if="newlyCreatedKey" class="modal-overlay">
        <div class="modal modal-sm">
          <div class="modal-header">
            <h2 class="modal-title-normal">API Key Created</h2>
          </div>
          <div class="modal-body">
            <p class="key-warning">
              Copy your API key now. You won't be able to see it again!
            </p>
            <div class="key-display">
              <code>{{ newlyCreatedKey }}</code>
              <button type="button" class="btn btn-icon" @click="copyKey" :title="keyCopied ? 'Copied!' : 'Copy'">
                <svg v-if="!keyCopied" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                </svg>
                <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
              </button>
            </div>
          </div>
          <div class="modal-actions">
            <button type="button" class="btn btn-primary" @click="newlyCreatedKey = null">Done</button>
          </div>
        </div>
      </div>

      <!-- Delete API Key Modal -->
      <div v-if="keyToDelete" class="modal-overlay" @click.self="keyToDelete = null">
        <div class="modal modal-sm">
          <div class="modal-header">
            <h2>Delete API Key?</h2>
            <button class="close-btn" @click="keyToDelete = null">&times;</button>
          </div>
          <div class="modal-body">
            <p>Are you sure you want to delete the API key "{{ keyToDelete.name }}"? Any applications using this key will stop working.</p>
            <div v-if="deleteKeyError" class="error-message">{{ deleteKeyError }}</div>
          </div>
          <div class="modal-actions">
            <button type="button" class="btn btn-secondary" @click="keyToDelete = null">Cancel</button>
            <button type="button" class="btn btn-danger" @click="deleteApiKey" :disabled="deletingKey">
              {{ deletingKey ? 'Deleting...' : 'Delete Key' }}
            </button>
          </div>
        </div>
      </div>

      <!-- Delete Account Modal -->
      <div v-if="showDeleteModal" class="modal-overlay" @click.self="showDeleteModal = false">
        <div class="modal modal-sm">
          <div class="modal-header">
            <h2>Delete Account</h2>
            <button class="close-btn" @click="showDeleteModal = false">&times;</button>
          </div>
          <form @submit.prevent="deleteAccount">
            <div class="modal-body">
              <p class="delete-warning">
                This will permanently delete your account, all workspaces, links, QR codes, and analytics data.
                This action <strong>cannot be undone</strong>.
              </p>
              <div class="form-group">
                <label for="deletePassword">Enter your password to confirm</label>
                <input
                  id="deletePassword"
                  v-model="deletePassword"
                  type="password"
                  required
                  placeholder="Your password"
                />
              </div>
              <div v-if="deleteError" class="error-message">{{ deleteError }}</div>
            </div>
            <div class="modal-actions">
              <button type="button" class="btn btn-secondary" @click="showDeleteModal = false">Cancel</button>
              <button type="submit" class="btn btn-danger" :disabled="deleting">
                {{ deleting ? 'Deleting...' : 'Delete My Account' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </AppLayout>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { authApi } from '../../api/auth.js';
import { apiKeysApi } from '../../api/apiKeys.js';
import { useAuthStore } from '../../stores/auth.js';
import { useWorkspaceStore } from '../../stores/workspace.js';
import AppLayout from '../../components/layout/AppLayout.vue';

const router = useRouter();
const authStore = useAuthStore();
const workspaceStore = useWorkspaceStore();

const loading = ref(true);
const profile = ref({ email: '', isVerified: false });

const savingProfile = ref(false);
const profileError = ref('');
const profileSuccess = ref('');

const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});
const changingPassword = ref(false);
const passwordError = ref('');
const passwordSuccess = ref('');

const showDeleteModal = ref(false);
const deletePassword = ref('');
const deleting = ref(false);
const deleteError = ref('');

// API Keys state
const apiKeys = ref([]);
const loadingKeys = ref(false);
const showCreateKeyModal = ref(false);
const newKeyName = ref('');
const newKeyExpiry = ref('');
const creatingKey = ref(false);
const createKeyError = ref('');
const newlyCreatedKey = ref(null);
const keyCopied = ref(false);
const keyToDelete = ref(null);
const deletingKey = ref(false);
const deleteKeyError = ref('');

onMounted(async () => {
  try {
    const data = await authApi.getProfile();
    profile.value = data;
    await loadApiKeys();
  } catch (err) {
    profileError.value = err.message;
  } finally {
    loading.value = false;
  }
});

watch(() => workspaceStore.currentWorkspaceId, async () => {
  if (workspaceStore.currentWorkspaceId) {
    await loadApiKeys();
  }
});

async function loadApiKeys() {
  const workspaceId = workspaceStore.currentWorkspaceId;
  if (!workspaceId) return;

  loadingKeys.value = true;
  try {
    const result = await apiKeysApi.list(workspaceId);
    apiKeys.value = result.apiKeys;
  } catch (err) {
    console.error('Failed to load API keys:', err);
  } finally {
    loadingKeys.value = false;
  }
}

async function updateProfile() {
  savingProfile.value = true;
  profileError.value = '';
  profileSuccess.value = '';

  try {
    const data = await authApi.updateProfile({ email: profile.value.email });
    profile.value = data;
    profileSuccess.value = 'Profile updated successfully';
  } catch (err) {
    profileError.value = err.message;
  } finally {
    savingProfile.value = false;
  }
}

async function changePassword() {
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    passwordError.value = 'Passwords do not match';
    return;
  }

  changingPassword.value = true;
  passwordError.value = '';
  passwordSuccess.value = '';

  try {
    await authApi.changePassword(
      passwordForm.value.currentPassword,
      passwordForm.value.newPassword
    );
    passwordSuccess.value = 'Password changed successfully';
    passwordForm.value = { currentPassword: '', newPassword: '', confirmPassword: '' };
  } catch (err) {
    passwordError.value = err.message;
  } finally {
    changingPassword.value = false;
  }
}

const resendingVerification = ref(false);

async function resendVerification() {
  resendingVerification.value = true;
  profileError.value = '';
  try {
    await authApi.resendVerification();
    profileSuccess.value = 'Verification email sent! Check your inbox.';
  } catch (err) {
    profileError.value = err.message;
  } finally {
    resendingVerification.value = false;
  }
}

async function deleteAccount() {
  deleting.value = true;
  deleteError.value = '';

  try {
    await authApi.deleteAccount(deletePassword.value);
    authStore.logout();
    router.push('/');
  } catch (err) {
    deleteError.value = err.message;
  } finally {
    deleting.value = false;
  }
}

// API Key functions
async function createApiKey() {
  const workspaceId = workspaceStore.currentWorkspaceId;
  if (!workspaceId) return;

  creatingKey.value = true;
  createKeyError.value = '';

  try {
    let expiresAt = null;
    if (newKeyExpiry.value) {
      const date = new Date();
      date.setDate(date.getDate() + parseInt(newKeyExpiry.value));
      expiresAt = date.toISOString();
    }

    const result = await apiKeysApi.create(workspaceId, newKeyName.value, expiresAt);
    newlyCreatedKey.value = result.key;
    apiKeys.value.unshift({
      id: result.id,
      name: result.name,
      keyPrefix: result.keyPrefix,
      scopes: result.scopes,
      expiresAt: result.expiresAt,
      createdAt: result.createdAt,
      isActive: true,
    });

    showCreateKeyModal.value = false;
    newKeyName.value = '';
    newKeyExpiry.value = '';
  } catch (err) {
    createKeyError.value = err.message;
  } finally {
    creatingKey.value = false;
  }
}

async function copyKey() {
  try {
    await navigator.clipboard.writeText(newlyCreatedKey.value);
    keyCopied.value = true;
    setTimeout(() => {
      keyCopied.value = false;
    }, 2000);
  } catch (err) {
    console.error('Failed to copy:', err);
  }
}

function confirmDeleteKey(key) {
  keyToDelete.value = key;
  deleteKeyError.value = '';
}

async function deleteApiKey() {
  const workspaceId = workspaceStore.currentWorkspaceId;
  if (!workspaceId || !keyToDelete.value) return;

  deletingKey.value = true;
  deleteKeyError.value = '';

  try {
    await apiKeysApi.delete(workspaceId, keyToDelete.value.id);
    apiKeys.value = apiKeys.value.filter(k => k.id !== keyToDelete.value.id);
    keyToDelete.value = null;
  } catch (err) {
    deleteKeyError.value = err.message;
  } finally {
    deletingKey.value = false;
  }
}

function formatDate(date) {
  if (!date) return '';
  return new Date(date).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}

function isExpired(date) {
  if (!date) return false;
  return new Date(date) < new Date();
}
</script>

<style scoped>
.settings {
  max-width: 800px;
  margin: 0 auto;
}

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

.page-header h1 {
  font-size: 1.75rem;
  font-weight: 600;
  margin: 0 0 0.5rem;
}

.subtitle {
  color: #6b7280;
  margin: 0;
}

.loading {
  text-align: center;
  padding: 3rem;
  color: #6b7280;
}

.settings-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 1.5rem;
  overflow: hidden;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1.25rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.section-header h2 {
  font-size: 1rem;
  font-weight: 600;
  margin: 0;
}

.badge {
  font-size: 0.75rem;
  font-weight: 500;
  padding: 0.25rem 0.5rem;
  background: #e5e7eb;
  color: #6b7280;
  border-radius: 4px;
}

.section-content {
  padding: 1.5rem;
}

.section-content.muted {
  color: #6b7280;
}

.section-content.muted p {
  margin: 0;
}

.form-group {
  margin-bottom: 1.25rem;
}

.form-group:last-of-type {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  margin-bottom: 0.5rem;
}

.form-group input {
  width: 100%;
  padding: 0.625rem 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 0.875rem;
}

.form-group input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-hint {
  font-size: 0.75rem;
  color: #6b7280;
  margin: 0.5rem 0 0;
}

.form-warning {
  font-size: 0.875rem;
  color: #d97706;
  margin: 0.5rem 0 0;
}

.link-btn {
  background: none;
  border: none;
  color: #3b82f6;
  text-decoration: underline;
  cursor: pointer;
  font-size: inherit;
}

.link-btn:hover {
  color: #2563eb;
}

/* Danger Zone */
.danger-zone .section-header {
  background: #fef2f2;
  border-bottom-color: #fecaca;
}

.danger-zone .section-header h2 {
  color: #dc2626;
}

.danger-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 2rem;
}

.danger-item h4 {
  font-size: 0.9rem;
  font-weight: 600;
  margin: 0 0 0.25rem;
}

.danger-item p {
  font-size: 0.875rem;
  color: #6b7280;
  margin: 0;
}

/* Buttons */
.btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.625rem 1rem;
  border-radius: 8px;
  font-weight: 500;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #2563eb;
}

.btn-secondary {
  background: white;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover:not(:disabled) {
  background: #f9fafb;
}

.btn-danger {
  background: #dc2626;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: #b91c1c;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Messages */
.error-message {
  background: #fee2e2;
  border: 1px solid #fecaca;
  border-radius: 8px;
  padding: 0.75rem;
  color: #dc2626;
  font-size: 0.875rem;
  margin-bottom: 1rem;
}

.success-message {
  background: #d1fae5;
  border: 1px solid #a7f3d0;
  border-radius: 8px;
  padding: 0.75rem;
  color: #065f46;
  font-size: 0.875rem;
  margin-bottom: 1rem;
}

/* Modal */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12px;
  width: 100%;
  max-width: 480px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-sm {
  max-width: 420px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.25rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h2 {
  font-size: 1.125rem;
  font-weight: 600;
  margin: 0;
  color: #dc2626;
}

.close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  font-size: 1.5rem;
  color: #6b7280;
  cursor: pointer;
  border-radius: 6px;
}

.close-btn:hover {
  background: #f3f4f6;
}

.modal-body {
  padding: 1.5rem;
}

.delete-warning {
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 8px;
  padding: 1rem;
  color: #991b1b;
  margin-bottom: 1.5rem;
  line-height: 1.5;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.75rem;
  padding: 1rem 1.5rem;
  border-top: 1px solid #e5e7eb;
}

/* API Keys */
.btn-sm {
  padding: 0.375rem 0.75rem;
  font-size: 0.8rem;
}

.section-description {
  color: #6b7280;
  font-size: 0.875rem;
  margin: 0 0 1rem;
}

.loading-inline {
  color: #6b7280;
  font-size: 0.875rem;
  padding: 1rem 0;
}

.empty-state-inline {
  color: #6b7280;
  font-size: 0.875rem;
  padding: 1rem;
  background: #f9fafb;
  border-radius: 8px;
  text-align: center;
}

.empty-state-inline p {
  margin: 0;
}

.api-keys-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.api-key-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: #f9fafb;
  border-radius: 8px;
}

.api-key-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.api-key-name {
  font-weight: 500;
  font-size: 0.9rem;
}

.api-key-prefix {
  font-family: monospace;
  font-size: 0.8rem;
  color: #6b7280;
  background: #e5e7eb;
  padding: 0.125rem 0.375rem;
  border-radius: 4px;
  width: fit-content;
}

.api-key-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 0.25rem;
  font-size: 0.75rem;
  color: #6b7280;
}

.api-key-expiry.expired {
  color: #dc2626;
}

.btn-icon {
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  background: transparent;
  border: none;
  cursor: pointer;
  color: #6b7280;
}

.btn-icon:hover {
  background: #e5e7eb;
}

.btn-danger-icon:hover {
  background: #fee2e2;
  color: #dc2626;
}

.modal-title-normal {
  color: #111827 !important;
}

.key-warning {
  background: #fef3c7;
  border: 1px solid #fcd34d;
  border-radius: 8px;
  padding: 0.75rem;
  color: #92400e;
  font-size: 0.875rem;
  margin-bottom: 1rem;
}

.key-display {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: #1f2937;
  border-radius: 8px;
  padding: 0.75rem;
}

.key-display code {
  flex: 1;
  color: #10b981;
  font-family: monospace;
  font-size: 0.8rem;
  word-break: break-all;
}

.key-display .btn-icon {
  color: #9ca3af;
  flex-shrink: 0;
}

.key-display .btn-icon:hover {
  color: white;
  background: transparent;
}

.form-group select {
  width: 100%;
  padding: 0.625rem 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 0.875rem;
  background: white;
}

.form-group select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

@media (max-width: 640px) {
  .danger-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .api-key-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .api-key-meta {
    flex-direction: row;
    align-items: center;
    gap: 1rem;
    width: 100%;
    justify-content: space-between;
  }
}
</style>
