<template>
  <div>
    <v-card-title class="text-h6 d-flex align-center pb-4">
      <v-icon class="mr-2" color="primary">mdi-email</v-icon>
      Email Communication
    </v-card-title>
    <v-card-text class="pt-0">
      
      <!-- Email Credentials Setup -->
      <EmailCredentialsSetup 
        v-if="!hasEmailCredentials"
        @credentials-saved="onCredentialsSaved"
      />
      
      <div v-else>
      
      <!-- Email Controls -->
      <div class="mb-4">
        <div class="d-flex align-center gap-2 flex-wrap">
          <v-btn
            @click="showComposer = true"
            color="primary"
            variant="flat"
            prepend-icon="mdi-email-edit"
            :size="mobile ? 'small' : 'default'"
          >
            {{ mobile ? 'Compose' : 'Compose Email' }}
          </v-btn>
          <v-btn
            @click="loadEmailThread"
            variant="tonal"
            :loading="isRefreshing"
            size="small"
            color="grey-darken-4"
            icon="mdi-refresh"
            class="ml-4"
          >
            <v-tooltip activator="parent" location="bottom">Refresh Emails</v-tooltip>
          </v-btn>
          <v-spacer />
          <v-btn-group v-if="!mobile" variant="text" density="compact">
            <v-btn
              @click="reconnectEmail"
              size="small"
              prepend-icon="mdi-connection"
            >
              Reconnect
            </v-btn>
            <v-btn
              @click="disconnectEmail"
              size="small"
              color="error"
              prepend-icon="mdi-logout"
            >
              Disconnect
            </v-btn>
          </v-btn-group>
          <v-menu v-else>
            <template v-slot:activator="{ props }">
              <v-btn
                v-bind="props"
                icon="mdi-dots-vertical"
                variant="text"
                size="small"
              />
            </template>
            <v-list density="compact">
              <v-list-item @click="reconnectEmail" prepend-icon="mdi-connection">
                <v-list-item-title>Reconnect</v-list-item-title>
              </v-list-item>
              <v-list-item @click="disconnectEmail" prepend-icon="mdi-logout" base-color="error">
                <v-list-item-title>Disconnect</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu>
        </div>
      </div>

      <!-- Loading State -->
      <div v-if="isRefreshing && emailThreads.length === 0 && threads.length === 0" class="text-center py-8">
        <v-progress-circular indeterminate color="primary" :size="48" />
        <div class="text-body-2 mt-3 text-grey">Loading email history...</div>
      </div>
      
      <!-- Email Thread List -->
      <div v-else-if="emailThreads.length > 0 || threads.length > 0" class="email-threads">
        <div class="text-subtitle-1 mb-3 d-flex align-center">
          Email History
          <v-spacer />
          <v-btn-toggle
            v-model="viewMode"
            mandatory
            density="compact"
            variant="outlined"
            size="small"
          >
            <v-btn value="threads" size="small">
              <v-icon :start="!mobile">mdi-forum</v-icon>
              <span v-if="!mobile" class="ml-1">Threads</span>
            </v-btn>
            <v-btn value="all" size="small">
              <v-icon :start="!mobile">mdi-email-multiple</v-icon>
              <span v-if="!mobile" class="ml-1">All</span>
            </v-btn>
          </v-btn-toggle>
        </div>
        
        <!-- Thread View -->
        <div v-if="viewMode === 'threads' && threads.length > 0">
          <v-expansion-panels v-model="expandedThreads" multiple variant="accordion">
            <v-expansion-panel v-for="thread in threads" :key="thread.id" elevation="0">
              <v-expansion-panel-title>
                <div class="d-flex align-center justify-space-between w-100">
                  <div>
                    <div class="text-body-2 font-weight-medium">{{ thread.subject }}</div>
                    <div class="text-caption text-grey">
                      {{ thread.emailCount }} {{ thread.emailCount === 1 ? 'email' : 'emails' }} • 
                      Last activity {{ formatRelativeTime(thread.latestTimestamp) }}
                    </div>
                  </div>
                  <v-chip size="small" color="primary" variant="tonal">
                    {{ thread.emailCount }}
                  </v-chip>
                </div>
              </v-expansion-panel-title>
              <v-expansion-panel-text>
                <v-timeline :density="mobile ? 'compact' : 'comfortable'" side="end">
                  <v-timeline-item
                    v-for="(email, emailIndex) in thread.emails"
                    :key="emailIndex"
                    :dot-color="email.direction === 'sent' ? 'primary' : 'success'"
                    :icon="email.direction === 'sent' ? 'mdi-email-send' : 'mdi-email-receive'"
                    :size="mobile ? 'x-small' : 'small'"
                  >
                    <v-card 
                      variant="outlined" 
                      :density="mobile ? 'compact' : 'default'"
                      @click="viewEmail(email)"
                      class="email-card"
                      :hover="true"
                    >
                      <v-card-subtitle class="d-flex align-center justify-space-between">
                        <span class="text-body-2">
                          {{ email.direction === 'sent' ? 'To' : 'From' }}: 
                          {{ email.direction === 'sent' ? email.to : email.from }}
                        </span>
                        <span class="text-caption text-grey">
                          {{ formatDate(email.timestamp) }}
                        </span>
                      </v-card-subtitle>
                      
                      <v-card-text :class="mobile ? 'pa-3' : ''">
                        <div class="email-content email-preview" :class="mobile ? 'email-content-mobile' : ''" v-html="formatEmailContent(email.content || email.body)"></div>
                        
                        <!-- Attachments -->
                        <div v-if="email.attachments && email.attachments.length > 0" class="mt-3">
                          <v-chip
                            v-for="(attachment, i) in email.attachments"
                            :key="i"
                            size="small"
                            color="primary"
                            variant="tonal"
                            prepend-icon="mdi-paperclip"
                            class="mr-2 mb-1"
                            :href="getAttachmentUrl(attachment)"
                            :target="isViewableAttachment(attachment) ? '_blank' : undefined"
                            :download="!isViewableAttachment(attachment)"
                            component="a"
                            clickable
                          >
                            {{ getAttachmentName(attachment) }}
                          </v-chip>
                        </div>
                        
                        <div class="d-flex justify-space-between mt-3 gap-2">
                          <v-btn variant="text" size="small" color="primary" @click.stop="viewEmail(email)">
                            <v-icon :start="!mobile" :size="mobile ? 'small' : 'default'">mdi-email-open</v-icon>
                            <span v-if="!mobile" class="ml-1">View</span>
                          </v-btn>
                          <v-btn variant="text" size="small" color="primary" @click.stop="replyToEmail(email)">
                            <v-icon :start="!mobile" :size="mobile ? 'small' : 'default'">mdi-reply</v-icon>
                            <span v-if="!mobile" class="ml-1">Reply</span>
                          </v-btn>
                        </div>
                      </v-card-text>
                    </v-card>
                  </v-timeline-item>
                </v-timeline>
                
                <!-- Reply to thread button -->
                <div class="text-center mt-4 mb-2">
                  <v-btn
                    @click="replyToThread(thread)"
                    color="primary"
                    variant="flat"
                    prepend-icon="mdi-reply"
                    size="default"
                  >
                    Reply to Thread
                  </v-btn>
                </div>
              </v-expansion-panel-text>
            </v-expansion-panel>
          </v-expansion-panels>
        </div>
        
        <!-- All Emails View (Original) -->
        <v-timeline v-else :side="mobile ? 'end' : 'end'" :density="mobile ? 'compact' : 'comfortable'">
          <v-timeline-item
            v-for="(email, index) in emailThreads"
            :key="index"
            :dot-color="email.direction === 'sent' ? 'primary' : 'success'"
            :icon="email.direction === 'sent' ? 'mdi-email-send' : 'mdi-email-receive'"
            :size="mobile ? 'x-small' : 'small'"
          >
            <template v-slot:opposite v-if="!mobile">
              <div class="text-caption">
                {{ formatDate(email.timestamp) }}
              </div>
            </template>
            
            <v-card 
              variant="outlined" 
              :density="mobile ? 'compact' : 'default'"
              @click="viewEmail(email)"
              class="email-card"
              :hover="true"
            >
              <v-card-subtitle class="d-flex align-center justify-space-between">
                <span class="text-body-2">
                  {{ email.direction === 'sent' ? 'To' : 'From' }}: 
                  {{ email.direction === 'sent' ? email.to : email.from }}
                </span>
                <span v-if="mobile" class="text-caption text-grey">
                  {{ formatDate(email.timestamp) }}
                </span>
              </v-card-subtitle>
              
              <v-card-text :class="mobile ? 'pa-3' : ''">
                <div class="text-body-2 font-weight-medium mb-2">{{ email.subject }}</div>
                <div class="email-content email-preview" :class="mobile ? 'email-content-mobile' : ''" v-html="formatEmailContent(email.content || email.body)"></div>
                
                <!-- Attachments -->
                <div v-if="email.attachments && email.attachments.length > 0" class="mt-3">
                  <v-chip
                    v-for="(attachment, i) in email.attachments"
                    :key="i"
                    size="small"
                    color="primary"
                    variant="tonal"
                    prepend-icon="mdi-paperclip"
                    class="mr-2 mb-1"
                    :href="getAttachmentUrl(attachment)"
                    :target="isViewableAttachment(attachment) ? '_blank' : undefined"
                    :download="!isViewableAttachment(attachment)"
                    component="a"
                    clickable
                  >
                    {{ getAttachmentName(attachment) }}
                  </v-chip>
                </div>
                
                <div class="d-flex justify-space-between mt-3">
                  <v-btn variant="text" size="small" color="primary">
                    <v-icon start>mdi-email-open</v-icon>
                    View Full Email
                  </v-btn>
                  <v-btn variant="text" size="small" color="primary" @click.stop="replyToEmail(email)">
                    <v-icon start>mdi-reply</v-icon>
                    Reply
                  </v-btn>
                </div>
              </v-card-text>
            </v-card>
          </v-timeline-item>
        </v-timeline>
      </div>
      
        <!-- Empty State -->
        <div v-else class="text-center py-8 text-grey">
          <v-icon size="48" class="mb-3">mdi-email-outline</v-icon>
          <div>No email communication yet</div>
        </div>
      </div>
    </v-card-text>

    <!-- Email Composer Dialog -->
    <v-dialog 
      v-model="showComposer" 
      :max-width="mobile ? '100%' : '800'"
      :fullscreen="mobile"
      persistent
      :transition="mobile ? 'dialog-bottom-transition' : 'dialog-transition'"
    >
      <v-card :max-height="mobile ? '100vh' : undefined">
        <v-card-title class="d-flex align-center">
          <v-icon class="mr-2">mdi-email-edit</v-icon>
          Compose Email
          <v-spacer />
          <v-btn icon="mdi-close" variant="text" @click="closeComposer"></v-btn>
        </v-card-title>
        
        <v-divider />
        
        <v-card-text>
          <!-- Recipient Info -->
          <v-alert type="info" variant="tonal" class="mb-4">
            <div class="d-flex align-center">
              <v-icon class="mr-2">mdi-account</v-icon>
              <div>
                <div class="font-weight-medium">{{ interest['Full Name'] }}</div>
                <div class="text-caption">{{ interest['Email Address'] }}</div>
              </div>
            </div>
          </v-alert>

          <!-- Subject -->
          <v-text-field
            v-model="emailDraft.subject"
            label="Subject"
            variant="outlined"
            :density="mobile ? 'compact' : 'comfortable'"
            class="mb-4"
          />

          <!-- Quick Actions -->
          <div class="mb-3" :class="mobile ? 'd-flex flex-column align-start' : ''">
            <span class="text-body-2" :class="mobile ? 'mb-2' : 'mr-2'">Quick Insert:</span>
            <div :class="mobile ? 'd-flex gap-2' : ''">
              <v-btn
                v-if="hasEOI"
                @click="insertEOILink"
                :size="mobile ? 'x-small' : 'small'"
                variant="tonal"
                :prepend-icon="mobile ? undefined : 'mdi-file-document'"
                :class="!mobile ? '' : ''"
              >
                <v-icon v-if="mobile" size="small">mdi-file-document</v-icon>
                EOI{{ mobile ? '' : ' Link' }}
              </v-btn>
              <v-btn
                v-if="hasBerth"
                @click="insertBerthInfo"
                :size="mobile ? 'x-small' : 'small'"
                variant="tonal"
                :prepend-icon="mobile ? undefined : 'mdi-anchor'"
                :class="!mobile ? 'ml-2' : ''"
              >
                <v-icon v-if="mobile" size="small">mdi-anchor</v-icon>
                Berth{{ mobile ? '' : ' Info' }}
              </v-btn>
            </div>
          </div>

          <!-- Email Content -->
          <v-textarea
            v-model="emailDraft.content"
            label="Email Content"
            variant="outlined"
            :rows="mobile ? 8 : 12"
            placeholder="Write your email here..."
            ref="contentTextarea"
            :density="mobile ? 'compact' : 'default'"
          />

          <!-- Signature Settings -->
          <v-expansion-panels variant="accordion" class="my-4">
            <v-expansion-panel>
              <v-expansion-panel-title>
                <v-icon class="mr-2">mdi-draw-pen</v-icon>
                Email Signature Settings
              </v-expansion-panel-title>
              <v-expansion-panel-text>
                <v-checkbox
                  v-model="includeSignature"
                  label="Include signature"
                  hide-details
                  class="mb-3"
                />
                <div v-if="includeSignature">
                  <v-text-field
                    v-model="signatureConfig.name"
                    label="Your Name"
                    variant="outlined"
                    density="compact"
                    class="mb-2"
                  />
                  <v-text-field
                    v-model="signatureConfig.title"
                    label="Job Title"
                    variant="outlined"
                    density="compact"
                    class="mb-2"
                  />
                  <v-text-field
                    v-model="signatureConfig.company"
                    label="Company"
                    variant="outlined"
                    density="compact"
                    class="mb-2"
                  />
                  <v-text-field
                    v-model="signatureConfig.email"
                    label="Email"
                    variant="outlined"
                    density="compact"
                    class="mb-2"
                  />
                  <v-textarea
                    v-model="signatureConfig.contactInfo"
                    label="Additional Contact Info"
                    variant="outlined"
                    density="compact"
                    rows="2"
                  />
                  <v-btn
                    @click="saveSignature"
                    variant="tonal"
                    color="primary"
                    size="small"
                    class="mt-2"
                  >
                    Save Signature
                  </v-btn>
                </div>
              </v-expansion-panel-text>
            </v-expansion-panel>
          </v-expansion-panels>

          <!-- Attachments -->
          <div class="mt-4">
            <div class="text-body-2 mb-2">Attachments</div>
            
            <!-- Attachment Options -->
            <v-btn-toggle 
              v-model="attachmentMode" 
              mandatory 
              class="mb-3"
              :density="mobile ? 'compact' : 'default'"
            >
              <v-btn value="upload" :size="mobile ? 'x-small' : 'small'">
                <v-icon :start="!mobile" :size="mobile ? 'small' : 'default'">mdi-upload</v-icon>
                <span :class="mobile ? 'text-caption' : ''">{{ mobile ? 'Upload' : 'Upload Files' }}</span>
              </v-btn>
              <v-btn value="browse" :size="mobile ? 'x-small' : 'small'">
                <v-icon :start="!mobile" :size="mobile ? 'small' : 'default'">mdi-folder-open</v-icon>
                <span :class="mobile ? 'text-caption' : ''">{{ mobile ? 'Browse' : 'Browse Files' }}</span>
              </v-btn>
            </v-btn-toggle>

            <!-- Upload Mode -->
            <v-file-input
              v-if="attachmentMode === 'upload'"
              v-model="emailDraft.attachments"
              label="Select files to attach"
              variant="outlined"
              :density="mobile ? 'compact' : 'comfortable'"
              multiple
              chips
              prepend-icon="mdi-paperclip"
              :show-size="!mobile"
            />
            
            <!-- Browse Mode -->
            <div v-else>
              <v-btn
                @click="openFileBrowser"
                variant="outlined"
                block
                :size="mobile ? 'default' : 'large'"
                :prepend-icon="!mobile ? 'mdi-folder-open' : undefined"
                :icon="mobile ? 'mdi-folder-open' : undefined"
              >
                <span v-if="!mobile">Browse Files</span>
              </v-btn>
            </div>

            <!-- All Attachments Preview -->
            <div v-if="allAttachments.length > 0" class="mt-3">
              <div class="text-caption mb-2">Attachments ({{ allAttachments.length }}):</div>
              <v-chip
                v-for="(attachment, i) in allAttachments"
                :key="`${attachment.type}-${i}`"
                size="small"
                color="primary"
                variant="tonal"
                closable
                @click:close="removeAttachment(attachment)"
                class="mr-2 mb-2"
              >
                <v-icon start size="small">{{ attachment.type === 'uploaded' ? 'mdi-upload' : 'mdi-file' }}</v-icon>
                {{ attachment.name }}
              </v-chip>
            </div>
          </div>
        </v-card-text>
        
        <v-divider />
        
        <v-card-actions>
          <v-spacer />
          <v-btn @click="closeComposer" variant="text">Cancel</v-btn>
          <v-btn
            @click="sendEmail"
            color="primary"
            variant="flat"
            prepend-icon="mdi-send"
            :loading="isSending"
          >
            Send Email
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- File Browser Dialog -->
    <v-dialog 
      v-model="showFileBrowser" 
      :max-width="mobile ? '100%' : '1200'"
      :fullscreen="mobile"
      :transition="mobile ? 'dialog-bottom-transition' : 'dialog-transition'"
    >
      <v-card :height="mobile ? '100vh' : '80vh'">
        <v-card-title class="d-flex align-center">
          <v-icon class="mr-2">mdi-folder-open</v-icon>
          Select Files from Browser
          <v-spacer />
          <v-btn icon="mdi-close" variant="text" @click="showFileBrowser = false"></v-btn>
        </v-card-title>
        <v-divider />
        <v-card-text class="pa-0" style="height: calc(100% - 64px - 72px);">
          <FileBrowser
            selection-mode
            @file-selected="handleFileSelected"
          />
        </v-card-text>
        <v-divider />
        <v-card-actions>
          <div class="text-caption" v-if="tempSelectedFiles.length > 0">
            {{ tempSelectedFiles.length }} file(s) selected
          </div>
          <v-spacer />
          <v-btn @click="cancelFileBrowser" variant="text">Cancel</v-btn>
          <v-btn 
            @click="confirmFileSelection" 
            color="primary" 
            variant="flat"
            :disabled="tempSelectedFiles.length === 0"
          >
            Attach Selected Files
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Email Details Dialog -->
    <EmailDetailsDialog 
      v-model="showEmailDetails"
      :email="selectedEmail"
    />
  </div>
