<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../stores/auth'
import { useActivitiesStore } from '../stores/activities'
import type { FtpDetection } from '../types/models'
import Card from 'primevue/card'
import InputNumber from 'primevue/inputnumber'
import InputText from 'primevue/inputtext'
import Select from 'primevue/select'
import Textarea from 'primevue/textarea'
import Button from 'primevue/button'
import Message from 'primevue/message'
import Dialog from 'primevue/dialog'

const auth = useAuthStore()
const store = useActivitiesStore()

const form = ref({
  name: '',
  ftp: null as number | null,
  lthr: null as number | null,
  weight: null as number | null,
  goals: '',
  experience_level: '',
})

const saving = ref(false)
const success = ref(false)
const detectingFtp = ref(false)
const ftpDetection = ref<FtpDetection | null>(null)
const showFtpDialog = ref(false)

async function detectFtp() {
  detectingFtp.value = true
  try {
    ftpDetection.value = await store.detectFtp()
    showFtpDialog.value = true
  } finally {
    detectingFtp.value = false
  }
}

async function applyDetectedFtp() {
  if (ftpDetection.value?.detected_ftp) {
    form.value.ftp = ftpDetection.value.detected_ftp
    showFtpDialog.value = false
    await save()
  }
}

const experienceLevels = [
  { label: 'Beginner', value: 'beginner' },
  { label: 'Intermediate', value: 'intermediate' },
  { label: 'Advanced', value: 'advanced' },
  { label: 'Pro', value: 'pro' },
]

onMounted(() => {
  if (auth.rider) {
    form.value.name = auth.rider.name || ''
    form.value.ftp = auth.rider.ftp
    form.value.lthr = auth.rider.lthr
    form.value.weight = auth.rider.weight
    form.value.goals = auth.rider.goals || ''
    form.value.experience_level = auth.rider.experience_level || ''
  }
})

async function save() {
  saving.value = true
  success.value = false
  try {
    await auth.updateRider({
      name: form.value.name || undefined,
      ftp: form.value.ftp,
      lthr: form.value.lthr,
      weight: form.value.weight,
      goals: form.value.goals || null,
      experience_level: form.value.experience_level || null,
    })
    success.value = true
    setTimeout(() => { success.value = false }, 3000)
  } finally {
    saving.value = false
  }
}
</script>

