<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ChildDetailCard from './ChildDetailCard.vue'
import ScrollingList from '../shared/ScrollingList.vue'
import { eventBus } from '@/common/eventBus'
import '@/assets/view-shared.css'
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 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
    childRewardListRef.value?.refresh()
  }
}

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
  }
}

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 || []
                }
                loading.value = false
              })
            } 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)
        loading.value = false
      }
    }
  }
}

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
            }
            loading.value = false
          })
        } catch (err) {
          console.warn('Failed to fetch child after EDIT operation:', err)
          loading.value = false
        }
        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 {
  }
}

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 || []
          }
          loading.value = false
        })
      }
    }
  } 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)
})

function getPendingRewardIds(): string[] {
  const items = childRewardListRef.value?.items || []
  return items.filter((item: RewardStatus) => item.redeeming).map((item: RewardStatus) => item.id)
}

const triggerTask = (task: Task) => {
  selectedTask.value = task
  const pendingRewardIds = getPendingRewardIds()
  console.log('Pending reward IDs:', pendingRewardIds)
  if (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 = getPendingRewardIds()
    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: RewardStatus) => {
  if (reward.points_needed > 0) 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 } })
  }
}
</script>

<template>
  <div>
    <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" />
        <ScrollingList
          title="Chores"
          ref="childChoreListRef"
          :fetchBaseUrl="`/api/task/list?ids=${tasks.join(',')}`"
          :ids="tasks"
          itemKey="tasks"
          imageField="image_id"
          @trigger-item="triggerTask"
          :getItemClass="(item) => ({ bad: !item.is_good, good: item.is_good })"
          :filter-fn="
            (item) => {
              return item.is_good
            }
          "
        >
          <template #item="{ item }">
            <div class="item-name">{{ item.name }}</div>
            <img v-if="item.image_url" :src="item.image_url" alt="Task Image" class="item-image" />
            <div
              class="item-points"
              :class="{ 'good-points': item.is_good, 'bad-points': !item.is_good }"
            >
              {{ item.is_good ? item.points : -item.points }} Points
            </div>
          </template>
        </ScrollingList>
        <ScrollingList
          title="Penalties"
          ref="childPenaltyListRef"
          :fetchBaseUrl="`/api/task/list?ids=${tasks.join(',')}`"
          :ids="tasks"
          itemKey="tasks"
          imageField="image_id"
          @trigger-item="triggerTask"
          :getItemClass="(item) => ({ bad: !item.is_good, good: item.is_good })"
          :filter-fn="
            (item) => {
              return !item.is_good
            }
          "
        >
          <template #item="{ item }">
            <div class="item-name">{{ item.name }}</div>
            <img v-if="item.image_url" :src="item.image_url" alt="Task Image" class="item-image" />
            <div
              class="item-points"
              :class="{ 'good-points': item.is_good, 'bad-points': !item.is_good }"
            >
              {{ item.is_good ? item.points : -item.points }} Points
            </div>
          </template>
        </ScrollingList>
        <ScrollingList
          title="Rewards"
          ref="childRewardListRef"
          :fetchBaseUrl="`/api/child/${child?.id}/reward-status`"
          itemKey="reward_status"
          imageField="image_id"
          @trigger-item="triggerReward"
          :getItemClass="(item) => ({ reward: true })"
        >
          <template #item="{ item }: { item: RewardStatus }">
            <div class="item-name">{{ item.name }}</div>
            <img
              v-if="item.image_url"
              :src="item.image_url"
              alt="Reward Image"
              class="item-image"
            />
            <div class="item-points">
              <span v-if="item.redeeming" class="pending">PENDING</span>
              <span v-if="item.points_needed <= 0" class="ready">REWARD READY</span>
              <span v-else>{{ item.points_needed }} more points</span>
            </div>
          </template>
        </ScrollingList>
      </div>
    </div>
    <div class="assign-buttons">
      <button v-if="child" class="btn btn-primary" @click="goToAssignTasks">Assign Tasks</button>
      <button v-if="child" class="btn btn-danger" @click="goToAssignBadHabits">
        Assign Penalties
      </button>
      <button v-if="child" class="btn btn-green" @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" class="btn btn-primary">Yes</button>
          <button @click="showPendingRewardDialog = false" class="btn btn-secondary">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 }} points
            </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" class="btn btn-primary">Yes</button>
          <button
            @click="
              () => {
                showConfirm = false
                selectedTask = null
              }
            "
            class="btn btn-secondary"
          >
            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_url"
            :src="selectedReward.image_url"
            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 + ' more points'
              }}
            </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" class="btn btn-primary">Yes</button>
          <button
            @click="
              () => {
                showRewardConfirm = false
                selectedReward = null
              }
            "
            class="btn btn-secondary"
          >
            Cancel
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.assign-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
  margin: 2rem 0;
}

.back-btn {
  background: var(--back-btn-bg);
  border: 0;
  padding: 0.6rem 1rem;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 1.5rem;
  color: var(--back-btn-color);
  font-weight: 600;
}

.item-points {
  color: var(--item-points-color, #ffd166);
  font-size: 1rem;
  font-weight: 900;
  text-shadow: var(--item-points-shadow);
}

.ready {
  color: var(--item-points-ready-color, #38c172);
  letter-spacing: 0.5px;
}
.pending {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  background: var(--pending-block-bg, #222b);
  color: var(--pending-block-color, #62ff7a);
  font-weight: 700;
  font-size: 1.05rem;
  text-align: center;
  border-radius: 6px;
  padding: 0.4rem 0;
  letter-spacing: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
  opacity: 0.95;
  pointer-events: none;
}

/* Mobile tweaks */
@media (max-width: 480px) {
  .item-points {
    font-size: 0.78rem;
  }
}

:deep(.good) {
  border-color: var(--list-item-border-good);
  background: var(--list-item-bg-good);
}
:deep(.bad) {
  border-color: var(--list-item-border-bad);
  background: var(--list-item-bg-bad);
}
:deep(.reward) {
  border-color: var(--list-item-border-reward);
  background: var(--list-item-bg-reward);
}
</style>
