<template>
  <div class="p-6 space-y-6">
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-3xl font-bold">Profile</h1>
        <p class="text-muted-foreground">Manage your account settings and preferences</p>
      </div>
      <Button variant="outline" @click="refreshData" :disabled="isLoading">
        <RefreshCw class="h-4 w-4 mr-2" :class="{ 'animate-spin': isLoading }" />
        Refresh
      </Button>
    </div>

    <!-- Error Alert -->
    <Alert v-if="error" variant="destructive">
      <AlertCircle class="h-4 w-4" />
      <AlertTitle>Error</AlertTitle>
      <AlertDescription>{{ error }}</AlertDescription>
    </Alert>

    <!-- Profile Information Card -->
    <Card>
      <CardHeader>
        <CardTitle class="flex items-center gap-2">
          <User class="h-5 w-5" />
          Profile Information
        </CardTitle>
        <CardDescription>Update your personal information and account details</CardDescription>
      </CardHeader>
      <CardContent class="space-y-6">
        <!-- Profile Header with Avatar Upload -->
        <div class="flex items-center gap-6">
          <!-- Avatar with Upload Controls -->
          <div class="relative group">
            <Avatar class="h-24 w-24">
              <AvatarImage 
                v-if="user?.avatar_url" 
                :src="getAvatarUrl(user.avatar_url, user.first_name, user.last_name)" 
              />
              <AvatarImage 
                v-else
                :src="getInitialsAvatarUrl(user?.first_name, user?.last_name)" 
              />
              <AvatarFallback class="text-2xl">{{ userInitials }}</AvatarFallback>
            </Avatar>
            
            <!-- Upload Button Overlay -->
            <Button
              variant="secondary"
              size="icon"
              class="absolute bottom-0 right-0 h-8 w-8 rounded-full shadow-md"
              @click="triggerAvatarUpload"
              :disabled="isUploadingAvatar"
            >
              <Camera v-if="!isUploadingAvatar" class="h-4 w-4" />
              <Loader2 v-else class="h-4 w-4 animate-spin" />
            </Button>
            
            <!-- Hidden File Input -->
            <input
              ref="avatarFileInput"
              type="file"
              accept=".jpg,.jpeg,.png,.gif,.webp"
              class="hidden"
              @change="handleAvatarSelect"
            />
          </div>

          <!-- User Info -->
          <div class="flex-1 space-y-2">
            <h3 class="text-xl font-semibold">{{ user?.first_name }} {{ user?.last_name }}</h3>
            <p class="text-muted-foreground">{{ user?.email }}</p>
            <div class="flex items-center gap-2">
              <Badge>{{ formatRole(user?.role) }}</Badge>
              <Badge v-if="user?.is_admin" variant="destructive">Admin</Badge>
              <Badge :variant="user?.is_approved ? 'default' : 'secondary'">
                {{ user?.is_approved ? 'Approved' : 'Pending' }}
              </Badge>
            </div>
            
            <!-- Avatar Actions -->
            <div class="flex items-center gap-2 pt-1">
              <Button
                variant="outline"
                size="sm"
                @click="triggerAvatarUpload"
                :disabled="isUploadingAvatar"
              >
                <Upload class="h-3 w-3 mr-1" />
                Change Avatar
              </Button>
              
              <Button
                v-if="user?.avatar_url"
                variant="outline"
                size="sm"
                @click="handleRemoveAvatar"
                :disabled="isRemovingAvatar || isUploadingAvatar"
              >
                <X class="h-3 w-3 mr-1" />
                Remove
              </Button>
            </div>
            
            <!-- Upload Status -->
            <p v-if="avatarError" class="text-xs text-destructive">
              {{ avatarError }}
            </p>
          </div>
        </div>

        <Separator />

        <!-- Edit Profile Form -->
        <form @submit.prevent="handleUpdateProfile" class="space-y-4">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="space-y-2">
              <Label for="first_name">First Name</Label>
              <Input
                id="first_name"
                v-model="profileForm.first_name"
                placeholder="Enter your first name"
                :disabled="isUpdatingProfile"
              />
            </div>
            <div class="space-y-2">
              <Label for="last_name">Last Name</Label>
              <Input
                id="last_name"
                v-model="profileForm.last_name"
                placeholder="Enter your last name"
                :disabled="isUpdatingProfile"
              />
            </div>
          </div>

          <div class="flex justify-end">
            <Button 
              type="submit" 
              :disabled="isUpdatingProfile || !hasProfileChanges"
            >
              <Loader2 v-if="isUpdatingProfile" class="h-4 w-4 mr-2 animate-spin" />
              Update Profile
            </Button>
          </div>
        </form>

        <Separator />

        <!-- Account Information -->
        <div class="space-y-3">
          <h4 class="text-sm font-medium">Account Information</h4>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
            <div class="flex justify-between">
              <span class="text-muted-foreground">Member since:</span>
              <span>{{ formatDate(user?.created_at) }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-muted-foreground">Last updated:</span>
              <span>{{ formatDate(user?.updated_at) }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-muted-foreground">User ID:</span>
              <span class="font-mono">{{ user?.id }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-muted-foreground">Account Status:</span>
              <span class="capitalize">{{ user?.is_approved ? 'Active' : 'Pending Approval' }}</span>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>

    <!-- Password Management Card -->
    <Card>
      <CardHeader>
        <CardTitle class="flex items-center gap-2">
          <Key class="h-5 w-5" />
          Password & Security
        </CardTitle>
        <CardDescription>Change your password to keep your account secure</CardDescription>
      </CardHeader>
      <CardContent>
        <PasswordChangeForm @password-changed="handlePasswordChanged" />
      </CardContent>
    </Card>

    <!-- Department Roles Card (for artists/coordinators) -->
    <Card v-if="showDepartmentRoles">
      <CardHeader>
        <CardTitle class="flex items-center gap-2">
          <Briefcase class="h-5 w-5" />
          Department Specializations
        </CardTitle>
        <CardDescription>Your specialized skills and department assignments across projects</CardDescription>
      </CardHeader>
      <CardContent>
        <div v-if="userProjects.length === 0" class="text-center py-8">
          <Briefcase class="h-12 w-12 mx-auto text-muted-foreground mb-4" />
          <h3 class="text-lg font-medium mb-2">No Project Assignments</h3>
          <p class="text-muted-foreground">You haven't been assigned to any projects yet.</p>
        </div>
        <div v-else class="space-y-4">
          <div v-for="project in userProjects" :key="project.id" class="border rounded-lg p-4">
            <div class="flex items-center justify-between mb-2">
              <h4 class="font-medium">{{ project.name }}</h4>
              <Badge v-if="project.department_role" variant="outline">
                {{ formatDepartmentRole(project.department_role) }}
              </Badge>
              <Badge v-else variant="secondary">No Department Assigned</Badge>
            </div>
            <p class="text-sm text-muted-foreground">{{ project.description || 'No description available' }}</p>
            <div class="flex items-center gap-4 mt-2 text-xs text-muted-foreground">
              <span>Status: {{ formatProjectStatus(project.status) }}</span>
              <span v-if="project.member_count">{{ project.member_count }} members</span>
              <span v-if="project.episode_count">{{ project.episode_count }} episodes</span>
              <span v-if="project.asset_count">{{ project.asset_count }} assets</span>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>

    <!-- API Key Management Card (for developers) -->
    <Card v-if="isDeveloper">
      <CardHeader>
        <CardTitle class="flex items-center gap-2">
          <Key class="h-5 w-5" />
          API Key Management
        </CardTitle>
        <CardDescription>Manage your API keys for external integrations and automation</CardDescription>
      </CardHeader>
      <CardContent class="space-y-4">
        <!-- Create New API Key -->
        <div class="border rounded-lg p-4 space-y-4">
          <h4 class="font-medium">Create New API Key</h4>
          <form @submit.prevent="handleCreateAPIKey" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="space-y-2">
                <Label for="api_key_name">Key Name</Label>
                <Input
                  id="api_key_name"
                  v-model="apiKeyForm.name"
                  placeholder="e.g., Production Pipeline"
                  :disabled="isCreatingAPIKey"
                />
              </div>
              <div class="space-y-2">
                <Label for="api_key_expires">Expires At (Optional)</Label>
                <Input
                  id="api_key_expires"
                  v-model="apiKeyForm.expires_at"
                  type="datetime-local"
                  :disabled="isCreatingAPIKey"
                />
              </div>
            </div>
            
            <div class="space-y-2">
              <Label>Scopes</Label>
              <div class="grid grid-cols-2 md:grid-cols-4 gap-2">
                <div v-for="scope in availableScopes" :key="scope.value" class="flex items-center space-x-2">
                  <Checkbox
                    :id="scope.value"
                    :checked="apiKeyForm.scopes.includes(scope.value)"
                    @update:checked="(checked) => toggleScope(scope.value, checked)"
                    :disabled="isCreatingAPIKey"
                  />
                  <Label :for="scope.value" class="text-sm">{{ scope.label }}</Label>
                </div>
              </div>
            </div>

            <Button 
              type="submit" 
              :disabled="isCreatingAPIKey || !apiKeyForm.name || apiKeyForm.scopes.length === 0"
            >
              <Loader2 v-if="isCreatingAPIKey" class="h-4 w-4 mr-2 animate-spin" />
              <Plus class="h-4 w-4 mr-2" />
              Create API Key
            </Button>
          </form>
        </div>

        <!-- Existing API Keys -->
        <div class="space-y-4">
          <h4 class="font-medium">Your API Keys</h4>
          <div v-if="apiKeys.length === 0" class="text-center py-8 border rounded-lg">
            <Key class="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <h3 class="text-lg font-medium mb-2">No API Keys</h3>
            <p class="text-muted-foreground">Create your first API key to start integrating with external tools.</p>
          </div>
          <div v-else class="space-y-3">
            <div v-for="apiKey in apiKeys" :key="apiKey.id" class="border rounded-lg p-4">
              <div class="flex items-center justify-between mb-2">
                <div>
                  <h5 class="font-medium">{{ apiKey.name }}</h5>
                  <p class="text-sm text-muted-foreground">
                    Created {{ formatDate(apiKey.created_at) }}
                    <span v-if="apiKey.last_used_at"> • Last used {{ formatDate(apiKey.last_used_at) }}</span>
                  </p>
                </div>
                <div class="flex items-center gap-2">
                  <Badge :variant="apiKey.is_active ? 'default' : 'secondary'">
                    {{ apiKey.is_active ? 'Active' : 'Inactive' }}
                  </Badge>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="sm">
                        <MoreHorizontal class="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem @click="handleViewAPIKey(apiKey)">
                        <Eye class="h-4 w-4 mr-2" />
                        View Details
                      </DropdownMenuItem>
                      <DropdownMenuItem 
                        v-if="apiKey.is_active"
                        @click="handleDeactivateAPIKey(apiKey.id)"
                      >
                        <Ban class="h-4 w-4 mr-2" />
                        Deactivate
                      </DropdownMenuItem>
                      <DropdownMenuSeparator />
                      <DropdownMenuItem 
                        class="text-destructive"
                        @click="handleDeleteAPIKey(apiKey.id)"
                      >
                        <Trash2 class="h-4 w-4 mr-2" />
                        Delete
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              </div>
              <div class="flex flex-wrap gap-1">
                <Badge v-for="scope in apiKey.scopes" :key="scope" variant="outline" class="text-xs">
                  {{ scope }}
                </Badge>
              </div>
              <div v-if="apiKey.expires_at" class="mt-2 text-sm text-muted-foreground">
                Expires: {{ formatDate(apiKey.expires_at) }}
              </div>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>

    <!-- New API Key Created Dialog -->
    <Dialog :open="showNewAPIKeyDialog" @update:open="showNewAPIKeyDialog = $event">
      <DialogContent class="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>API Key Created</DialogTitle>
          <DialogDescription>
            Your new API key has been created. Make sure to copy it now as you won't be able to see it again.
          </DialogDescription>
        </DialogHeader>
        <div v-if="newAPIKeyToken" class="space-y-4">
          <div class="space-y-2">
            <Label>API Key Token</Label>
            <div class="flex items-center space-x-2">
              <Input
                :value="newAPIKeyToken"
                readonly
                class="font-mono text-sm"
              />
              <Button
                variant="outline"
                size="sm"
                @click="copyToClipboard(newAPIKeyToken)"
              >
                <Copy class="h-4 w-4" />
              </Button>
            </div>
          </div>
          <Alert>
            <AlertTriangle class="h-4 w-4" />
            <AlertTitle>Important</AlertTitle>
            <AlertDescription>
              Store this API key securely. You won't be able to view it again after closing this dialog.
            </AlertDescription>
          </Alert>
        </div>
        <DialogFooter>
          <Button @click="showNewAPIKeyDialog = false">I've Saved the Key</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <!-- Success Toast -->
    <div v-if="successMessage" class="fixed bottom-4 right-4 z-50">
      <Alert class="w-80 bg-green-50 border-green-200 dark:bg-green-950 dark:border-green-800">
        <CheckCircle class="h-4 w-4 text-green-600 dark:text-green-400" />
        <AlertTitle class="text-green-800 dark:text-green-200">Success</AlertTitle>
        <AlertDescription class="text-green-700 dark:text-green-300">{{ successMessage }}</AlertDescription>
      </Alert>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive, watch } from 'vue'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Separator } from '@/components/ui/separator'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Checkbox } from '@/components/ui/checkbox'
