<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
import * as z from 'zod'
import { format } from 'date-fns'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Calendar, Loader2 } from 'lucide-vue-next'
import { toastService } from '@/core/services/ToastService'
import { injectService, SERVICE_TOKENS } from '@/core/di-container'
import { EVENTS_API_TOKEN } from '../composables/useEvents'
import type { CreateEventRequest } from '../types/event'

// Props
interface Props {
  open: boolean
  onCreateEvent: (eventData: CreateEventRequest) => Promise<void>
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:open': [value: boolean]
  'event-created': []
}>()

// Form validation schema (removed wallet field - will be auto-selected)
// Note: Ticket sales will automatically close when the event ends
const formSchema = toTypedSchema(z.object({
  name: z.string().min(1, "Event name is required").max(200, "Name too long"),
  info: z.string().min(1, "Event description is required").max(2000, "Description too long"),
  event_start_date: z.string().min(1, "Event start date is required"),
  event_end_date: z.string().min(1, "Event end date is required"),
  currency: z.string().default("sats"),
  amount_tickets: z.number().min(1, "Must have at least 1 ticket").max(100000, "Too many tickets"),
  price_per_ticket: z.number().min(0, "Price must be 0 or higher"),
  banner: z.string().optional(),
}).refine((data) => {
  const startDate = new Date(data.event_start_date)
  const endDate = new Date(data.event_end_date)
  return startDate <= endDate
}, {
  message: "Event start date must be before or equal to end date",
  path: ["event_end_date"]
}))

// Form setup
const form = useForm({
  validationSchema: formSchema,
  initialValues: {
    name: '',
    info: '',
    event_start_date: '',
    event_end_date: '',
    currency: 'sats',
    amount_tickets: 100,
    price_per_ticket: 1000,
    banner: ''
  }
})

// Get PaymentService for wallet selection
const paymentService = injectService(SERVICE_TOKENS.PAYMENT_SERVICE)

// Get EventsApiService for currency loading
const eventsApi = injectService(EVENTS_API_TOKEN)

// Load available currencies
const availableCurrencies = ref<string[]>(['sats'])
const loadingCurrencies = ref(false)

// Load currencies when dialog opens
watch(() => props.open, async (isOpen) => {
  if (isOpen && eventsApi && !loadingCurrencies.value) {
    loadingCurrencies.value = true
    try {
      // Type cast to ensure getCurrencies method exists
      const apiService = eventsApi as any
      if (apiService.getCurrencies) {
        availableCurrencies.value = await apiService.getCurrencies()
      }
    } catch (error) {
      console.warn('Failed to load currencies:', error)
      // Keep default currencies
    } finally {
      loadingCurrencies.value = false
    }
  }
})

const { resetForm, meta } = form
const isFormValid = computed(() => meta.value.valid)
const isLoading = ref(false)

// Get today's date in YYYY-MM-DD format for min date validation
const today = computed(() => format(new Date(), 'yyyy-MM-dd'))

// Form submission
const onSubmit = form.handleSubmit(async (formValues) => {
  if (!isFormValid.value) return
  
  if (!paymentService) {
    toastService.error('Payment service not available')
    return
  }

  // Type cast to ensure getPreferredWallet method exists
  const paymentSvc = paymentService as any
  const preferredWallet = paymentSvc?.getPreferredWallet?.()
  if (!preferredWallet) {
    toastService.error('No wallet available. Please connect a wallet first.')
    return
  }
  
  isLoading.value = true
  try {
    // Add the selected wallet ID and set closing_date to event_end_date
    const eventData: CreateEventRequest = {
      ...formValues,
      wallet: preferredWallet.id,
      closing_date: formValues.event_end_date // Ticket sales close when event ends
    }
    
    await props.onCreateEvent(eventData)
    toastService.success('Event created successfully!')
    resetForm()
    emit('update:open', false)
    emit('event-created')
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Failed to create event'
    toastService.error(errorMessage)
  } finally {
    isLoading.value = false
  }
})

// Handle dialog close
const handleOpenChange = (open: boolean) => {
  if (!open && !isLoading.value) {
    resetForm()
  }
  emit('update:open', open)
}
</script>

