<template>
  <div>
    <v-container fluid>
      <!-- Header Section -->
      <v-row class="mb-6">
        <v-col cols="12" md="8">
          <h1 class="text-h4 font-weight-bold mb-2">
            Port Nimara Berth Interests
          </h1>
          <p class="text-subtitle-1 text-grey-darken-1">
            Manage and track all potential client interests
          </p>
        </v-col>
        <v-col cols="12" md="4" class="d-flex justify-end align-center">
          <v-btn
            color="primary"
            size="large"
            @click="showCreateModal = true"
            prepend-icon="mdi-plus"
            variant="tonal"
          >
            Add Interest
          </v-btn>
        </v-col>
      </v-row>

      <!-- Search and Filters Section -->
      <v-row class="mb-4">
        <v-col cols="12" md="6">
          <v-text-field
            v-model="search"
            label="Search interests..."
            placeholder="Search by name, yacht, email, phone..."
            prepend-inner-icon="mdi-magnify"
            variant="outlined"
            density="comfortable"
            clearable
            hide-details
            class="search-field"
          >
            <template v-slot:append-inner>
              <v-fade-transition>
                <v-chip
                  v-if="filteredInterests.length !== interests?.list?.length"
                  size="small"
                  color="primary"
                  variant="tonal"
                >
                  {{ filteredInterests.length }} results
                </v-chip>
              </v-fade-transition>
            </template>
          </v-text-field>
        </v-col>
        <v-col cols="12" md="6" class="d-flex justify-end align-center gap-2">
          <v-btn
            v-if="hasActiveFilters"
            variant="text"
            color="primary"
            size="small"
            @click="clearAllFilters"
            prepend-icon="mdi-filter-off"
          >
            Clear Filters
          </v-btn>
          <v-chip-group
            v-model="selectedSalesLevel"
            selected-class="text-primary"
            column
          >
            <v-chip
              filter
              variant="outlined"
              size="small"
              value="all"
            >
              All Levels
            </v-chip>
            <v-chip
              filter
              variant="outlined"
              size="small"
              value="qualified"
            >
              Qualified
            </v-chip>
            <v-chip
              filter
              variant="outlined"
              size="small"
              value="loi"
            >
              LOI Sent
            </v-chip>
            <v-chip
              filter
              variant="outlined"
              size="small"
              value="reserved"
            >
              Reserved
            </v-chip>
          </v-chip-group>
        </v-col>
      </v-row>

      <!-- Data Table -->
      <v-card elevation="0" class="rounded-lg">
        <div class="table-container">
          <v-data-table
            :headers="headers"
            :items="filteredInterests"
            :search="search"
            :sort-by="[{ key: 'Created At', order: 'desc' }, { key: 'Full Name', order: 'asc' }]"
            must-sort
            hover
            :loading="loading"
            loading-text="Loading interests..."
            :items-per-page="50"
            :items-per-page-options="[10, 20, 50, 100]"
            class="modern-table"
          >
          <template #item="{ item }">
            <tr @click="handleRowClick(item)" class="table-row">
              <td>
                <div class="d-flex align-center">
                  <v-avatar size="32" color="primary" class="mr-3">
                    <span class="text-white text-caption font-weight-bold">
                      {{ getInitials(item["Full Name"]) }}
                    </span>
                  </v-avatar>
                  <div class="flex-grow-1">
                    <div class="d-flex align-center gap-2">
                      <span class="font-weight-medium">{{ item["Full Name"] }}</span>
                      <v-tooltip v-if="item['Extra Comments']" location="bottom">
                        <template #activator="{ props }">
                          <v-icon
                            v-bind="props"
                            size="small"
                            color="orange"
                          >
                            mdi-comment-text
                          </v-icon>
                        </template>
                        <span>{{ item["Extra Comments"] }}</span>
                      </v-tooltip>
                    </div>
                    <div class="text-caption text-grey-darken-1">{{ item["Email Address"] }}</div>
                  </div>
                </div>
              </td>
              <td>
                <InterestSalesBadge
                  :salesProcessLevel="item['Sales Process Level']"
                />
              </td>
              <td>
                <EOIStatusBadge
                  v-if="item['EOI Status']"
                  :eoiStatus="item['EOI Status']"
                />
                <span v-else class="text-grey-darken-1">—</span>
              </td>
              <td>
                <ContractStatusBadge
                  v-if="item['Contract Status']"
                  :contractStatus="item['Contract Status']"
                />
                <span v-else class="text-grey-darken-1">—</span>
              </td>
              <td><LeadCategoryBadge :leadCategory="item['Lead Category']" /></td>
              <td>
                <div class="text-caption">
                  <div>{{ formatDate(item["Created At"]) }}</div>
                  <div class="text-grey-darken-1">{{ getRelativeTime(item["Created At"]) }}</div>
                </div>
              </td>
            </tr>
          </template>


          </v-data-table>
        </div>
      </v-card>
    </v-container>

    <!-- Interest Details Modal -->
    <InterestDetailsModal
      v-model="showModal"
      :selected-interest="selectedInterest"
      @save="handleSaveInterest"
    />

    <!-- Create Interest Modal -->
    <CreateInterestModal
      v-model="showCreateModal"
      @created="handleInterestCreated"
    />
  </div>