</template>

<script setup lang="ts">
import type { Interest } from '~/utils/types';
import FileBrowser from '~/pages/dashboard/file-browser.vue';
import EmailDetailsDialog from '~/components/EmailDetailsDialog.vue';

const props = defineProps<{
  interest: Interest;
}>();

const emit = defineEmits<{
  'email-sent': [];
  'update': [];
}>();

const { mobile } = useDisplay();
const toast = useToast();
const showComposer = ref(false);
const isSending = ref(false);
const emailThreads = ref<any[]>([]);
const contentTextarea = ref<any>(null);
const isRefreshing = ref(false);
const attachmentMode = ref('upload');
const selectedBrowserFiles = ref<any[]>([]);
const hasEmailCredentials = ref(false);
const sessionId = ref<string>('');
const includeSignature = ref(true);
const signatureConfig = ref<any>({});
const showFileBrowser = ref(false);
const tempSelectedFiles = ref<any[]>([]);
const showEmailDetails = ref(false);
const selectedEmail = ref<any>(null);
const threads = ref<any[]>([]);
const viewMode = ref('threads');
const expandedThreads = ref<number[]>([0]); // Expand first thread by default
const replyingTo = ref<any>(null);

const emailDraft = ref<{
  subject: string;
  content: string;
  attachments: File[];
}>({
  subject: '',
  content: '',
  attachments: []
});

