<!-- src/pages/customer/profile/TankEstimation.vue -->
<template>
  <div class="card-glass p-4 border-0">
    <h3 class="font-semibold mb-4 flex items-center gap-2">
      <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
          d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
      </svg>
      Fuel Tank Estimation
    </h3>

    <div v-if="loading" class="flex justify-center items-center py-8">
      <span class="loading loading-spinner loading-lg"></span>
    </div>

    <div v-else-if="error" class="text-center py-4">
      <p class="text-sm text-red-600">
        <span class="font-medium">Estimation Error:</span> {{ error }}
      </p>
    </div>

    <div v-else-if="estimation">
      <div class="space-y-4">
        <!-- Tank Level Display -->
        <div>
          <div class="flex justify-between items-center mb-2">
            <label class="label-text font-medium">Current Tank Level</label>
            <span class="text-sm text-gray-500">{{ Math.round(estimation.estimated_gallons) }} / {{ Math.round(estimation.tank_size) }} gal</span>
          </div>

          <div>
            <progress
              class="progress w-full"
              :value="estimation.estimated_gallons"
              :max="estimation.tank_size"
              :class="{
                'progress-success': getTankLevelPercentage() > 60,
                'progress-warning': getTankLevelPercentage() >= 25 && getTankLevelPercentage() <= 60,
                'progress-error': getTankLevelPercentage() < 25
              }"
            ></progress>

            <div class="flex justify-between text-xs text-gray-500 mt-1">
              <span>Empty</span>
              <span>{{ Math.round(getTankLevelPercentage()) }}% Full</span>
              <span>Full</span>
            </div>
          </div>
        </div>

        <!-- Days Until Empty + Last Fill -->
        <div class="grid grid-cols-2 gap-4">
          <div v-if="estimation.days_remaining != null">
            <label class="label-text font-medium">Days Until Empty</label>
            <div class="mt-1">
              <span v-if="estimation.days_remaining >= 999" class="text-lg font-mono text-base-content/40">N/A</span>
              <span v-else class="text-lg font-mono font-bold" :class="{
                'text-error': estimation.days_remaining <= 7,
                'text-warning': estimation.days_remaining > 7 && estimation.days_remaining <= 14,
                'text-success': estimation.days_remaining > 14
              }">{{ estimation.days_remaining }} days</span>
            </div>
          </div>
          <div>
            <label class="label-text font-medium">Last Fill</label>
            <div class="mt-1">
              <span v-if="estimation.last_fill" class="text-lg font-mono font-bold">{{ formatDate(estimation.last_fill) }}</span>
              <span v-else class="text-lg font-mono text-base-content/40">N/A</span>
            </div>
          </div>
        </div>

        <!-- Gallons to Fill + Days Since Last Fill -->
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="label-text font-medium">Gallons to Fill</label>
            <div class="mt-1">
              <span class="text-lg font-mono font-bold">{{ Math.max(0, getMaxFill(estimation.tank_size) - Math.round(estimation.estimated_gallons)) }} gal</span>
            </div>
          </div>
          <div>
            <label class="label-text font-medium">Days Since Last Fill</label>
            <div class="mt-1">
              <span v-if="estimation.last_fill" class="text-lg font-mono font-bold">{{ daysSinceLastFill(estimation.last_fill) }} days</span>
              <span v-else class="text-lg font-mono text-base-content/40">N/A</span>
            </div>
          </div>
        </div>

        <!-- Usage Information -->
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="label-text font-medium">Usage Factor</label>
            <div class="text-lg font-mono">{{ getScalingFactorCategory(sliderValue) }}</div>
            <div class="text-xs text-gray-500">{{ sliderValue.toFixed(4) }} gal/degree day</div>
          </div>

          <div>
            <label class="label-text font-medium">Daily Usage</label>
            <div class="text-lg font-mono">{{ computedGallonsPerDay }}</div>
            <div class="text-xs text-gray-500">Gallons per day</div>
          </div>
        </div>

        <!-- K-Factor Slider (admin only) -->
        <div v-if="currentUserId === 0" class="pt-2 border-t">
          <label class="label-text font-medium">Adjust Usage Factor (K-Factor)</label>
          <div class="flex items-center gap-3 mt-2">
            <span class="text-xs text-gray-500 w-8">0.01</span>
            <input
              type="range"
              min="0.01"
              max="1.00"
              step="0.001"
              class="range range-sm range-primary flex-1"
              v-model.number="sliderValue"
              @input="onSliderInput"
            />
            <span class="text-xs text-gray-500 w-8">1.00</span>
          </div>
          <div class="flex justify-between items-center mt-1">
            <span class="text-xs text-gray-500">{{ sliderValue.toFixed(4) }} gal/degree day</span>
            <span v-if="saving" class="text-xs text-info">Saving...</span>
            <span v-else-if="saveSuccess" class="text-xs text-success">Saved</span>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="text-center py-8 text-gray-500">
      <svg class="w-12 h-12 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
          d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
      </svg>
      <p>No fuel estimation data available</p>
      <p class="text-xs mt-1">Run fuel estimation to see tank levels</p>
    </div>
  </div>