</template>

<script lang="ts" setup>
import LeadCategoryBadge from "~/components/LeadCategoryBadge.vue";
import InterestSalesBadge from "~/components/InterestSalesBadge.vue";
import InterestDetailsModal from "~/components/InterestDetailsModal.vue";
import CreateInterestModal from "~/components/CreateInterestModal.vue";
import EOIStatusBadge from "~/components/EOIStatusBadge.vue";
import ContractStatusBadge from "~/components/ContractStatusBadge.vue";
import { useFetch } from "#app";
import { ref, computed } from "vue";
import type { Interest } from "@/utils/types";

useHead({
  title: "Interest List",
});

const user = useDirectusUser();
const router = useRouter();
const loading = ref(true);
const showModal = ref(false);
const showCreateModal = ref(false);
const selectedInterest = ref<Interest | null>(null);
const selectedSalesLevel = ref('all');

const { data: interests, refresh } = useFetch<InterestsResponse>("/api/get-interests", {
  headers: {
    "x-tag": user.value?.email ? "094ut234" : "pjnvü1230",
  },
  onResponse() {
    loading.value = false;
  },
  onResponseError() {
    loading.value = false;
  },
});

const search = ref("");

const handleRowClick = (interest: Interest) => {
  selectedInterest.value = { ...interest };
  showModal.value = true;
};

// Event handlers for the modal
const handleSaveInterest = async (interest: Interest) => {
  // Refresh the interests data to reflect the updates
  loading.value = true;
  await refresh();
  loading.value = false;
};

const handleInterestCreated = async (interest: Interest) => {
  // Refresh the interests data to include the new interest
  loading.value = true;
  await refresh();
  loading.value = false;
};

const headers = [
  { title: "Contact", key: "Full Name", sortable: true, width: "25%" },
  { title: "Sales Status", key: "Sales Process Level", sortable: true },
  { title: "EOI Status", key: "EOI Status", sortable: true },
  { title: "Contract", key: "Contract Status", sortable: true },
  { title: "Category", key: "Lead Category", sortable: true },
  { title: "Created", key: "Created At", sortable: true },
];

// Check if any filters are active
const hasActiveFilters = computed(() => {
  return search.value !== '' || selectedSalesLevel.value !== 'all';
});

// Clear all filters
const clearAllFilters = () => {
  search.value = '';
  selectedSalesLevel.value = 'all';
};

const formatDate = (dateString: string) => {
  if (!dateString) return "-";
  
  try {
    // Handle DD-MM-YYYY format
    const parts = dateString.split("-");
    if (parts.length === 3) {
      const day = parseInt(parts[0], 10);
      const month = parseInt(parts[1], 10) - 1; // Month is 0-indexed in JavaScript
      const year = parseInt(parts[2], 10);
      
      const date = new Date(year, month, day);
      
      // Check if the date is valid
      if (isNaN(date.getTime())) {
        console.warn("Invalid date format:", dateString);
        return "-";
      }
      
      return date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "short",
        day: "numeric",
      });
    } else {
      // Fallback to standard Date parsing
      const date = new Date(dateString);
      
      if (isNaN(date.getTime())) {
        console.warn("Invalid date format:", dateString);
        return "-";
      }
      
      return date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "short",
        day: "numeric",
      });
    }
  } catch (error) {
    console.error("Error formatting date:", dateString, error);
    return "-";
  }
};

const filteredInterests = computed(() => {
  if (!interests.value?.list) return [];

  let filtered = interests.value.list;

  // Apply sales level filter
  if (selectedSalesLevel.value !== 'all') {
    filtered = filtered.filter((item) => {
      const level = item['Sales Process Level']?.toLowerCase() || '';
      switch (selectedSalesLevel.value) {
        case 'qualified':
          return level.includes('qualified');
        case 'loi':
          return level.includes('loi');
        case 'reserved':
          return level.includes('reservation') || level.includes('reserved');
        default:
          return true;
      }
    });
  }

  // Apply search filter
  if (search.value) {
    const searchLower = search.value.toLowerCase();
    filtered = filtered.filter((item) => {
      return Object.values(item).some((value) =>
        String(value).toLowerCase().includes(searchLower)
      );
    });
  }

  return filtered;
});