import { User, RefreshCw, AlertCircle, Loader2, CheckCircle, Briefcase, Key, Plus, MoreHorizontal, Eye, Ban, Trash2, Copy, AlertTriangle, Camera, Upload, X } from 'lucide-vue-next'
import { useAuthStore } from '@/stores/auth'
import { useUserStore } from '@/stores/user'
import { apiKeyService, API_KEY_SCOPES, type APIKey } from '@/services/apiKey'
import { projectService, type Project } from '@/services/project'
import { userService } from '@/services/user'
import PasswordChangeForm from '@/components/user/PasswordChangeForm.vue'
import { useToast } from '@/components/ui/toast/use-toast'


// Types are now imported from services

const authStore = useAuthStore()
const userStore = useUserStore()
const { toast } = useToast()

// Local state
const isLoading = ref(false)
const isUpdatingProfile = ref(false)
const isCreatingAPIKey = ref(false)
const isUploadingAvatar = ref(false)
const isRemovingAvatar = ref(false)
const avatarError = ref('')
const error = ref('')
const successMessage = ref('')
const showNewAPIKeyDialog = ref(false)
const newAPIKeyToken = ref('')
const avatarFileInput = ref<HTMLInputElement>()

// API Keys state
const apiKeys = ref<APIKey[]>([])
const userProjects = ref<Project[]>([])

