<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { isParentAuthenticated } from '../../stores/auth'
import ChildDetailCard from './ChildDetailCard.vue'
import ChildTaskList from '../task/ChildTaskList.vue'
import ChildRewardList from '../reward/ChildRewardList.vue'
import { eventBus } from '@/common/eventBus'
import type {
  Task,
  Child,
  Event,
  Reward,
  RewardStatus,
  ChildTaskTriggeredEventPayload,
  ChildRewardTriggeredEventPayload,
  ChildRewardRequestEventPayload,
  ChildTasksSetEventPayload,
  ChildRewardsSetEventPayload,
  ChildModifiedEventPayload,
  TaskModifiedEventPayload,
  RewardModifiedEventPayload,
} from '@/common/models'

const route = useRoute()
const router = useRouter()

const child = ref<Child | null>(null)
const tasks = ref<string[]>([])
const rewards = ref<string[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const showConfirm = ref(false)
const selectedTask = ref<Task | null>(null)
const showRewardConfirm = ref(false)
const selectedReward = ref<Reward | null>(null)
const childRewardListRef = ref()
const childChoreListRef = ref()
const childHabitListRef = ref()
const showPendingRewardDialog = ref(false)

function handleTaskTriggered(event: Event) {
  const payload = event.payload as ChildTaskTriggeredEventPayload
  if (child.value && payload.child_id == child.value.id) {
    child.value.points = payload.points
  }
}

function handleRewardTriggered(event: Event) {
  const payload = event.payload as ChildRewardTriggeredEventPayload
  if (child.value && payload.child_id == child.value.id) {
    child.value.points = payload.points
    childRewardListRef.value?.refresh()
  }
}

function handleChildTaskSet(event: Event) {
  const payload = event.payload as ChildTasksSetEventPayload
  if (child.value && payload.child_id == child.value.id) {
    tasks.value = payload.task_ids
  }
}

function handleChildRewardSet(event: Event) {
  const payload = event.payload as ChildRewardsSetEventPayload
  if (child.value && payload.child_id == child.value.id) {
    rewards.value = payload.reward_ids
    childRewardListRef.value?.refresh()
  }
}

function handleRewardRequest(event: Event) {
  const payload = event.payload as ChildRewardRequestEventPayload
  const childId = payload.child_id
  const rewardId = payload.reward_id
  if (child.value && childId == child.value.id) {
    if (rewards.value.find((r) => r === rewardId)) {
      childRewardListRef.value?.refresh()
    }
  }
}

function handleTaskModified(event: Event) {
  const payload = event.payload as TaskModifiedEventPayload
  if (child.value) {
    const task_id = payload.task_id
    if (tasks.value.includes(task_id)) {
      try {
        switch (payload.operation) {
          case 'DELETE':
            // Remove the task from the list
            tasks.value = tasks.value.filter((t) => t !== task_id)
            return // No need to refetch

          case 'ADD':
            // A new task was added, this shouldn't affect the current task list
            console.log('ADD operation received for task_modified, no action taken.')
            return // No need to refetch

          case 'EDIT':
            try {
              const dataPromise = fetchChildData(child.value.id)
              dataPromise.then((data) => {
                if (data) {
                  tasks.value = data.tasks || []
                }
              })
            } catch (err) {
              console.warn('Failed to fetch child after EDIT operation:', err)
            }
            break

          default:
            console.warn(`Unknown operation: ${payload.operation}`)
            return // No need to refetch
        }
      } catch (err) {
        console.warn('Failed to fetch child after task modification:', err)
      }
    }
  }
}

function handleRewardModified(event: Event) {
  const payload = event.payload as RewardModifiedEventPayload
  if (child.value) {
    const reward_id = payload.reward_id
    if (rewards.value.includes(reward_id)) {
      childRewardListRef.value?.refresh()
    }
  }
}

function handleChildModified(event: Event) {
  const payload = event.payload as ChildModifiedEventPayload
  if (child.value && payload.child_id == child.value.id) {
    switch (payload.operation) {
      case 'DELETE':
        // Navigate away back to children list
        router.push({ name: 'ChildrenListView' })
        break

      case 'ADD':
        // A new child was added, this shouldn't affect the current child view
        console.log('ADD operation received for child_modified, no action taken.')
        break

      case 'EDIT':
        //our child was edited, refetch its data
        try {
          const dataPromise = fetchChildData(payload.child_id)
          dataPromise.then((data) => {
            if (data) {
              child.value = data
            }
          })
        } catch (err) {
          console.warn('Failed to fetch child after EDIT operation:', err)
        }
        break
      default:
        console.warn(`Unknown operation: ${payload.operation}`)
    }
  }
}

async function fetchChildData(id: string | number) {
  loading.value = true
  try {
    const resp = await fetch(`/api/child/${id}`)
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
    const data = await resp.json()
    error.value = null
    return data
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'Failed to fetch child'
    console.error(err)
    return null
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  try {
    eventBus.on('child_task_triggered', handleTaskTriggered)
    eventBus.on('child_reward_triggered', handleRewardTriggered)
    eventBus.on('child_tasks_set', handleChildTaskSet)
    eventBus.on('child_rewards_set', handleChildRewardSet)
    eventBus.on('task_modified', handleTaskModified)
    eventBus.on('reward_modified', handleRewardModified)
    eventBus.on('child_modified', handleChildModified)
    eventBus.on('child_reward_request', handleRewardRequest)

    if (route.params.id) {
      const idParam = Array.isArray(route.params.id) ? route.params.id[0] : route.params.id
      if (idParam !== undefined) {
        const promise = fetchChildData(idParam)
        promise.then((data) => {
          if (data) {
            child.value = data
            tasks.value = data.tasks || []
            rewards.value = data.rewards || []
          }
        })
      }
    }
  } catch (err) {
    console.error('Error in onMounted:', err)
  }
})

onUnmounted(() => {
  eventBus.off('child_task_triggered', handleTaskTriggered)
  eventBus.off('child_reward_triggered', handleRewardTriggered)
  eventBus.off('child_tasks_set', handleChildTaskSet)
  eventBus.off('child_rewards_set', handleChildRewardSet)
  eventBus.off('child_modified', handleChildModified)
  eventBus.off('child_reward_request', handleRewardRequest)
  eventBus.off('task_modified', handleTaskModified)
  eventBus.off('reward_modified', handleRewardModified)
})

const triggerTask = (task: Task) => {
  selectedTask.value = task
  const pendingRewardIds = childRewardListRef.value?.getPendingRewards()
  if (pendingRewardIds && pendingRewardIds.length > 0) {
    showPendingRewardDialog.value = true
    return
  }
  showConfirm.value = true
}

async function cancelRewardById(rewardId: string) {
  if (!child.value?.id) {
    return
  }
  try {
    await fetch(`/api/child/${child.value.id}/cancel-request-reward`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ reward_id: rewardId }),
    })
  } catch (err) {
    console.error(`Failed to cancel reward ID ${rewardId}:`, err)
  }
}