// Combined attachments from both upload and browser
const allAttachments = computed(() => {
  const uploaded = emailDraft.value.attachments.map((file, index) => ({
    type: 'uploaded',
    file,
    name: file.name,
    index
  }));
  
  const browser = selectedBrowserFiles.value.map((file, index) => ({
    type: 'browser',
    file,
    name: file.displayName || file.name,
    index
  }));
  
  return [...uploaded, ...browser];
});

// Check for stored session on mount and validate it
onMounted(async () => {
  // Use sessionStorage instead of localStorage for email sessions to require re-auth on page reload
  const storedSession = sessionStorage.getItem('emailSessionId');
  
  if (storedSession) {
    // Validate the session is still active
    try {
      const testResponse = await $fetch('/api/email/test-connection', {
        method: 'POST',
        headers: {
          'x-tag': '094ut234'
        },
        body: {
          sessionId: storedSession
        }
      });
      
      if (testResponse.success) {
        sessionId.value = storedSession;
        hasEmailCredentials.value = true;
      } else {
        // Session invalid, clear it
        sessionStorage.removeItem('emailSessionId');
        hasEmailCredentials.value = false;
      }
    } catch (error) {
      // Connection test failed, clear session
      console.log('[ClientEmailSection] Email session validation failed, clearing session');
      sessionStorage.removeItem('emailSessionId');
      hasEmailCredentials.value = false;
    }
  }
  
  // Load signature config (this can persist in localStorage)
  const storedSignature = localStorage.getItem('emailSignature');
  if (storedSignature) {
    signatureConfig.value = JSON.parse(storedSignature);
  }
  
  // Load email thread immediately if credentials are available and valid
  if (hasEmailCredentials.value) {
    loadEmailThread();
  }
  
  // Auto-refresh every 30 seconds
  const refreshInterval = setInterval(() => {
    if (hasEmailCredentials.value) {
      loadEmailThread();
    }
  }, 30000);
  
  // Clean up interval on unmount
  onUnmounted(() => {
    clearInterval(refreshInterval);
  });
});