// Forms
const profileForm = reactive({
  first_name: '',
  last_name: ''
})

const apiKeyForm = reactive({
  name: '',
  scopes: [] as string[],
  expires_at: ''
})

// Computed
const user = computed(() => authStore.user)
const isDeveloper = computed(() => authStore.userRole === 'developer')
const showDepartmentRoles = computed(() => 
  authStore.userRole === 'artist' || authStore.userRole === 'coordinator'
)

const userInitials = computed(() => {
  if (!user.value) return ''
  return `${user.value.first_name.charAt(0)}${user.value.last_name.charAt(0)}`.toUpperCase()
})

const hasProfileChanges = computed(() => {
  if (!user.value) return false
  return profileForm.first_name !== user.value.first_name || 
         profileForm.last_name !== user.value.last_name
})

const availableScopes = API_KEY_SCOPES

// Methods
const initializeProfileForm = () => {
  if (user.value) {
    profileForm.first_name = user.value.first_name
    profileForm.last_name = user.value.last_name
  }
}

const refreshData = async () => {
  try {
    isLoading.value = true
    error.value = ''
    
    await authStore.getCurrentUser()
    
    if (isDeveloper.value) {
      await fetchAPIKeys()
    }
    
    if (showDepartmentRoles.value) {
      await fetchUserProjects()
    }
  } catch (err: any) {
    error.value = err.message || 'Failed to refresh data'
  } finally {
    isLoading.value = false
  }
}