async function cancelPendingReward() {
  if (!child.value?.id) {
    showPendingRewardDialog.value = false
    return
  }
  try {
    const pendingRewardIds = childRewardListRef.value?.getPendingRewards()
    await Promise.all(pendingRewardIds?.map((id: string) => cancelRewardById(id)) || [])
    childRewardListRef.value?.refresh()
  } catch (err) {
    console.error('Failed to cancel pending reward:', err)
  } finally {
    showPendingRewardDialog.value = false
    // After cancelling, proceed to trigger the task if one was selected
    if (selectedTask.value) {
      showConfirm.value = true
    }
  }
}

const confirmTriggerTask = async () => {
  if (!child.value?.id || !selectedTask.value) return
  try {
    const resp = await fetch(`/api/child/${child.value.id}/trigger-task`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ task_id: selectedTask.value.id }),
    })
    if (!resp.ok) return
    const data = await resp.json()
    if (child.value && child.value.id === data.id) child.value.points = data.points
  } catch (err) {
    console.error('Failed to trigger task:', err)
  } finally {
    showConfirm.value = false
    selectedTask.value = null
  }
}

const triggerReward = (reward: Reward, redeemable: boolean) => {
  if (!redeemable) return
  selectedReward.value = reward
  showRewardConfirm.value = true
}