<template>
  <Dialog :open="open" @update:open="handleOpenChange">
    <DialogContent class="max-w-2xl max-h-[90vh] overflow-y-auto">
      <DialogHeader>
        <DialogTitle class="flex items-center gap-2">
          <Calendar class="w-5 h-5" />
          Create New Event
        </DialogTitle>
        <DialogDescription>
          Create a new event with ticket sales. All fields are required.
        </DialogDescription>
      </DialogHeader>

      <form @submit="onSubmit" class="space-y-6 mt-4">
        <!-- Event Name -->
        <FormField v-slot="{ componentField }" name="name">
          <FormItem>
            <FormLabel>Event Name *</FormLabel>
            <FormControl>
              <Input 
                placeholder="Enter event name"
                v-bind="componentField"
              />
            </FormControl>
            <FormMessage />
          </FormItem>
        </FormField>

        <!-- Event Description -->
        <FormField v-slot="{ componentField }" name="info">
          <FormItem>
            <FormLabel>Event Description *</FormLabel>
            <FormControl>
              <Textarea 
                placeholder="Describe your event..."
                rows="3"
                v-bind="componentField"
              />
            </FormControl>
            <FormDescription>Provide details about your event</FormDescription>
            <FormMessage />
          </FormItem>
        </FormField>

        <!-- Date Fields -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <FormField v-slot="{ componentField }" name="event_start_date">
            <FormItem>
              <FormLabel>Event Starts *</FormLabel>
              <FormControl>
                <Input 
                  type="date"
                  :min="today"
                  v-bind="componentField"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          </FormField>

          <FormField v-slot="{ componentField }" name="event_end_date">
            <FormItem>
              <FormLabel>Event Ends *</FormLabel>
              <FormControl>
                <Input 
                  type="date"
                  :min="today"
                  v-bind="componentField"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          </FormField>
        </div>

        <!-- Ticket Details -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <FormField v-slot="{ componentField }" name="amount_tickets">
            <FormItem>
              <FormLabel>Total Tickets *</FormLabel>
              <FormControl>
                <Input 
                  type="number"
                  min="1"
                  max="100000"
                  placeholder="100"
                  v-bind="componentField"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          </FormField>

          <FormField v-slot="{ componentField }" name="price_per_ticket">
            <FormItem>
              <FormLabel>Price per Ticket *</FormLabel>
              <FormControl>
                <Input 
                  type="number"
                  min="0"
                  step="0.01"
                  placeholder="1000"
                  v-bind="componentField"
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          </FormField>

          <FormField v-slot="{ componentField }" name="currency">
            <FormItem>
              <FormLabel>Currency</FormLabel>
              <FormControl>
                <Select v-bind="componentField">
                  <SelectTrigger>
                    <SelectValue placeholder="Select currency" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem
                      v-for="currency in availableCurrencies"
                      :key="currency"
                      :value="currency"
                    >
                      {{ currency }}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </FormControl>
              <FormDescription>
                <span v-if="loadingCurrencies">Loading currencies...</span>
                <span v-else>Currency for ticket pricing</span>
              </FormDescription>
              <FormMessage />
            </FormItem>
          </FormField>
        </div>

        <!-- Banner URL (Optional) -->
        <FormField v-slot="{ componentField }" name="banner">
          <FormItem>
            <FormLabel>Banner Image URL (Optional)</FormLabel>
            <FormControl>
              <Input 
                type="url"
                placeholder="https://example.com/banner.jpg"
                v-bind="componentField"
              />
            </FormControl>
            <FormDescription>URL to an image for your event banner</FormDescription>
            <FormMessage />
          </FormItem>
        </FormField>

        <!-- Action Buttons -->
        <div class="flex justify-end gap-3 pt-4">
          <Button 
            type="button" 
            variant="outline" 
            @click="handleOpenChange(false)"
            :disabled="isLoading"
          >
            Cancel
          </Button>
          <Button 
            type="submit"
            :disabled="isLoading || !isFormValid"
          >
            <Loader2 v-if="isLoading" class="w-4 h-4 mr-2 animate-spin" />
            {{ isLoading ? 'Creating...' : 'Create Event' }}
          </Button>
        </div>
      </form>
    </DialogContent>
  </Dialog>
</template>
