<template>
  <form @submit.prevent="handleSubmit" class="space-y-6">
    <!-- Basic Information -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div class="space-y-2">
        <Label for="name">Project Name</Label>
        <Input
          id="name"
          v-model="formData.name"
          placeholder="Enter project name"
          :disabled="isSubmitting"
          required
        />
      </div>

      <div class="space-y-2">
        <Label for="code_name">Code Name</Label>
        <Input
          id="code_name"
          v-model="formData.code_name"
          placeholder="Enter project code name"
          :disabled="isSubmitting"
          required
        />
      </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div class="space-y-2">
        <Label for="client_name">Client Name</Label>
        <Input
          id="client_name"
          v-model="formData.client_name"
          placeholder="Enter client name"
          :disabled="isSubmitting"
          required
        />
      </div>

      <div class="space-y-2">
        <Label for="project_type">Project Type</Label>
        <Select v-model="formData.project_type" :disabled="isSubmitting">
          <SelectTrigger>
            <SelectValue placeholder="Select project type" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="tv">TV</SelectItem>
            <SelectItem value="cinema">Cinema</SelectItem>
            <SelectItem value="game">Game</SelectItem>
          </SelectContent>
        </Select>
      </div>
    </div>

    <!-- Description -->
    <div class="space-y-2">
      <Label for="description">Description</Label>
      <Textarea
        id="description"
        v-model="formData.description"
        placeholder="Enter project description (optional)"
        :disabled="isSubmitting"
        rows="3"
      />
    </div>

    <!-- Status and Dates -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
      <div class="space-y-2">
        <Label for="status">Status</Label>
        <Select v-model="formData.status" :disabled="isSubmitting">
          <SelectTrigger>
            <SelectValue placeholder="Select status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="planning">Planning</SelectItem>
            <SelectItem value="in_progress">In Progress</SelectItem>
            <SelectItem value="on_hold">On Hold</SelectItem>
            <SelectItem value="completed">Completed</SelectItem>
            <SelectItem value="cancelled">Cancelled</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div class="space-y-2">
        <Label for="start_date">Start Date</Label>
        <Input
          id="start_date"
          v-model="formData.start_date"
          type="date"
          :disabled="isSubmitting"
        />
      </div>

      <div class="space-y-2">
        <Label for="end_date">End Date</Label>
        <Input
          id="end_date"
          v-model="formData.end_date"
          type="date"
          :disabled="isSubmitting"
        />
      </div>
    </div>

    <!-- Form Actions -->
    <div class="flex justify-end gap-3 pt-4 border-t">
      <Button
        type="button"
        variant="outline"
        @click="resetForm"
        :disabled="isSubmitting"
      >
        Reset
      </Button>
      <Button
        type="submit"
        :disabled="isSubmitting || !hasChanges"
      >
        <div v-if="isSubmitting" class="flex items-center gap-2">
          <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-current"></div>
          <span>Saving...</span>
        </div>
        <span v-else>Save Changes</span>
      </Button>
    </div>

    <!-- Success/Error Messages -->
    <div v-if="successMessage" class="flex items-center gap-2 text-green-600 text-sm">
      <CheckCircle class="h-4 w-4" />
      {{ successMessage }}
    </div>
    
    <div v-if="errorMessage" class="flex items-center gap-2 text-red-600 text-sm">
      <AlertCircle class="h-4 w-4" />
      {{ errorMessage }}
    </div>
  </form>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { CheckCircle, AlertCircle } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { projectService, type Project, type ProjectUpdate } from '@/services/project'

interface Props {
  project: Project
}

interface Emits {
  (e: 'project-updated', project: Project): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// State
const isSubmitting = ref(false)
const successMessage = ref('')
const errorMessage = ref('')

// Form data
const formData = reactive<ProjectUpdate & { name: string; code_name: string; client_name: string; project_type: 'tv' | 'cinema' | 'game' }>({
  name: props.project.name,
  code_name: props.project.code_name,
  client_name: props.project.client_name,
  project_type: props.project.project_type,
  description: props.project.description || '',
  status: props.project.status,
  start_date: props.project.start_date || '',
  end_date: props.project.end_date || ''
})

// Original data for comparison
const originalData = reactive({
  name: props.project.name,
  code_name: props.project.code_name,
  client_name: props.project.client_name,
  project_type: props.project.project_type,
  description: props.project.description || '',
  status: props.project.status,
  start_date: props.project.start_date || '',
  end_date: props.project.end_date || ''
})

// Computed
const hasChanges = computed(() => {
  return Object.keys(formData).some(key => {
    const formValue = formData[key as keyof typeof formData]
    const originalValue = originalData[key as keyof typeof originalData]
    return formValue !== originalValue
  })
})

// Methods
const resetForm = () => {
  Object.assign(formData, originalData)
  clearMessages()
}

const clearMessages = () => {
  successMessage.value = ''
  errorMessage.value = ''
}

const handleSubmit = async () => {
  if (!hasChanges.value) return

  try {
    isSubmitting.value = true
    clearMessages()

    // Prepare update data (only include changed fields)
    const updateData: ProjectUpdate = {}
    Object.keys(formData).forEach(key => {
      const formValue = formData[key as keyof typeof formData]
      const originalValue = originalData[key as keyof typeof originalData]
      if (formValue !== originalValue) {
        updateData[key as keyof ProjectUpdate] = formValue as any
      }
    })

    // Update project
    const updatedProject = await projectService.updateProject(props.project.id, updateData)
    
    // Update original data to reflect the new state
    Object.assign(originalData, formData)
    
    // Emit the updated project
    emit('project-updated', updatedProject)
    
    successMessage.value = 'Project updated successfully!'
    
    // Clear success message after 3 seconds
    setTimeout(() => {
      successMessage.value = ''
    }, 3000)

  } catch (error) {
    console.error('Failed to update project:', error)
    errorMessage.value = error instanceof Error ? error.message : 'Failed to update project'
  } finally {
    isSubmitting.value = false
  }
}

// Watch for prop changes to update form data
watch(() => props.project, (newProject) => {
  Object.assign(formData, {
    name: newProject.name,
    code_name: newProject.code_name,
    client_name: newProject.client_name,
    project_type: newProject.project_type,
    description: newProject.description || '',
    status: newProject.status,
    start_date: newProject.start_date || '',
    end_date: newProject.end_date || ''
  })
  
  Object.assign(originalData, {
    name: newProject.name,
    code_name: newProject.code_name,
    client_name: newProject.client_name,
    project_type: newProject.project_type,
    description: newProject.description || '',
    status: newProject.status,
    start_date: newProject.start_date || '',
    end_date: newProject.end_date || ''
  })
}, { deep: true })

// Clear messages when form data changes
watch(formData, clearMessages)
</script>