<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>
      
      <!-- Compose New Email -->
      <div class="mb-4 d-flex align-center gap-2">
        <v-btn
          @click="showComposer = true"
          color="primary"
          variant="flat"
          prepend-icon="mdi-email-edit"
        >
          Compose Email
        </v-btn>
        <v-btn
          @click="loadEmailThread"
          variant="text"
          icon="mdi-refresh"
          :loading="isRefreshing"
          size="small"
        >
          <v-tooltip activator="parent">Refresh Emails</v-tooltip>
        </v-btn>
      </div>

      <!-- Email Thread List -->
      <div v-if="emailThreads.length > 0" class="email-threads">
        <div class="text-subtitle-1 mb-3">Email History</div>
        <v-timeline side="end" density="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="small"
          >
            <template v-slot:opposite>
              <div class="text-caption">
                {{ formatDate(email.timestamp) }}
              </div>
            </template>
            
            <v-card variant="outlined">
              <v-card-subtitle class="d-flex align-center">
                <span class="text-body-2">
                  {{ email.direction === 'sent' ? 'To' : 'From' }}: 
                  {{ email.direction === 'sent' ? email.to : email.from }}
                </span>
              </v-card-subtitle>
              
              <v-card-text>
                <div class="text-body-2 font-weight-medium mb-2">{{ email.subject }}</div>
                <div class="email-content" v-html="formatEmailContent(email.content)"></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"
                  >
                    {{ attachment.name }}
                  </v-chip>
                </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="800" persistent>
      <v-card>
        <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="comfortable"
            class="mb-4"
          />

          <!-- Quick Actions -->
          <div class="mb-3">
            <span class="text-body-2 mr-2">Quick Insert:</span>
            <v-btn
              v-if="hasEOI"
              @click="insertEOILink"
              size="small"
              variant="tonal"
              prepend-icon="mdi-file-document"
            >
              EOI Link
            </v-btn>
            <v-btn
              @click="insertFormLink"
              size="small"
              variant="tonal"
              prepend-icon="mdi-form-select"
              class="ml-2"
            >
              Interest Form
            </v-btn>
            <v-btn
              v-if="hasBerth"
              @click="insertBerthInfo"
              size="small"
              variant="tonal"
              prepend-icon="mdi-anchor"
              class="ml-2"
            >
              Berth Info
            </v-btn>
          </div>

          <!-- Email Content -->
          <v-textarea
            v-model="emailDraft.content"
            label="Email Content"
            variant="outlined"
            rows="12"
            placeholder="Write your email here..."
            ref="contentTextarea"
          />

          <!-- 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"
                  />
                </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">
              <v-btn value="upload" size="small">
                <v-icon start>mdi-upload</v-icon>
                Upload Files
              </v-btn>
              <v-btn value="browse" size="small">
                <v-icon start>mdi-folder-open</v-icon>
                Browse Files
              </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="comfortable"
              multiple
              chips
              prepend-icon="mdi-paperclip"
              show-size
            />
            
            <!-- Browse Mode -->
            <div v-else>
              <v-btn
                @click="openFileBrowser"
                variant="outlined"
                block
                size="large"
                prepend-icon="mdi-folder-open"
              >
                Browse Files
              </v-btn>
            </div>

            <!-- Selected Files Preview -->
            <div v-if="selectedBrowserFiles.length > 0" class="mt-3">
              <div class="text-caption mb-2">Selected from browser:</div>
              <v-chip
                v-for="(file, i) in selectedBrowserFiles"
                :key="i"
                size="small"
                color="primary"
                variant="tonal"
                closable
                @click:close="removeBrowserFile(i)"
                class="mr-2 mb-2"
              >
                <v-icon start size="small">mdi-file</v-icon>
                {{ file.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="1200" height="80vh">
      <v-card height="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);">
          <FileBrowser
            selection-mode
            @file-selected="handleFileSelected"
          />
        </v-card-text>
      </v-card>
    </v-dialog>
  </div>
</template>

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

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

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

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 emailDraft = ref<{
  subject: string;
  content: string;
  attachments: File[];
}>({
  subject: '',
  content: '',
  attachments: []
});

// Check for stored session on mount
onMounted(() => {
  const storedSession = localStorage.getItem('emailSessionId');
  if (storedSession) {
    sessionId.value = storedSession;
    hasEmailCredentials.value = true;
  }
  
  // Load signature config
  const storedSignature = localStorage.getItem('emailSignature');
  if (storedSignature) {
    signatureConfig.value = JSON.parse(storedSignature);
  }
  
  loadEmailThread();
  
  // Auto-refresh every 30 seconds
  const refreshInterval = setInterval(() => {
    loadEmailThread();
  }, 30000);
  
  // Clean up interval on unmount
  onUnmounted(() => {
    clearInterval(refreshInterval);
  });
});

// Check if interest has EOI or berth
const hasEOI = computed(() => {
  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 () => {
  isRefreshing.value = true;
  try {
    const response = await $fetch<{
      success: boolean;
      emails: any[];
    }>('/api/email/fetch-thread', {
      method: 'POST',
      headers: {
        'x-tag': '094ut234'
      },
      body: {
        email: props.interest['Email Address']
      }
    });
    
    if (response.success) {
      emailThreads.value = response.emails || [];
    }
  } catch (error) {
    console.error('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 {
          const formData = new FormData();
          formData.append('file', file);
          
          // Use the client's name for the attachment folder
          const clientName = props.interest['Full Name']
            .toLowerCase()
            .replace(/\s+/g, '-')
            .replace(/[^a-z0-9-]/g, '');
          
          const uploadResponse = await $fetch<{ 
            success: boolean; 
            path: string; 
            fileName: string 
          }>('/api/files/upload', {
            method: 'POST',
            headers: {
              'x-tag': '094ut234'
            },
            query: {
              path: `${clientName}-attachments`,
              bucket: 'client-emails'
            },
            body: formData
          });
          
          if (uploadResponse.success) {
            uploadedAttachments.push({
              name: file.name,
              path: uploadResponse.path
            });
          }
        } catch (uploadError) {
          console.error('Failed to upload attachment:', uploadError);
          toast.error(`Failed to upload ${file.name}`);
        }
      }
    }
    
    // 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');
      
      // Add to thread
      emailThreads.value.unshift({
        direction: 'sent',
        to: props.interest['Email Address'],
        subject: emailDraft.value.subject,
        content: emailDraft.value.content,
        timestamp: new Date().toISOString(),
        attachments: emailDraft.value.attachments.map((f: File) => ({ name: f.name }))
      });
      
      // 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 = [];
};

const removeBrowserFile = (index: number) => {
  selectedBrowserFiles.value.splice(index, 1);
};

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

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 = () => {
  showFileBrowser.value = true;
};

const handleFileSelected = (file: any) => {
  // Check if file is already selected
  const exists = selectedBrowserFiles.value.some(f => f.name === file.name);
  if (!exists) {
    selectedBrowserFiles.value.push(file);
  }
  toast.success(`Added ${file.displayName || file.name} to attachments`);
};
</script>

<style scoped>
.email-content {
  max-height: 200px;
  overflow-y: auto;
  line-height: 1.6;
}

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

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

.email-threads {
  max-height: 600px;
  overflow-y: auto;
}
</style>