const confirmTriggerReward = async () => {
  if (!child.value?.id || !selectedReward.value) return
  try {
    const resp = await fetch(`/api/child/${child.value.id}/trigger-reward`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ reward_id: selectedReward.value.id }),
    })
    if (!resp.ok) return
    const data = await resp.json()
    if (child.value && child.value.id === data.id) child.value.points = data.points
  } catch (err) {
    console.error('Failed to trigger reward:', err)
  } finally {
    showRewardConfirm.value = false
    selectedReward.value = null
  }
}

function goToAssignTasks() {
  if (child.value?.id) {
    router.push({ name: 'TaskAssignView', params: { id: child.value.id, type: 'good' } })
  }
}

function goToAssignBadHabits() {
  if (child.value?.id) {
    router.push({ name: 'TaskAssignView', params: { id: child.value.id, type: 'bad' } })
  }
}

function goToAssignRewards() {
  if (child.value?.id) {
    router.push({ name: 'RewardAssignView', params: { id: child.value.id } })
  }
}

const childId = computed(() => child.value?.id ?? null)
</script>

<template>
  <div class="container">
    <div v-if="loading" class="loading">Loading...</div>
    <div v-else-if="error" class="error">Error: {{ error }}</div>

    <div v-else class="layout">
      <div class="main">
        <ChildDetailCard :child="child" />
        <ChildTaskList
          title="Chores"
          ref="childChoreListRef"
          :task-ids="tasks"
          :child-id="childId"
          :is-parent-authenticated="isParentAuthenticated"
          :filter-type="1"
          @trigger-task="triggerTask"
        />
        <ChildTaskList
          title="Bad Habits"
          ref="childHabitListRef"
          :task-ids="tasks"
          :child-id="childId"
          :is-parent-authenticated="isParentAuthenticated"
          :filter-type="2"
          @trigger-task="triggerTask"
        />
        <ChildRewardList
          ref="childRewardListRef"
          :child-id="childId"
          :child-points="child?.points ?? 0"
          :is-parent-authenticated="false"
          @trigger-reward="triggerReward"
        />
      </div>
    </div>
    <div class="assign-buttons">
      <button v-if="child" class="assign-task-btn" @click="goToAssignTasks">Assign Tasks</button>
      <button v-if="child" class="assign-bad-btn" @click="goToAssignBadHabits">
        Assign Bad Habits
      </button>
      <button v-if="child" class="assign-reward-btn" @click="goToAssignRewards">
        Assign Rewards
      </button>
    </div>

    <!-- Pending Reward Dialog -->
    <div v-if="showPendingRewardDialog" class="modal-backdrop">
      <div class="modal">
        <div class="dialog-message" style="margin-bottom: 1.2rem">
          There is a pending reward request. The reward must be cancelled before triggering a new
          task.<br />
          Would you like to cancel the pending reward?
        </div>
        <div class="actions">
          <button @click="cancelPendingReward">Yes, Cancel Reward</button>
          <button @click="showPendingRewardDialog = false">No</button>
        </div>
      </div>
    </div>

    <div v-if="showConfirm && selectedTask" class="modal-backdrop">
      <div class="modal">
        <div class="task-info">
          <img
            v-if="selectedTask.image_url"
            :src="selectedTask.image_url"
            alt="Task Image"
            class="task-image"
          />
          <div class="task-details">
            <div class="task-name">{{ selectedTask.name }}</div>
            <div class="task-points" :class="selectedTask.is_good ? 'good' : 'bad'">
              {{ selectedTask.points }} pts
            </div>
          </div>
        </div>
        <div class="dialog-message" style="margin-bottom: 1.2rem">
          {{ selectedTask.is_good ? 'Add' : 'Subtract' }} these points
          {{ selectedTask.is_good ? 'to' : 'from' }}
          <span class="child-name">{{ child?.name }}</span>
        </div>
        <div class="actions">
          <button @click="confirmTriggerTask">Yes</button>
          <button
            @click="
              () => {
                showConfirm = false
                selectedTask = null
              }
            "
          >
            Cancel
          </button>
        </div>
      </div>
    </div>

    <div v-if="showRewardConfirm && selectedReward" class="modal-backdrop">
      <div class="modal">
        <div class="reward-info">
          <img
            v-if="selectedReward.image_id"
            :src="selectedReward.image_id"
            alt="Reward Image"
            class="reward-image"
          />
          <div class="reward-details">
            <div class="reward-name">{{ selectedReward.name }}</div>
            <div class="reward-points">
              {{
                selectedReward.points_needed === 0
                  ? 'Reward Ready!'
                  : selectedReward.points_needed + ' pts needed'
              }}
            </div>
          </div>
        </div>
        <div class="dialog-message" style="margin-bottom: 1.2rem">
          Redeem this reward for <span class="child-name">{{ child?.name }}</span
          >?
        </div>
        <div class="actions">
          <button @click="confirmTriggerReward">Yes</button>
          <button
            @click="
              () => {
                showRewardConfirm = false
                selectedReward = null
              }
            "
          >
            Cancel
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  min-height: 100vh;
  padding: 2rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-sizing: border-box;
}
.loading,
.error {
  color: white;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}