</template>

<script setup lang="ts">

import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { customerService } from '../../../services/customerService'
import { deliveryService } from '../../../services/deliveryService'
import dayjs from 'dayjs'
import { AxiosResponse, AxiosError, CustomersResponse } from '../../../types/models'

interface FuelEstimation {
  id: number;
  customer_id: number;
  total_deliveries: number;
  customer_full_name: string;
  account_number: string;
  address: string;
  estimated_gallons: number;
  tank_size: number;
  scaling_factor: number | null;
  confidence_score: number | null;
  k_factor_source: string | null;
  days_remaining: number | null;
  gallons_per_day: number | null;
  avg_hdd: number | null;
  hot_water_summer: number | null;
  last_5_deliveries: Array<{
    fill_date: string;
    gallons_delivered: number;
    price_per_gallon: number | null;
    total_amount_customer: number;
  }>;
  last_fill?: string | null;
}

// Props
const props = defineProps<{
  customerId: number
  currentUserId: number
}>()

// Reactive data
const estimation = ref<FuelEstimation | null>(null)
const loading = ref(true)
const error = ref<string | null>(null)
const isAutomatic = ref(false)
const sliderValue = ref(0.12)
const saving = ref(false)
const saveSuccess = ref(false)
let debounceTimer: ReturnType<typeof setTimeout> | null = null
let saveSuccessTimer: ReturnType<typeof setTimeout> | null = null

// Computed: real-time gallons per day from slider
const computedGallonsPerDay = computed(() => {
  const avgHdd = estimation.value?.avg_hdd ?? 20
  const hotWater = estimation.value?.hot_water_summer === 1 ? 1.0 : 0
  const daily = sliderValue.value * avgHdd + hotWater
  return daily.toFixed(1)
})

// Lifecycle
onMounted(() => {
  fetchEstimation()
})

// Watchers
watch(() => props.customerId, (newId, oldId) => {
  if (newId !== oldId) {
    console.log('Customer ID changed from', oldId, 'to', newId)
    fetchEstimation()
  }
})