<template>
  <div>
    <h1 class="text-2xl font-semibold mb-6">Settings</h1>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
      <!-- Profile -->
      <Card>
        <template #title>Profile</template>
        <template #content>
          <div class="flex flex-col gap-4">
            <div>
              <label class="text-surface-500 text-xs uppercase font-medium mb-1 block">Name</label>
              <InputText v-model="form.name" class="w-full" />
            </div>
            <div>
              <label class="text-surface-500 text-xs uppercase font-medium mb-1 block">Experience Level</label>
              <Select
                v-model="form.experience_level"
                :options="experienceLevels"
                option-label="label"
                option-value="value"
                placeholder="Select level"
                class="w-full"
              />
            </div>
            <div>
              <label class="text-surface-500 text-xs uppercase font-medium mb-1 block">Goals</label>
              <Textarea v-model="form.goals" rows="3" class="w-full" placeholder="e.g. Complete a century ride, improve FTP to 300W..." />
            </div>
          </div>
        </template>
      </Card>

      <!-- Training Zones -->
      <Card>
        <template #title>Training Parameters</template>
        <template #content>
          <div class="flex flex-col gap-4">
            <div>
              <label class="text-surface-500 text-xs uppercase font-medium mb-1 block">FTP (Functional Threshold Power)</label>
              <div class="flex items-center gap-2">
                <InputNumber v-model="form.ftp" :min="50" :max="600" class="w-full" placeholder="e.g. 250" />
                <span class="text-surface-500 text-sm font-medium">W</span>
              </div>
              <Button
                label="Auto-detect FTP"
                icon="pi pi-sparkles"
                severity="secondary"
                size="small"
                class="mt-2"
                :loading="detectingFtp"
                @click="detectFtp"
              />
            </div>
            <div>
              <label class="text-surface-500 text-xs uppercase font-medium mb-1 block">LTHR (Lactate Threshold Heart Rate)</label>
              <div class="flex items-center gap-2">
                <InputNumber v-model="form.lthr" :min="100" :max="220" class="w-full" placeholder="e.g. 170" />
                <span class="text-surface-500 text-sm font-medium">bpm</span>
              </div>
            </div>
            <div>
              <label class="text-surface-500 text-xs uppercase font-medium mb-1 block">Weight</label>
              <div class="flex items-center gap-2">
                <InputNumber v-model="form.weight" :min="30" :max="200" :max-fraction-digits="1" class="w-full" placeholder="e.g. 75" />
                <span class="text-surface-500 text-sm font-medium">kg</span>
              </div>
            </div>
            <div v-if="form.ftp && form.weight" class="bg-surface-50 rounded-lg p-3 border border-surface-200">
              <p class="text-surface-500 text-xs uppercase mb-1">W/kg ratio</p>
              <p class="text-xl font-bold text-primary">{{ (form.ftp / form.weight).toFixed(2) }} <span class="text-sm font-normal text-surface-500">W/kg</span></p>
            </div>
          </div>
        </template>
      </Card>
    </div>

    <div class="flex items-center gap-4 mt-6">
      <Button label="Save Changes" icon="pi pi-check" :loading="saving" @click="save" />
      <transition enter-active-class="transition-opacity" leave-active-class="transition-opacity" enter-from-class="opacity-0" leave-to-class="opacity-0">
        <Message v-if="success" severity="success" :closable="false" class="m-0">Settings saved successfully</Message>
      </transition>
    </div>

    <!-- FTP Detection Dialog -->
    <Dialog v-model:visible="showFtpDialog" header="FTP Auto-Detection" :modal="true" :style="{ width: '420px' }">
      <div v-if="ftpDetection">
        <div v-if="ftpDetection.detected_ftp" class="flex flex-col gap-4">
          <div class="bg-primary/10 rounded-lg p-4 text-center">
            <p class="text-surface-500 text-xs uppercase mb-1">Detected FTP</p>
            <p class="text-3xl font-bold text-primary">{{ ftpDetection.detected_ftp }} <span class="text-lg font-normal">W</span></p>
          </div>
          <div class="grid grid-cols-2 gap-3 text-sm">
            <div class="bg-surface-50 rounded-lg p-3">
              <p class="text-surface-500 text-xs">Best 20min Power</p>
              <p class="font-semibold">{{ ftpDetection.best_20min_power }} W</p>
            </div>
            <div class="bg-surface-50 rounded-lg p-3">
              <p class="text-surface-500 text-xs">Current FTP</p>
              <p class="font-semibold">{{ ftpDetection.current_ftp ?? '—' }} W</p>
            </div>
            <div class="bg-surface-50 rounded-lg p-3">
              <p class="text-surface-500 text-xs">Activity</p>
              <p class="font-semibold text-xs">{{ ftpDetection.activity_name }}</p>
            </div>
            <div class="bg-surface-50 rounded-lg p-3">
              <p class="text-surface-500 text-xs">Date</p>
              <p class="font-semibold text-xs">{{ ftpDetection.date }}</p>
            </div>
          </div>
          <p class="text-surface-500 text-xs">FTP = Best 20min Power x 0.95. This will recalculate TSS/IF for all your activities.</p>
          <div class="flex justify-end gap-2">
            <Button label="Cancel" severity="secondary" @click="showFtpDialog = false" />
            <Button label="Apply FTP" icon="pi pi-check" @click="applyDetectedFtp" />
          </div>
        </div>
        <div v-else class="text-center py-4">
          <i class="pi pi-info-circle text-2xl text-surface-400 mb-2"></i>
          <p class="text-surface-500">{{ ftpDetection.message || 'No 20-minute power data found. Upload more rides!' }}</p>
          <Button label="Close" severity="secondary" class="mt-4" @click="showFtpDialog = false" />
        </div>
      </div>
    </Dialog>
  </div>
</template>