.error {
  color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
  border-radius: 8px;
  padding: 1rem;
}
.layout {
  display: flex;
  justify-content: center;
  align-items: flex-start;
}
.main {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1.5rem;
  width: 100%;
}

/* Modal styles */
.modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.45);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1200;
}
.modal {
  background: #fff;
  color: #222;
  padding: 1.5rem 2rem;
  border-radius: 12px;
  min-width: 240px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
  text-align: center;
}
.task-info {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}
.task-image {
  width: 72px;
  height: 72px;
  object-fit: cover;
  border-radius: 8px;
  background: #eee;
}
.task-details {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.task-name {
  font-weight: 600;
  font-size: 1.1rem;
}
.task-points,
.task-points.good,
.task-points.bad {
  font-weight: 600;
  font-size: 1.1rem;
}
.task-points.good {
  color: #38c172;
}
.task-points.bad {
  color: #ef4444;
}
.actions {
  margin-top: 1.2rem;
  display: flex;
  gap: 1rem;
  justify-content: center;
}
.actions button {
  padding: 0.5rem 1.2rem;
  border-radius: 8px;
  border: none;
  font-weight: 600;
  cursor: pointer;
}
.actions button:first-child {
  background: #667eea;
  color: #fff;
}
.actions button:last-child {
  background: #f3f3f3;
  color: #666;
}
.actions button:last-child:hover {
  background: #e2e8f0;
}

/* Mobile adjustments */
@media (max-width: 900px) {
  .layout {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .container {
    padding: 1rem;
  }
  .main {
    gap: 1rem;
  }
}

.dialog-message {
  font-size: 1.08rem;
  color: #444;
  font-weight: 500;
}
.dialog-message .child-name {
  color: #667eea;
  font-weight: 700;
  margin-left: 2px;
}
.reward-info {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}
.reward-image {
  width: 72px;
  height: 72px;
  object-fit: cover;
  border-radius: 8px;
  background: #eee;
}
.reward-details {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.reward-name {
  font-weight: 600;
  font-size: 1.1rem;
}
.reward-points {
  color: #667eea;
  font-weight: 500;
  font-size: 1rem;
}
.assign-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
  margin: 2rem 0;
}
.assign-task-btn,
.assign-bad-btn,
.assign-reward-btn {
  font-weight: 600;
  border: none;
  border-radius: 8px;
  padding: 0.7rem 1.5rem;
  font-size: 1.1rem;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.08);
  transition: background 0.18s;
  color: #fff;
  background: #667eea;
}
.assign-task-btn:hover,
.assign-bad-btn:hover,
.assign-reward-btn:hover {
  background: #5a67d8;
}
.assign-bad-btn {
  background: #ef4444;
}
.assign-bad-btn:hover {
  background: #dc2626;
}
.assign-reward-btn {
  background: #38c172;
}
.assign-reward-btn:hover {
  background: #2f855a;
}
</style>
