<template>
  <div class="settings-panel">
    <h2>Edit: {{ site.name }}</h2>

    <div class="form-group">
      <label>Name</label>
      <input v-model="editName" type="text" class="edit-input" />
    </div>

    <div class="form-group">
      <label>URL</label>
      <input v-model="editUrl" type="url" placeholder="https://example.com" class="edit-input" />
    </div>

    <div class="form-group">
      <label>Description</label>
      <textarea v-model="editDescription" rows="3"
                placeholder="Optional description..." class="edit-input"></textarea>
    </div>

    <div class="form-group">
      <label>Theme Color</label>
      <div class="color-row">
        <input v-model="editThemeColor" type="color" class="color-picker" />
        <input v-model="editThemeColor" type="text"
               placeholder="#2563eb" class="edit-input color-text" />
      </div>
    </div>

    <div class="form-group">
      <label>Link Target</label>
      <select v-model="editTargetWindow" class="edit-input">
        <option value="_blank">Open in new tab</option>
        <option value="_self">Open in same tab</option>
      </select>
    </div>

    <div class="form-group checkbox-group">
      <label>
        <input v-model="editEnabled" type="checkbox" />
        Enabled (visible on the site)
      </label>
    </div>

    <div class="form-actions git-actions-bar" v-if="hasGit">
      <button class="git-sync-btn" @click.prevent="handleSyncGit" :disabled="syncing">
        {{ syncing ? 'Syncing...' : 'Sync Git' }}
      </button>
      <span class="save-status" v-if="lastGitMsg">{{ lastGitMsg }}</span>
    </div>

    <div class="git-divider" v-if="hasGit"></div>

    <div class="form-group git-group" v-if="hasGit">
      <label>Git Repository URL</label>
      <input v-model="editGitRepoUrl" type="url" placeholder="https://github.com/user/repo.git" class="edit-input" />
    </div>

    <div class="form-group git-group" v-if="hasGit">
      <label>Git Branch</label>
      <input v-model="editGitBranch" type="text" placeholder="main" class="edit-input" />
    </div>

    <div class="form-actions">
      <button class="delete-btn" @click.prevent="$emit('delete')">Delete</button>
      <span class="save-status" v-if="lastSaved">{{ lastSaved }}</span>
      <button class="preview-btn" @click.prevent="$emit('preview')" :disabled="!site.url">
        Preview Link
      </button>
    </div>

    <div class="form-actions save-bar">
      <div></div>
      <button class="save-btn" @click="handleSave" :disabled="!isDirty" :class="{ 'save-btn-dirty': isDirty }">
        Save
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'

const props = defineProps<{
  site: { name: string; url: string; description: string; themeColor: string; targetWindow: string; enabled: boolean; gitRepoUrl?: string; gitBranch?: string }
  lastSaved: string
  siteId?: string
}>()

const emit = defineEmits<{ delete: []; preview: []; changed: [{ name: string; url: string; description: string; themeColor: string; targetWindow: string; enabled: boolean, gitRepoUrl?: string; gitBranch?: string; id: string }] }>()

const syncing = ref(false)
const lastGitMsg = ref('')

const hasGit = computed(() => {
  return !!(props.site.gitRepoUrl || props.siteId)
})

const editName = ref(props.site.name)
const editUrl = ref(props.site.url)
const editDescription = ref(props.site.description)
const editThemeColor = ref(props.site.themeColor)
const editTargetWindow = ref(props.site.targetWindow)
const editEnabled = ref(props.site.enabled)
const editGitRepoUrl = ref(props.site.gitRepoUrl || '')
const editGitBranch = ref(props.site.gitBranch || 'main')

const isDirty = computed(() => {
  return (
    editName.value !== props.site.name ||
    editUrl.value !== props.site.url ||
    editDescription.value !== props.site.description ||
    editThemeColor.value !== props.site.themeColor ||
    editTargetWindow.value !== props.site.targetWindow ||
    editEnabled.value !== props.site.enabled ||
    editGitRepoUrl.value !== (props.site.gitRepoUrl || '') ||
    editGitBranch.value !== (props.site.gitBranch || 'main')
  )
})