const handleUpdateProfile = async () => {
  try {
    isUpdatingProfile.value = true
    error.value = ''
    
    await userStore.updateCurrentUserProfile({
      first_name: profileForm.first_name,
      last_name: profileForm.last_name
    })
    
    // Refresh auth store to get updated user data
    await authStore.getCurrentUser()
    
    showSuccessMessage('Profile updated successfully')
  } catch (err: any) {
    error.value = err.message || 'Failed to update profile'
  } finally {
    isUpdatingProfile.value = false
  }
}

const fetchAPIKeys = async () => {
  try {
    apiKeys.value = await apiKeyService.getAPIKeys()
  } catch (err) {
    console.error('Failed to fetch API keys:', err)
  }
}

const fetchUserProjects = async () => {
  try {
    userProjects.value = await projectService.getUserProjects()
  } catch (err) {
    console.error('Failed to fetch user projects:', err)
  }
}

const handleCreateAPIKey = async () => {
  try {
    isCreatingAPIKey.value = true
    error.value = ''
    
    const result = await apiKeyService.createAPIKey({
      name: apiKeyForm.name,
      scopes: apiKeyForm.scopes,
      expires_at: apiKeyForm.expires_at || undefined
    })
    
    newAPIKeyToken.value = result.token
    showNewAPIKeyDialog.value = true
    
    // Reset form
    apiKeyForm.name = ''
    apiKeyForm.scopes = []
    apiKeyForm.expires_at = ''
    
    showSuccessMessage('API key created successfully')
    await fetchAPIKeys()
  } catch (err: any) {
    error.value = err.response?.data?.detail || err.message || 'Failed to create API key'
  } finally {
    isCreatingAPIKey.value = false
  }
}