// Functions
const fetchEstimation = async () => {
  loading.value = true
  error.value = null
  estimation.value = null // Clear previous data

  try {
    console.log('Fetching estimation for customer ID:', props.customerId)

    // First check if customer is automatic
    console.log('Checking customer type')
    const customerResponse = await customerService.getById(props.customerId)
    const customerData = customerResponse.data.customer || customerResponse.data;
    isAutomatic.value = customerData.customer_automatic === 1
    console.log('Customer automatic status:', isAutomatic.value, customerData)

    let response: AxiosResponse<any>;
    if (isAutomatic.value) {
      console.log('Fetching automatic data')
      response = await deliveryService.auto.getByCustomer(props.customerId)
    } else {
      console.log('Fetching customer estimation data')
      response = await deliveryService.auto.estimateGallons(props.customerId)
    }
    console.log('API Response:', response.data)

    if (response.data.error) {
      error.value = response.data.error
      console.error('API returned error:', response.data.error)
    } else {
      if (isAutomatic.value) {
        // Transform automatic delivery data to match our interface
        if (response.data && response.data.id) {
          const autoData = response.data
          console.log('Processing automatic data:', autoData)
          estimation.value = {
            id: autoData.id,
            customer_id: autoData.customer_id,
            total_deliveries: 0,
            customer_full_name: autoData.customer_full_name,
            account_number: autoData.account_number,
            address: autoData.customer_address,
            estimated_gallons: autoData.estimated_gallons_left,
            tank_size: autoData.tank_size,
            scaling_factor: autoData.house_factor,
            confidence_score: autoData.confidence_score ?? null,
            k_factor_source: autoData.k_factor_source ?? null,
            days_remaining: autoData.days_remaining ?? null,
            gallons_per_day: autoData.gallons_per_day ?? null,
            avg_hdd: autoData.avg_hdd ?? null,
            hot_water_summer: autoData.hot_water_summer ?? null,
            last_5_deliveries: [],
            last_fill: autoData.last_fill
          }
          console.log('Set automatic estimation:', estimation.value)
        } else {
          console.warn('No automatic delivery data found for customer', props.customerId)
          error.value = 'No automatic delivery data available'
        }
      } else {
        console.log('Setting customer estimation:', response.data)
        estimation.value = response.data
      }

      // Initialize slider from loaded data
      if (estimation.value?.scaling_factor != null) {
        sliderValue.value = Math.max(0.01, Math.min(1.0, estimation.value.scaling_factor))
      }
    }
  } catch (err: unknown) {
    const errorObj = err as AxiosError<any>;
    console.error('Failed to fetch fuel estimation:', errorObj)
    if (errorObj.response?.status === 404) {
      error.value = 'Customer data not found'
    } else if (errorObj.response?.data?.error) {
      error.value = errorObj.response.data.error
    } else {
      error.value = 'Failed to load fuel estimation data'
    }
  } finally {
    loading.value = false
  }
}

const TANK_MAX_FILLS: Record<number, number> = {
  275: 240,
  320: 275,
  330: 280,
  500: 475,
  550: 500,
}

const getMaxFill = (tankSize: number): number => {
  return TANK_MAX_FILLS[Math.round(tankSize)] ?? Math.round(tankSize * 0.9)
}

const getTankLevelPercentage = (): number => {
  if (!estimation.value || !estimation.value.tank_size || estimation.value.tank_size === 0) {
    return 0
  }
  return (estimation.value.estimated_gallons / estimation.value.tank_size) * 100
}

// Slider input handler with debounce
const onSliderInput = () => {
  saveSuccess.value = false
  if (debounceTimer) clearTimeout(debounceTimer)
  debounceTimer = setTimeout(() => saveHouseFactor(), 500)
}

const saveHouseFactor = async () => {
  saving.value = true
  saveSuccess.value = false
  try {
    if (isAutomatic.value) {
      await deliveryService.auto.updateHouseFactor(props.customerId, { house_factor: sliderValue.value })
    } else {
      await deliveryService.auto.updateCustomerHouseFactor(props.customerId, { house_factor: sliderValue.value })
    }
    saveSuccess.value = true
    if (saveSuccessTimer) clearTimeout(saveSuccessTimer)
    saveSuccessTimer = setTimeout(() => { saveSuccess.value = false }, 2000)
  } catch (err) {
    console.error('Failed to save house factor:', err)
  } finally {
    saving.value = false
  }
}

onUnmounted(() => {
  if (debounceTimer) clearTimeout(debounceTimer)
  if (saveSuccessTimer) clearTimeout(saveSuccessTimer)
})

const getScalingFactorCategory = (scalingFactor: number | null): string => {
  if (scalingFactor === null || scalingFactor === undefined) {
    return 'N/A'
  }

  if (scalingFactor < 0.05) {
    return 'Very Low'
  } else if (scalingFactor < 0.1) {
    return 'Low'
  } else if (scalingFactor < 0.2) {
    return 'Normal'
  } else if (scalingFactor < 0.5) {
    return 'High'
  } else {
    return 'Very High'
  }
}

const formatDate = (dateString: string): string => {
  if (!dateString) return 'N/A'
  return dayjs(dateString).format('MMM D, YYYY')
}

const daysSinceLastFill = (dateString: string): number => {
  return dayjs().diff(dayjs(dateString), 'day')
}
</script>