// Check if interest has EOI or berth
const hasEOI = computed(() => {
  // Don't show EOI link if EOI is already signed
  if (props.interest['EOI Status'] === 'Signed') return false;
  
  const eoiDocs = props.interest['EOI Document'];
  const hasEOIDocs = Array.isArray(eoiDocs) && eoiDocs.length > 0;
  return !!(props.interest['Signature Link Client'] || hasEOIDocs);
});

const hasBerth = computed(() => {
  const berths = props.interest.Berths;
  const hasBerthsArray = Array.isArray(berths) && berths.length > 0;
  return !!(hasBerthsArray || props.interest['Berth Number']);
});

// Watch for interest changes
watch(() => props.interest.Id, () => {
  loadEmailThread();
});

const loadEmailThread = async () => {
  if (!sessionId.value) {
    console.log('[ClientEmailSection] No sessionId available, skipping email thread load');
    return;
  }
  
  isRefreshing.value = true;
  try {
    console.log('[ClientEmailSection] Loading email thread for:', props.interest['Email Address']);
    const response = await $fetch<{
      success: boolean;
      emails: any[];
      threads?: any[];
    }>('/api/email/fetch-thread', {
      method: 'POST',
      headers: {
        'x-tag': '094ut234'
      },
      body: {
        clientEmail: props.interest['Email Address'],
        interestId: props.interest.Id.toString(),
        sessionId: sessionId.value
      }
    });
    
    if (response.success) {
      console.log('[ClientEmailSection] Successfully loaded', response.emails?.length || 0, 'emails');
      emailThreads.value = response.emails || [];
      
      // Check if we have threads from the API response
      if (response.threads) {
        console.log('[ClientEmailSection] Threads available:', response.threads.length);
        threads.value = response.threads;
      }
    }
  } catch (error) {
    console.error('[ClientEmailSection] Failed to load email thread:', error);
  } finally {
    isRefreshing.value = false;
  }
};

