<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">
      
      <!-- Compose New Email -->
      <div class="mb-4">
        <v-btn
          @click="showComposer = true"
          color="primary"
          variant="flat"
          prepend-icon="mdi-email-edit"
        >
          Compose Email
        </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>
    </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"
          />

          <!-- Attachments -->
          <v-file-input
            v-model="emailDraft.attachments"
            label="Attachments"
            variant="outlined"
            density="comfortable"
            multiple
            chips
            prepend-icon="mdi-paperclip"
            class="mt-4"
          />
        </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>
  </div>
</template>

<script setup lang="ts">
import type { Interest } from '~/utils/types';

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

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

// Load email thread on mount
onMounted(() => {
  loadEmailThread();
});

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

const loadEmailThread = async () => {
  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);
  }
};

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;
  }
  
  isSending.value = true;
  
  try {
    // Format email content with proper line breaks
    const formattedContent = emailDraft.value.content
      .split('\n')
      .map(line => line.trim() ? `<p>${line}</p>` : '<br>')
      .join('');
    
    // Prepare email data
    const emailData = {
      to: props.interest['Email Address'],
      toName: props.interest['Full Name'],
      subject: emailDraft.value.subject,
      html: formattedContent,
      interestId: props.interest.Id.toString()
    };
    
    // 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: formattedContent,
        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: []
  };
};

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