<template>
  <div>
    <v-container fluid>
      <!-- Duplicate notification banner for admins -->
      <DuplicateNotificationBanner />
      
      <!-- Header Section -->
      <v-row class="mb-4 mb-md-6">
        <v-col cols="12" md="8">
          <h1 class="text-h5 text-md-h4 font-weight-bold mb-1 mb-md-2">
            Port Nimara Berth Interests
          </h1>
          <p class="text-body-2 text-md-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-start justify-md-end align-center mt-2 mt-md-0">
          <v-btn
            color="primary"
            :size="mobile ? 'default' : 'large'"
            @click="showCreateModal = true"
            prepend-icon="mdi-plus"
            variant="tonal"
            :block="mobile"
          >
            Add Interest
          </v-btn>
        </v-col>
      </v-row>

      <!-- Search and Filters Section -->
      <v-row class="mb-4">
        <v-col cols="12" :md="mobile ? 12 : 6" class="mb-2 mb-md-0">
          <v-text-field
            v-model="search"
            label="Search interests..."
            placeholder="Search by name, yacht, email, phone..."
            prepend-inner-icon="mdi-magnify"
            variant="outlined"
            :density="mobile ? 'compact' : '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="x-small"
                  color="primary"
                  variant="tonal"
                >
                  {{ filteredInterests.length }}
                </v-chip>
              </v-fade-transition>
            </template>
          </v-text-field>
        </v-col>
        <v-col cols="12" :md="mobile ? 12 : 6">
          <div class="d-flex flex-wrap align-center" :class="mobile ? 'justify-start' : 'justify-end'">
            <v-btn
              v-if="hasActiveFilters && mobile"
              variant="text"
              color="primary"
              size="x-small"
              @click="clearAllFilters"
              icon="mdi-filter-off"
              class="mr-2"
            />
            <v-btn
              v-if="hasActiveFilters && !mobile"
              variant="text"
              color="primary"
              size="small"
              @click="clearAllFilters"
              prepend-icon="mdi-filter-off"
              class="mr-2"
            >
              Clear Filters
            </v-btn>
            <v-chip-group
              v-model="selectedSalesLevel"
              selected-class="text-primary"
              :column="false"
              mandatory
            >
              <v-chip
                filter
                variant="outlined"
                :size="mobile ? 'x-small' : 'small'"
                value="all"
              >
                All
              </v-chip>
              <v-chip
                filter
                variant="outlined"
                :size="mobile ? 'x-small' : 'small'"
                value="qualified"
              >
                Qualified
              </v-chip>
              <v-chip
                filter
                variant="outlined"
                :size="mobile ? 'x-small' : 'small'"
                value="loi"
              >
                LOI
              </v-chip>
              <v-chip
                filter
                variant="outlined"
                :size="mobile ? 'x-small' : 'small'"
                value="reserved"
              >
                Reserved
              </v-chip>
            </v-chip-group>
          </div>
        </v-col>
      </v-row>

      <!-- Mobile: Card-Based Layout -->
      <div v-if="mobile" class="mobile-card-container">
        <v-progress-linear v-if="loading" indeterminate color="primary" class="mb-4" />
        
        <div v-if="!loading && filteredInterests.length === 0" class="text-center py-8">
          <v-icon size="64" color="grey-lighten-2" class="mb-4">mdi-account-search</v-icon>
          <p class="text-h6 text-grey-darken-1">No interests found</p>
          <p class="text-body-2 text-grey">Try adjusting your search or filters</p>
        </div>

        <div v-for="(item, index) in sortedFilteredInterests" :key="item.Id" class="mobile-interest-card">
          <v-card 
            @click="handleRowClick(item)"
            class="interest-card"
            elevation="1"
            hover
          >
            <v-card-text class="pa-4">
              <!-- Contact Header -->
              <div class="d-flex align-center mb-3">
                <v-avatar size="40" color="primary" class="mr-3">
                  <span class="text-white text-body-2 font-weight-bold">
                    {{ getInitials(item["Full Name"]) }}
                  </span>
                </v-avatar>
                <div class="flex-grow-1 min-width-0">
                  <div class="d-flex align-center gap-1">
                    <h3 class="text-subtitle-1 font-weight-medium text-truncate">{{ item["Full Name"] }}</h3>
                    <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>
                  <p class="text-body-2 text-grey-darken-1 text-truncate mb-0">{{ item["Email Address"] }}</p>
                </div>
                <v-chip
                  size="x-small"
                  variant="tonal"
                  color="grey"
                  class="ml-2"
                >
                  {{ getRelativeTime(item["Created At"]) }}
                </v-chip>
              </div>

              <!-- Status Section -->
              <div class="status-section mb-3">
                <div class="d-flex align-center justify-space-between mb-2">
                  <span class="text-caption text-grey-darken-1 font-weight-medium">CURRENT STATUS</span>
                  <v-chip
                    :color="getSalesStatusColor(item['Sales Process Level'])"
                    size="small"
                    variant="flat"
                    class="font-weight-medium"
                  >
                    {{ getDescriptiveSalesStatus(item['Sales Process Level']) }}
                  </v-chip>
                </div>
              </div>

              <!-- Detailed Status Grid -->
              <div class="status-grid">
                <div class="status-item">
                  <span class="status-label">EOI Status</span>
                  <div class="status-value">
                    <EOIStatusBadge
                      v-if="item['EOI Status']"
                      :eoiStatus="item['EOI Status']"
                      size="small"
                    />
                    <v-chip v-else size="small" variant="tonal" color="grey">
                      Awaiting Further Details
                    </v-chip>
                  </div>
                </div>

                <div class="status-item">
                  <span class="status-label">Lead Type</span>
                  <div class="status-value">
                    <v-chip
                      size="small"
                      :color="item['Lead Category'] === 'Friends and Family' ? 'purple' : 'blue'"
                      variant="tonal"
                    >
                      {{ item['Lead Category'] === 'Friends and Family' ? 'Friends & Family' : 'General Lead' }}
                    </v-chip>
                  </div>
                </div>

                <div v-if="item['Contract Status']" class="status-item">
                  <span class="status-label">Contract</span>
                  <div class="status-value">
                    <ContractStatusBadge
                      :contractStatus="item['Contract Status']"
                      size="small"
                    />
                  </div>
                </div>

                <div class="status-item">
                  <span class="status-label">Added</span>
                  <div class="status-value">
                    <span class="text-body-2">{{ formatDate(item["Created At"]) }}</span>
                  </div>
                </div>
              </div>
            </v-card-text>
          </v-card>
        </div>
      </div>

      <!-- Desktop: Data Table -->
      <v-card v-if="!mobile" elevation="0" class="rounded-lg">
        <div class="table-container">
          <v-data-table
            :headers="headers"
            :items="filteredInterests"
            :search="search"
            :sort-by="[{ key: 'Id', order: 'desc' }]"
            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 class="contact-cell">
                <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 min-width-0">
                    <div class="d-flex align-center gap-1">
                      <span class="font-weight-medium text-truncate">{{ 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 text-truncate">{{ 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";
import { formatDate, formatDateUS, getRelativeTime } from "@/utils/dateUtils";

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

const { mobile } = useDisplay();
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", {
  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 = computed(() => {
  return [
    { 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';
};

// Helper functions for mobile card layout
const getDescriptiveSalesStatus = (status: string) => {
  if (!status) return 'New Interest';
  if (status.includes('Qualified')) return 'Qualified Interest';
  if (status.includes('LOI')) return 'LOI & NDA Sent';
  if (status.includes('Signed')) return 'Signed LOI & NDA';
  if (status.includes('Reservation')) return 'Made Reservation';
  if (status.includes('Contract')) return 'Contract Stage';
  return status;
};

const getSalesStatusColor = (status: string) => {
  if (!status) return 'grey';
  if (status.includes('Qualified')) return 'blue';
  if (status.includes('LOI')) return 'orange';
  if (status.includes('Signed')) return 'green';
  if (status.includes('Reservation')) return 'purple';
  if (status.includes('Contract')) return 'primary';
  return 'grey';
};


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;
});

// Sorted filtered interests for mobile view (newest first)
const sortedFilteredInterests = computed(() => {
  if (!filteredInterests.value) return [];
  
  // Sort by Id in descending order (newest first)
  return [...filteredInterests.value].sort((a, b) => b.Id - a.Id);
});

// 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();
};

</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);
}

/* Mobile Card Layout Styles */
.mobile-card-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.mobile-interest-card {
  width: 100%;
}

.interest-card {
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 12px !important;
}

.interest-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12) !important;
}

.status-section {
  border-top: 1px solid #e0e0e0;
  padding-top: 12px;
}

.status-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.status-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.status-label {
  font-size: 0.75rem;
  font-weight: 500;
  color: #666;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.status-value {
  display: flex;
  align-items: center;
}

/* Desktop Table Styles */
.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;
}

.table-container {
  position: relative;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

/* Responsive column widths for desktop */
@media (min-width: 769px) {
  .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;
  }
}

/* Mobile-specific adjustments */
@media (max-width: 768px) {
  .v-container {
    padding: 12px 16px !important;
  }
  
  .status-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .status-item {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
  
  .status-label {
    flex: 1;
  }
  
  .status-value {
    flex: 0 0 auto;
  }
}

/* Ensure proper text truncation */
.text-truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.min-width-0 {
  min-width: 0;
}
</style>