const insertEOILink = () => {
  if (!contentTextarea.value) return;
  
  const link = props.interest['Signature Link Client'] || 
               props.interest['EOI Client Link'] ||
               'EOI document has been generated for your review';
  
  const insertText = `\n\nPlease review and sign your Expression of Interest (EOI) document:\n${link}\n\n`;
  
  insertAtCursor(insertText);
};

const insertFormLink = () => {
  const formLink = `https://form.portnimara.com/interest/${props.interest.Id}`;
  const insertText = `\n\nPlease complete your interest form:\n${formLink}\n\n`;
  
  insertAtCursor(insertText);
};

const insertBerthInfo = () => {
  let berthNumber = props.interest['Berth Number'];
  
  // Check if Berths is an array and has items
  if (!berthNumber && Array.isArray(props.interest.Berths) && props.interest.Berths.length > 0) {
    berthNumber = props.interest.Berths[0]['Berth Number'];
  }
  
  const insertText = `\n\nBerth Information:\nBerth Number: ${berthNumber || 'TBD'}\n\n`;
  
  insertAtCursor(insertText);
};

const insertAtCursor = (text: string) => {
  const textarea = contentTextarea.value.$el.querySelector('textarea');
  if (!textarea) return;
  
  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;
  const current = emailDraft.value.content;
  
  emailDraft.value.content = current.substring(0, start) + text + current.substring(end);
  
  // Set cursor position after inserted text
  nextTick(() => {
    textarea.focus();
    textarea.setSelectionRange(start + text.length, start + text.length);
  });
};

