import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api } from '@/api'

export interface User {
  id: string
  email: string
  role: 'chef' | 'disponent' | 'mitarbeiter'
  first_name: string
  last_name: string
  org_id: string
}

export interface Organization {
  id: string
  name: string
  slug: string
  logo_url: string | null
  settings?: Record<string, unknown>
}

export interface Subscription {
  status: 'trial' | 'active' | 'paused' | 'expired' | 'cancelled' | 'free'
  plan: 'starter' | 'business' | 'enterprise'
  trialEndsAt: string | null
  subscriptionEndsAt: string | null
  daysRemaining: number | null
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const organization = ref<Organization | null>(null)
  const subscription = ref<Subscription | null>(null)
  const accessToken = ref<string | null>(localStorage.getItem('accessToken'))
  const refreshToken = ref<string | null>(localStorage.getItem('refreshToken'))
  const orgSlug = ref<string>(localStorage.getItem('orgSlug') || '')

  const isAuthenticated = computed(() => !!user.value && !!accessToken.value)
  const hasStoredToken = computed(() => !!accessToken.value)
  const isChef = computed(() => user.value?.role === 'chef')
  const isDisponent = computed(() => user.value?.role === 'disponent')
  const isMitarbeiter = computed(() => user.value?.role === 'mitarbeiter')
  const canManageUsers = computed(() => isChef.value || isDisponent.value)
  const canManageOrders = computed(() => isChef.value || isDisponent.value)
  const fullName = computed(() => user.value ? `${user.value.first_name} ${user.value.last_name}` : '')
  const orgName = computed(() => organization.value?.name || '')
  const orgLogo = computed(() => organization.value?.logo_url || null)
  
  // Subscription computed
  const isFreeAccount = computed(() => subscription.value?.status === 'free')
  const isTrialActive = computed(() => subscription.value?.status === 'trial' && (subscription.value?.daysRemaining ?? 0) > 0)
  const isSubscriptionActive = computed(() => 
    subscription.value?.status === 'active' || 
    subscription.value?.status === 'free' || 
    isTrialActive.value
  )
  const isSubscriptionExpired = computed(() => 
    !isFreeAccount.value && (
      subscription.value?.status === 'expired' || 
      subscription.value?.status === 'paused' ||
      (subscription.value?.status === 'trial' && (subscription.value?.daysRemaining ?? 0) <= 0)
    )
  )
  const trialDaysRemaining = computed(() => subscription.value?.daysRemaining ?? null)
  const showTrialWarning = computed(() => isTrialActive.value && (trialDaysRemaining.value ?? 0) <= 7)

  function setTokens(access: string, refresh: string) {
    accessToken.value = access
    refreshToken.value = refresh
    localStorage.setItem('accessToken', access)
    localStorage.setItem('refreshToken', refresh)
  }

  function setOrgSlug(slug: string) {
    orgSlug.value = slug
    localStorage.setItem('orgSlug', slug)
  }

  function clearAuth() {
    user.value = null
    organization.value = null
    subscription.value = null
    accessToken.value = null
    refreshToken.value = null
    localStorage.removeItem('accessToken')
    localStorage.removeItem('refreshToken')
  }

  async function login(email: string, password: string, org: string) {
    const response = await api.post('/auth/login', {
      email,
      password,
      org_slug: org
    })
    
    setTokens(response.data.accessToken, response.data.refreshToken)
    setOrgSlug(org)
    user.value = response.data.user
    
    return response.data
  }

  async function register(data: {
    email: string
    password: string
    first_name: string
    last_name: string
    phone?: string
    org_slug: string
  }) {
    const response = await api.post('/auth/register', data)
    return response.data
  }

  async function logout() {
    try {
      await api.post('/auth/logout')
    } catch {
      // Ignore errors
    }
    clearAuth()
  }

  async function fetchCurrentUser() {
    try {
      const response = await api.get('/auth/me')
      user.value = response.data.user
      subscription.value = response.data.subscription
      // Also fetch organization info
      await fetchOrganization()
    } catch {
      clearAuth()
    }
  }

  async function fetchOrganization() {
    try {
      const response = await api.get('/organizations/current')
      organization.value = response.data.organization
    } catch {
      // Ignore errors - org info is optional
    }
  }

  function setOrgLogo(logoUrl: string | null) {
    if (organization.value) {
      organization.value.logo_url = logoUrl
    }
  }

  async function refreshAccessToken() {
    if (!refreshToken.value) {
      throw new Error('No refresh token')
    }
    
    const response = await api.post('/auth/refresh', {
      refreshToken: refreshToken.value
    })
    
    accessToken.value = response.data.accessToken
    localStorage.setItem('accessToken', response.data.accessToken)
    
    return response.data.accessToken
  }

  return {
    user,
    organization,
    subscription,
    accessToken,
    refreshToken,
    orgSlug,
    isAuthenticated,
    hasStoredToken,
    isChef,
    isDisponent,
    isMitarbeiter,
    canManageUsers,
    canManageOrders,
    fullName,
    orgName,
    orgLogo,
    isFreeAccount,
    isTrialActive,
    isSubscriptionActive,
    isSubscriptionExpired,
    trialDaysRemaining,
    showTrialWarning,
    login,
    register,
    logout,
    fetchCurrentUser,
    fetchOrganization,
    refreshAccessToken,
    setOrgSlug,
    setOrgLogo
  }
})