watch([editName, editUrl, editDescription, editThemeColor, editTargetWindow, editEnabled, editGitRepoUrl, editGitBranch], () => {
  emit('changed', {
    name: editName.value,
    url: editUrl.value,
    description: editDescription.value,
    themeColor: editThemeColor.value,
    targetWindow: editTargetWindow.value,
    enabled: editEnabled.value,
    gitRepoUrl: editGitRepoUrl.value,
    gitBranch: editGitBranch.value,
    id: props.siteId!,
  })
})

function handleSave() {
  emit('changed', {
    name: editName.value,
    url: editUrl.value,
    description: editDescription.value,
    themeColor: editThemeColor.value,
    targetWindow: editTargetWindow.value,
    enabled: editEnabled.value,
    gitRepoUrl: editGitRepoUrl.value,
    gitBranch: editGitBranch.value,
    id: props.siteId!,
  })
}

async function handleSyncGit() {
  if (!props.site.id || syncing.value) return
  const API_BASE = window.location.origin
  syncing.value = true
  lastGitMsg.value = ''
  try {
    const res = await fetch(`${API_BASE}/api/sites/${encodeURIComponent(props.site.id)}/sync-git`, { method: 'POST', headers: { 'Content-Type': 'application/json' } })
    const data = await res.json()
    if (res.ok) {
      lastGitMsg.value = data.cloned ? 'Cloned repository' : 'Pull succeeded'
    } else {
      lastGitMsg.value = data.error || 'Sync failed'
    }
  } catch (err) {
    lastGitMsg.value = 'Sync failed'
  }
  syncing.value = false
}
</script>

<style scoped>
.settings-panel {
  flex: 1;
  min-width: 320px;
  padding: 24px;
  border: 1px solid var(--border-color);
  border-radius: 12px;
  background: var(--bg-secondary);
}

.settings-panel h2 {
  margin: 0 0 20px;
  font-size: 1.25rem;
  color: var(--text-primary);
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  font-size: 13px;
  font-weight: 600;
  color: var(--text-secondary);
  margin-bottom: 6px;
}

.edit-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid var(--border-input);
  border-radius: 6px;
  font-size: 14px;
  box-sizing: border-box;
  background: var(--bg-primary);
  color: var(--text-primary);
}

.edit-input:focus {
  outline: none;
  border-color: #2563eb;
  box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.15);
}

.edit-input::placeholder {
  color: var(--text-muted);
}

textarea.edit-input {
  resize: vertical;
  font-family: inherit;
}

.color-row {
  display: flex;
  gap: 8px;
  align-items: center;
}

.color-picker {
  width: 48px;
  height: 40px;
  padding: 2px;
  border: 1px solid var(--border-input);
  border-radius: 6px;
  cursor: pointer;
}

.color-text {
  flex: 1;
}

.checkbox-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 400;
  cursor: pointer;
  color: var(--text-primary);
}

.form-actions {
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-top: 24px;
   padding-top: 16px;
   border-top: 1px solid var(--border-color);
 }

 .delete-btn {
   padding: 8px 16px;
   background: var(--danger-bg);
   color: var(--danger-text);
   border: none;
   border-radius: 6px;
   font-size: 14px;
   cursor: pointer;
 }

 .delete-btn:hover {
   background: var(--danger-hover);
 }

 .save-status {
   font-size: 12px;
   color: var(--text-muted);
 }

.preview-btn {
 padding: 8px 16px;
 background: #2563eb;
 color: white;
 border: none;
 border-radius: 6px;
 font-size: 14px;
 cursor: pointer;
}

.preview-btn:hover:not(:disabled) {
  background: #1d4ed8;
}

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

.save-bar {
  margin-top: 8px;
  padding-top: 12px;
  border-top: none;
}

.save-btn {
  padding: 8px 32px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  background: var(--border-color);
  color: var(--text-muted);
}

.save-btn:disabled {
  cursor: not-allowed;
}

.save-btn-dirty {
  background: #2563eb;
  color: white;
}

.save-btn-dirty:hover {
  background: #1d4ed8;
}

.git-divider {
  border: none;
  border-top: 1px dashed var(--border-color);
  margin: 16px 0;
}

.git-group {
  margin-top: 8px;
}

.git-actions-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 4px;
}

.git-sync-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  background: #7c3aed;
  color: white;
}

.git-sync-btn:hover:not(:disabled) {
  background: #6d28d9;
}

.git-sync-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