const sendEmail = async () => {
  if (!emailDraft.value.subject || !emailDraft.value.content) {
    toast.error('Please enter a subject and message');
    return;
  }
  
  if (!sessionId.value) {
    toast.error('Please set up email credentials first');
    hasEmailCredentials.value = false;
    return;
  }
  
  isSending.value = true;
  
  try {
    // First, upload any attachments to MinIO
    const uploadedAttachments = [];
    
    // Handle regular file attachments
    if (emailDraft.value.attachments && emailDraft.value.attachments.length > 0) {
      for (const file of emailDraft.value.attachments) {
        try {
          console.log('[ClientEmailSection] Uploading file:', file.name, 'size:', file.size);
          
          const formData = new FormData();
          formData.append('file', file);
          
          // Use the current user's username/email for the attachment folder
          // Get email from stored signature config or session
          const userEmail = signatureConfig.value?.email || 'unknown';
          const username = userEmail.split('@')[0]
            .toLowerCase()
            .replace(/[^a-z0-9-]/g, '');
          
          console.log('[ClientEmailSection] Upload path:', `${username}-attachments/`, 'bucket: client-emails');
          
          const uploadResponse = await $fetch<{ 
            success: boolean; 
            path: string; 
            fileName: string 
          }>('/api/files/upload', {
            method: 'POST',
            headers: {
              'x-tag': '094ut234'
            },
            query: {
              path: `${username}-attachments/`,
              bucket: 'client-emails'
            },
            body: formData
          });
          
          console.log('[ClientEmailSection] Upload response:', uploadResponse);
          
          if (uploadResponse.success) {
            const attachmentPath = uploadResponse.path || uploadResponse.fileName;
            console.log('[ClientEmailSection] Successfully uploaded, path:', attachmentPath);
            
            uploadedAttachments.push({
              name: file.name,
              path: attachmentPath,
              bucket: 'client-emails'
            });
          } else {
            console.error('[ClientEmailSection] Upload failed, response:', uploadResponse);
            toast.error(`Failed to upload ${file.name}`);
          }
        } catch (uploadError: any) {
          console.error('[ClientEmailSection] Failed to upload attachment:', file.name, uploadError);
          console.error('[ClientEmailSection] Upload error details:', uploadError.data || uploadError.message);
          toast.error(`Failed to upload ${file.name}: ${uploadError.data?.statusMessage || uploadError.message || 'Unknown error'}`);
        }
      }
    }
    
    // Handle files selected from browser
    if (selectedBrowserFiles.value.length > 0) {
      for (const file of selectedBrowserFiles.value) {
        // Files from browser are already in MinIO
        // Include bucket information
        uploadedAttachments.push({
          name: file.displayName || file.name,
          path: file.name,
          bucket: file.bucket || 'client-portal' // Include bucket info
        });
      }
    }
    
    // Prepare email data with the correct structure
    const emailData = {
      to: props.interest['Email Address'],
      subject: emailDraft.value.subject,
      body: emailDraft.value.content, // Use 'body' not 'html'
      interestId: props.interest.Id.toString(),
      sessionId: sessionId.value,
      includeSignature: includeSignature.value,
      signatureConfig: signatureConfig.value,
      attachments: uploadedAttachments
    };
    
    // Send email
    const response = await $fetch<{
      success: boolean;
      messageId?: string;
    }>('/api/email/send', {
      method: 'POST',
      headers: {
        'x-tag': '094ut234'
      },
      body: emailData
    });
    
    if (response.success) {
      toast.success('Email sent successfully');
      
      // Save signature config
      if (includeSignature.value) {
        localStorage.setItem('emailSignature', JSON.stringify(signatureConfig.value));
      }
      
      // Add to thread with all attachments info
      const allAttachmentNames = [
        ...emailDraft.value.attachments.map((f: File) => ({ name: f.name })),
        ...selectedBrowserFiles.value.map((f: any) => ({ name: f.displayName || f.name }))
      ];
      
      emailThreads.value.unshift({
        direction: 'sent',
        to: props.interest['Email Address'],
        subject: emailDraft.value.subject,
        content: emailDraft.value.content,
        timestamp: new Date().toISOString(),
        attachments: allAttachmentNames
      });
      
      // Close composer and reset
      closeComposer();
      emit('email-sent');
      emit('update');
    }
  } catch (error: any) {
    console.error('Failed to send email:', error);
    toast.error(error.data?.statusMessage || 'Failed to send email');
  } finally {
    isSending.value = false;
  }
};

