<!-- src/pages/employee/profile/home.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md:px-10 py-4">
      <!-- Breadcrumbs -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li>Employees</li>
          <li>Profile</li>
        </ul>
      </div>

      <!-- Loading State -->
      <div v-if="!loaded" class="text-center p-10">
        <span class="loading loading-spinner loading-lg"></span>
      </div>

      <!-- Main Content -->
      <div v-else>
        <!-- Employee Header Card -->
        <div class="bg-neutral rounded-lg p-6 mt-6">
          <div class="flex flex-col md:flex-row gap-6">
            
            <!-- Left Side: Avatar and Name -->
            <div class="flex-none flex flex-col items-center md:items-start text-center md:text-left">
              <div class="avatar">
                <div class="w-32 rounded-full ring ring-primary ring-offset-base-100 ring-offset-2">
                  <img src="../../../assets/images/user_placeholder.png" alt="Employee Avatar" />
                </div>
              </div>
              <h1 class="text-2xl font-bold mt-4">{{ employee.employee_first_name }} {{ employee.employee_last_name }}</h1>
              <span class="badge badge-ghost mt-1">{{ employeeTypeName }}</span>
              <router-link :to="{ name: 'employeeEdit', params: { id: employee.id } }" class="btn btn-sm btn-secondary mt-4">
                Edit Employee
              </router-link>
            </div>

            <!-- Right Side: Details Grid -->
            <div class="flex-grow grid grid-cols-1 sm:grid-cols-2 gap-6 pt-4 border-t md:border-t-0 md:border-l border-base-100 md:pl-6">
              <div>
                <h3 class="font-bold text-sm uppercase text-gray-400">Contact Information</h3>
                <div class="mt-2 space-y-1 text-sm">
                  <p>{{ employee.employee_phone_number }}</p>
                  <p class="link link-hover">{{ employee.employee_email }}</p>
                </div>
              </div>
              <div>
                <h3 class="font-bold text-sm uppercase text-gray-400">Address</h3>
                <div class="mt-2 space-y-1 text-sm">
                  <p>{{ employee.employee_address }}</p>
                  <p v-if="employee.employee_apt && employee.employee_apt !== 'None'">{{ employee.employee_apt }}</p>
                  <p>{{ employee.employee_town }}, {{ employeeStateName }} {{ employee.employee_zip }}</p>
                </div>
              </div>
              <div>
                <h3 class="font-bold text-sm uppercase text-gray-400">Employment Dates</h3>
                <div class="mt-2 space-y-1 text-sm">
                  <p><strong>Start Date:</strong> {{ employee.employee_start_date || 'N/A' }}</p>
                  <p><strong>End Date:</strong> {{ employee.employee_end_date || 'N/A' }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Statistics Card -->
        <div class="bg-neutral rounded-lg p-6 mt-6">
          <h2 class="text-xl font-bold mb-4">Delivery Statistics</h2>
          <div class="stats stats-vertical lg:stats-horizontal shadow bg-base-100 w-full">
            <div class="stat">
              <div class="stat-title">Total Deliveries</div>
              <div class="stat-value">{{ total_deliviers_done }}</div>
            </div>
            <div class="stat">
              <div class="stat-title">Total Gallons</div>
              <div class="stat-value">{{ total_gallons_delivered }}</div>
              <div class="stat-desc">Delivered</div>
            </div>
            <div class="stat">
              <div class="stat-title">Total Primes</div>
              <div class="stat-value text-error">{{ total_primes }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import authHeader from '../../../services/auth.header'

export default defineComponent({
  name: 'employeeProfile',
  components: {
  },
  data() {
    return {
      user: null,
      loaded: false,
      employee: {
        id: '',
        employee_last_name: "",
        employee_first_name: "",
        employee_town: "",
        employee_address: "",
        employee_apt: "",
        employee_zip: "",
        employee_phone_number: "",
        employee_start_date: "",
        employee_end_date: "",
        employee_type: '',
        employee_state: '',
        employee_email: '', // Added for completeness
      },
      total_deliviers_done: 0,
      total_gallons_delivered: 0,
      total_primes: 0,
    }
  },
  computed: {
    employeeTypeName(): string {
      const typeMap: Record<string, string> = {
        '0': 'Owner', '1': 'Manager', '2': 'Secretary', '3': 'Office',
        '4': 'Driver', '5': 'Tech', '6': 'Contractor', '7': 'Cash Driver', '8': 'Driver/Tech'
      };
      return typeMap[this.employee.employee_type] || 'Unknown Role';
    },
    employeeStateName(): string {
      const stateMap: Record<string, string> = {
        '0': 'MA', '1': 'RI', '2': 'NH', '3': 'ME', '4': 'VT', '5': 'CT', '6': 'NY'
      };
      return stateMap[this.employee.employee_state] || 'Unknown State';
    }
  },
  created() {
    this.userStatus();
    this.getEmployee(this.$route.params.id);
  },
  watch: {
    // Watch the route to refetch data if the employee ID changes
    '$route.params.id'(newId) {
      if (newId) {
        this.getEmployee(newId);
      }
    },
  },
  methods: {
    userStatus() {
      const path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          if (response.data.ok) {
            this.user = response.data.user;
          }
        })
        .catch(() => {
          this.user = null;
        });
    },
    getEmployee(userid: any) {
      this.loaded = false; // Set loading state
      const path = `${import.meta.env.VITE_BASE_URL}/employee/${userid}`;
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          if (response.data) {
            this.employee = response.data;
            // Fetch stats only after we confirm we have a valid employee
            if (this.employee.id) {
              this.getEmployeeStatsDeliveriesDone(this.employee.id);
              this.getEmployeeStatsGallonsDone(this.employee.id);
              this.getEmployeeStatsPrimesDone(this.employee.id);
            }
          }
        })
        .catch((error: any) => {
          console.error("Failed to fetch employee data:", error);
        })
        .finally(() => {
          this.loaded = true; // End loading state
        });
    },
    getEmployeeStatsDeliveriesDone(userid: string) {
      const path = `${import.meta.env.VITE_BASE_URL}/stats/delivery/total/${userid}`;
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          this.total_deliviers_done = response.data.data || 0;
        });
    },
    getEmployeeStatsGallonsDone(userid: string) {
      const path = `${import.meta.env.VITE_BASE_URL}/stats/gallons/total/${userid}`;
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          this.total_gallons_delivered = response.data.data || 0;
        });
    },
    getEmployeeStatsPrimesDone(userid: string) {
      const path = `${import.meta.env.VITE_BASE_URL}/stats/primes/total/${userid}`;
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          this.total_primes = response.data.data || 0;
        });
    },
  },
});
</script>