// Helper function to get initials
const getInitials = (name: string) => {
  if (!name) return '?';
  const parts = name.split(' ');
  if (parts.length >= 2) {
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  }
  return name.substring(0, 2).toUpperCase();
};

// Helper function to get relative time
const getRelativeTime = (dateString: string) => {
  if (!dateString) return '';
  
  try {
    let date: Date;
    
    // Handle DD-MM-YYYY format
    if (dateString.includes('-')) {
      const parts = dateString.split('-');
      if (parts.length === 3) {
        const [day, month, year] = parts;
        date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
      } else {
        date = new Date(dateString);
      }
    } else {
      date = new Date(dateString);
    }
    
    if (isNaN(date.getTime())) return '';
    
    const now = new Date();
    const diffTime = Math.abs(now.getTime() - date.getTime());
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) return 'Today';
    if (diffDays === 1) return 'Yesterday';
    if (diffDays < 7) return `${diffDays} days ago`;
    if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`;
    if (diffDays < 365) return `${Math.floor(diffDays / 30)} months ago`;
    return `${Math.floor(diffDays / 365)} years ago`;
  } catch (error) {
    return '';
  }
};
</script>

<style scoped>
.search-field :deep(.v-field) {
  transition: all 0.3s ease;
}

.search-field:focus-within :deep(.v-field) {
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}

.modern-table :deep(.v-table__wrapper) {
  border-radius: 8px;
  overflow: hidden;
}

.modern-table :deep(.v-data-table-header__content) {
  font-weight: 600;
  color: #424242;
  font-size: 0.875rem;
  text-transform: uppercase;
  letter-spacing: 0.025em;
}

.modern-table :deep(tbody tr) {
  transition: all 0.2s ease;
}

.modern-table :deep(tbody tr:hover) {
  background-color: #f8f9fa;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.table-row {
  cursor: pointer;
}

.table-row td {
  padding: 16px !important;
  border-bottom: 1px solid #e0e0e0;
}

.table-row:last-child td {
  border-bottom: none;
}

.v-avatar {
  font-size: 0.875rem;
}

.logo-icon {
  height: 32px;
  width: auto;
  max-width: 32px;
  object-fit: contain;
}

/* Mobile horizontal scrolling with visual indicators */
.table-container {
  position: relative;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

/* Scroll indicators */
.table-container::before,
.table-container::after {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  width: 40px;
  pointer-events: none;
  z-index: 1;
  transition: opacity 0.3s;
}

.table-container::before {
  left: 0;
  background: linear-gradient(to right, white, transparent);
  opacity: 0;
}

.table-container::after {
  right: 0;
  background: linear-gradient(to left, white, transparent);
}

.table-container:not(.scroll-start)::before {
  opacity: 1;
}

.table-container:not(.scroll-end)::after {
  opacity: 1;
}

/* Safari-specific fixes and scrolling performance improvements */
.modern-table :deep(.v-table__wrapper) {
  -webkit-transform: translateZ(0);
  transform: translateZ(0);
  /* Improve scrolling performance */
  will-change: scroll-position;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.modern-table :deep(.v-data-table__td) {
  min-width: 0;
  /* Optimize for better rendering */
  contain: layout style paint;
}

/* Fix potential scrolling issues on desktop */
.modern-table :deep(.v-table) {
  table-layout: fixed;
  width: 100%;
}

.modern-table :deep(tbody tr) {
  /* Prevent sub-pixel rendering issues */
  transform: translateZ(0);
}

/* Column width constraints */
.modern-table :deep(th:nth-child(1)),
.modern-table :deep(td:nth-child(1)) {
  min-width: 250px;
}

.modern-table :deep(th:nth-child(2)),
.modern-table :deep(td:nth-child(2)) {
  min-width: 150px;
}

.modern-table :deep(th:nth-child(3)),
.modern-table :deep(td:nth-child(3)) {
  min-width: 120px;
}

.modern-table :deep(th:nth-child(4)),
.modern-table :deep(td:nth-child(4)) {
  min-width: 120px;
}

.modern-table :deep(th:nth-child(5)),
.modern-table :deep(td:nth-child(5)) {
  min-width: 120px;
}

.modern-table :deep(th:nth-child(6)),
.modern-table :deep(td:nth-child(6)) {
  min-width: 140px;
}

@media (max-width: 768px) {
  .table-container {
    margin: 0 -12px;
    padding: 0 12px;
  }
  
  .modern-table :deep(.v-table__wrapper) {
    min-width: 900px;
  }
  
  .modern-table :deep(th) {
    white-space: nowrap;
  }
  
  .modern-table :deep(td) {
    white-space: nowrap;
  }
}
</style>