const closeComposer = () => {
  showComposer.value = false;
  // Reset draft
  emailDraft.value = {
    subject: '',
    content: '',
    attachments: []
  };
  attachmentMode.value = 'upload';
  selectedBrowserFiles.value = [];
  replyingTo.value = null;
};

const removeBrowserFile = (index: number) => {
  selectedBrowserFiles.value = selectedBrowserFiles.value.filter((_, i) => i !== index);
};

const removeAttachment = (attachment: any) => {
  if (attachment.type === 'uploaded') {
    // Remove from uploaded files
    emailDraft.value.attachments = emailDraft.value.attachments.filter((_, i) => i !== attachment.index);
  } else if (attachment.type === 'browser') {
    // Remove from browser-selected files
    selectedBrowserFiles.value = selectedBrowserFiles.value.filter((_, i) => i !== attachment.index);
  }
};

const onCredentialsSaved = (data: { sessionId: string }) => {
  sessionId.value = data.sessionId;
  localStorage.setItem('emailSessionId', data.sessionId);
  hasEmailCredentials.value = true;
  toast.success('Email credentials saved successfully');
};

const disconnectEmail = () => {
  // Clear stored credentials
  localStorage.removeItem('emailSessionId');
  localStorage.removeItem('emailSignature');
  sessionId.value = '';
  hasEmailCredentials.value = false;
  emailThreads.value = [];
  toast.success('Email disconnected');
};

const reconnectEmail = () => {
  // Clear current session to force re-authentication
  localStorage.removeItem('emailSessionId');
  sessionId.value = '';
  hasEmailCredentials.value = false;
  toast.info('Please enter your email credentials');
};

const formatDate = (dateString: string) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  return date.toLocaleString('en-GB', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  });
};

const formatEmailContent = (content: string) => {
  // Ensure HTML content is properly formatted
  if (content.includes('<p>') || content.includes('<br>')) {
    return content;
  }
  // Convert plain text to HTML
  return content.split('\n').map(line => `<p>${line}</p>`).join('');
};

const openFileBrowser = () => {
  tempSelectedFiles.value = [...selectedBrowserFiles.value]; // Clone existing selections
  showFileBrowser.value = true;
};

const handleFileSelected = (file: any) => {
  // Check if file is already selected in temp list
  const existsIndex = tempSelectedFiles.value.findIndex(f => f.name === file.name);
  if (existsIndex > -1) {
    // Remove if already selected (toggle behavior)
    tempSelectedFiles.value.splice(existsIndex, 1);
    toast.info(`Removed ${file.displayName || file.name} from selection`);
  } else {
    // Add to temp selection
    tempSelectedFiles.value.push(file);
    toast.success(`Selected ${file.displayName || file.name}`);
  }
};

const confirmFileSelection = () => {
  selectedBrowserFiles.value = [...tempSelectedFiles.value];
  showFileBrowser.value = false;
  tempSelectedFiles.value = [];
  toast.success(`${selectedBrowserFiles.value.length} file(s) attached`);
};

