<script setup lang="ts">
import { ref, computed } from 'vue'
import { useAuth } from './composables/useAuth'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'

const props = defineProps<{
  onSuccess?: () => void
  onBack?: () => void
}>()

const { requestPasswordReset, isLoading, error } = useAuth()

const email = ref('')
const submitted = ref(false)

const isFormValid = computed(() => {
  return email.value.trim() !== '' && email.value.includes('@')
})

async function handleSubmit() {
  const result = await requestPasswordReset(email.value)
  if (result.success) {
    submitted.value = true
    props.onSuccess?.()
  }
}
</script>

<template>
  <Card class="w-full max-w-md">
    <CardHeader class="space-y-1">
      <CardTitle class="text-2xl font-bold">Reset password</CardTitle>
      <CardDescription>
        Enter your email address and we'll send you a link to reset your password
      </CardDescription>
    </CardHeader>

    <template v-if="!submitted">
      <form @submit.prevent="handleSubmit">
        <CardContent class="space-y-4">
          <Alert v-if="error" variant="destructive">
            <AlertDescription>\{{ error }}</AlertDescription>
          </Alert>

          <div class="space-y-2">
            <Label for="email">Email</Label>
            <Input
              id="email"
              v-model="email"
              type="email"
              placeholder="name@example.com"
              autocomplete="email"
              required
            />
          </div>
        </CardContent>

        <CardFooter class="flex flex-col space-y-4">
          <Button
            type="submit"
            class="w-full"
            :disabled="!isFormValid || isLoading"
          >
            <span v-if="isLoading">Sending...</span>
            <span v-else>Send reset link</span>
          </Button>

          <Button
            v-if="onBack"
            type="button"
            variant="ghost"
            class="w-full"
            @click="onBack"
          >
            Back to sign in
          </Button>
        </CardFooter>
      </form>
    </template>

    <template v-else>
      <CardContent class="space-y-4">
        <Alert>
          <AlertDescription>
            If an account with that email exists, we've sent you a password reset link.
            Please check your inbox and spam folder.
          </AlertDescription>
        </Alert>
      </CardContent>

      <CardFooter>
        <Button
          v-if="onBack"
          type="button"
          variant="outline"
          class="w-full"
          @click="onBack"
        >
          Back to sign in
        </Button>
      </CardFooter>
    </template>
  </Card>
</template>