const toggleScope = (scope: string, checked: boolean | 'indeterminate') => {
  const isChecked = checked === true
  if (isChecked) {
    if (!apiKeyForm.scopes.includes(scope)) {
      apiKeyForm.scopes.push(scope)
    }
  } else {
    const index = apiKeyForm.scopes.indexOf(scope)
    if (index > -1) {
      apiKeyForm.scopes.splice(index, 1)
    }
  }
}

const handleViewAPIKey = (apiKey: APIKey) => {
  // TODO: Implement API key detail view
  console.log('View API key:', apiKey)
}

const handleDeactivateAPIKey = async (apiKeyId: number) => {
  try {
    await apiKeyService.updateAPIKey(apiKeyId, { is_active: false })
    showSuccessMessage('API key deactivated')
    await fetchAPIKeys()
  } catch (err: any) {
    error.value = err.response?.data?.detail || err.message || 'Failed to deactivate API key'
  }
}

const handleDeleteAPIKey = async (apiKeyId: number) => {
  try {
    await apiKeyService.deleteAPIKey(apiKeyId)
    showSuccessMessage('API key deleted')
    await fetchAPIKeys()
  } catch (err: any) {
    error.value = err.response?.data?.detail || err.message || 'Failed to delete API key'
  }
}

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    showSuccessMessage('Copied to clipboard')
  } catch (err) {
    console.error('Failed to copy to clipboard:', err)
  }
}

const formatDate = (dateString?: string) => {
  if (!dateString) return 'Unknown'
  return new Date(dateString).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

const formatRole = (role?: string) => {
  if (!role) return 'Unknown'
  return role.charAt(0).toUpperCase() + role.slice(1)
}

const formatDepartmentRole = (role: string) => {
  return role.charAt(0).toUpperCase() + role.slice(1)
}

const formatProjectStatus = (status: string) => {
  return status.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')
}

const showSuccessMessage = (message: string) => {
  successMessage.value = message
  setTimeout(() => {
    successMessage.value = ''
  }, 3000)
}

import { useAvatarUrl } from '@/composables/useAvatarUrl'

const { getAvatarUrl, getInitialsAvatarUrl } = useAvatarUrl()

const triggerAvatarUpload = () => {
  avatarFileInput.value?.click()
}

const validateAvatarFile = (file: File): boolean => {
  avatarError.value = ''

  // Check file type
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
  if (!allowedTypes.includes(file.type)) {
    avatarError.value = 'Invalid file format. Please upload JPG, PNG, GIF, or WEBP.'
    return false
  }

  // Check file size (5MB max)
  const maxSize = 5 * 1024 * 1024 // 5MB in bytes
  if (file.size > maxSize) {
    avatarError.value = 'File too large. Maximum size is 5MB.'
    return false
  }

  return true
}

const handleAvatarSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  if (!validateAvatarFile(file)) {
    toast({
      title: 'Invalid File',
      description: avatarError.value,
      variant: 'destructive',
    })
    return
  }

  // Upload immediately after selection
  isUploadingAvatar.value = true
  avatarError.value = ''

  try {
    const response = await userService.uploadAvatar(file)
    
    // Update auth store with new avatar URL
    if (authStore.user) {
      authStore.user.avatar_url = response.avatar_url
    }
    
    toast({
      title: 'Success',
      description: 'Avatar uploaded successfully',
    })
    
  } catch (error: any) {
    avatarError.value = error.response?.data?.detail || 'Failed to upload avatar'
    toast({
      title: 'Error',
      description: avatarError.value,
      variant: 'destructive',
    })
  } finally {
    isUploadingAvatar.value = false
    // Reset file input
    if (avatarFileInput.value) {
      avatarFileInput.value.value = ''
    }
  }
}

const handleRemoveAvatar = async () => {
  if (!confirm('Are you sure you want to remove your avatar?')) {
    return
  }

  isRemovingAvatar.value = true
  avatarError.value = ''

  try {
    await userService.removeAvatar()
    
    // Update auth store
    if (authStore.user) {
      authStore.user.avatar_url = null
    }
    
    toast({
      title: 'Success',
      description: 'Avatar removed successfully',
    })
  } catch (error: any) {
    avatarError.value = error.response?.data?.detail || 'Failed to remove avatar'
    toast({
      title: 'Error',
      description: avatarError.value,
      variant: 'destructive',
    })
  } finally {
    isRemovingAvatar.value = false
  }
}

const handlePasswordChanged = () => {
  showSuccessMessage('Password changed successfully')
}

// Lifecycle
onMounted(() => {
  initializeProfileForm()
  refreshData()
})

// Watch for user changes
watch(user, () => {
  initializeProfileForm()
}, { deep: true })
</script>