const cancelFileBrowser = () => {
  showFileBrowser.value = false;
  tempSelectedFiles.value = [];
};

const viewEmail = (email: any) => {
  selectedEmail.value = email;
  showEmailDetails.value = true;
};

const replyToEmail = (email: any) => {
  replyingTo.value = email;
  
  // Pre-fill the subject with Re: prefix if not already there
  const subject = email.subject || '';
  emailDraft.value.subject = subject.startsWith('Re:') ? subject : `Re: ${subject}`;
  
  // Pre-fill with a reply header
  const originalDate = formatDate(email.timestamp);
  const originalFrom = email.direction === 'sent' ? 'you' : email.from;
  
  emailDraft.value.content = `\n\n\n--- Original Message ---\nFrom: ${originalFrom}\nDate: ${originalDate}\n\n${email.content || email.body || ''}`;
  
  showComposer.value = true;
};

const replyToThread = (thread: any) => {
  // Reply to the last email in the thread
  const lastEmail = thread.emails[thread.emails.length - 1];
  replyToEmail(lastEmail);
};

const formatRelativeTime = (timestamp: string) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);
  
  if (minutes < 1) return 'just now';
  if (minutes < 60) return `${minutes}m ago`;
  if (hours < 24) return `${hours}h ago`;
  if (days < 7) return `${days}d ago`;
  
  return date.toLocaleDateString('en-GB', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
  });
};

const saveSignature = () => {
  localStorage.setItem('emailSignature', JSON.stringify(signatureConfig.value));
  toast.success('Signature saved successfully');
};

// Helper functions for attachments
const getAttachmentName = (attachment: any) => {
  if (typeof attachment === 'string') {
    return attachment;
  }
  return attachment?.name || attachment?.filename || 'Attachment';
};

const getAttachmentUrl = (attachment: any) => {
  // If attachment is just a string (filename), assume it's in the client-emails bucket
  if (typeof attachment === 'string') {
    return `/api/files/proxy-download?fileName=${encodeURIComponent(attachment)}&bucket=client-emails`;
  }
  
  // If it has a path property, use that
  if (attachment?.path) {
    const bucket = attachment.bucket || 'client-emails';
    return `/api/files/proxy-download?fileName=${encodeURIComponent(attachment.path)}&bucket=${bucket}`;
  }
  
  // If it has a url property, use that directly
  if (attachment?.url) {
    return attachment.url;
  }
  
  // Default fallback
  const name = attachment?.name || attachment?.filename || 'attachment';
  return `/api/files/proxy-download?fileName=${encodeURIComponent(name)}&bucket=client-emails`;
};

const isViewableAttachment = (attachment: any) => {
  const name = getAttachmentName(attachment);
  const ext = name.split('.').pop()?.toLowerCase();
  
  // These file types can be viewed in browser
  const viewableExtensions = ['pdf', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'txt'];
  return viewableExtensions.includes(ext || '');
};
</script>

<style scoped>
.email-card {
  cursor: pointer;
  transition: all 0.2s;
}

.email-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.email-content {
  line-height: 1.6;
}

.email-preview {
  max-height: 100px;
  overflow: hidden;
  position: relative;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.email-preview::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 30px;
  background: linear-gradient(to bottom, transparent, white);
  pointer-events: none;
}

.email-content-mobile {
  max-height: 120px;
  font-size: 0.875rem;
  line-height: 1.4;
}

.email-content :deep(p) {
  margin: 0 0 0.5em 0;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.email-content :deep(br) {
  display: block;
  content: "";
  margin: 0.25em 0;
}

.email-threads {
  max-height: 600px;
  overflow-y: auto;
}

/* Fix expansion panel width on mobile */
:deep(.v-expansion-panel-text__wrapper) {
  padding: 0 !important;
}

@media (max-width: 768px) {
  .email-threads {
    max-height: 400px;
    /* Prevent horizontal scrolling */
    overflow-x: hidden;
  }
  
  /* Adjust timeline and cards for mobile */
  :deep(.v-timeline) {
    padding: 0;
  }
  
  :deep(.v-timeline-item__body) {
    max-width: 100%;
  }
  
  /* Ensure email cards don't overflow */
  .email-card {
    max-width: 100%;
    word-break: break-word;
  }
  
  /* Adjust expansion panel padding on mobile */
  :deep(.v-expansion-panel-text) {
    padding: 8px !important;
  }
  
  /* Ensure thread titles wrap properly */
  :deep(.v-expansion-panel-title) {
    padding: 12px 16px !important;
    min-height: auto !important;
  }
  
  :deep(.v-expansion-panel-title__content) {
    flex-wrap: wrap;
  }
}
</style>
