<template>
  <div class="w-full sm:w-1/2 md:w-1/3 lg:w-1/4 p-2">
    <div class="inner-doc p-4 rounded">
      <h3>Сформированный документ</h3>

      <div class="mt-3">
        <p class="inner-doc-small-gray">Дата формирования документа {{ formatDate(innerDoc.created_at) }}</p>
      </div>

      <!-- Сторона 1 -->
      <div class="clients-inner-doc mt-4">
        <h4 class="inner-doc-title">Сторона 1:</h4>
        <div v-for="side in currentDeal.side_one || []" :key="side.client_id" class="mt-2 flex items-baseline">
          <span style="margin-right: 10px;" class="font-medium min-w-[80px]">{{ side.role }}:</span>
          <div class="ml-2 underline">
            <span>{{ getClientName(side) }} ({{ side.phone }})</span>
          </div>
        </div>
      </div>

      <!-- Сторона 2 -->
      <div class="clients-inner-doc mt-4">
        <h4 class="inner-doc-title">Сторона 2:</h4>
        <div v-for="side in currentDeal.side_two || []" :key="side.client_id" class="mt-2 flex items-baseline">
          <span style="margin-right: 10px;" class="font-medium min-w-[80px]">{{ side.role }}:</span>
          <div class="ml-2 underline">
            <span>{{ getClientName(side) }} ({{ side.phone }})</span>
          </div>
        </div>
      </div>

      <div class="clients-inner-doc mt-4">
        <h4 class="inner-doc-title">Комментарий:</h4>
        <p class="mt-2">{{ currentPivot?.comment || 'Нет комментария' }}</p>
      </div>

      <div class="clients-inner-doc mt-4">
        <h4 class="inner-doc-title">Документ:</h4>
      </div>

      <div class="flex flex-col flex-grow mt-4">
        <div class="mt-2 flex space-x-2">
          <img src="@/shared/assets/icons/doc.svg" alt="Договор" class="w-5 h-5">
          <a :href="`/api/inner-docs/${innerDoc.id}/download`" target="_blank" class="inner-doc-small-gray underline">{{ innerDoc.name }}.pdf</a>
        </div>
      </div>

      <div class="mt-4">
        <p class="inner-doc-small-gray">{{ innerDoc.creator.last_name }} {{ innerDoc.creator.first_name }}</p>
      </div>

      <div class="mt-4 flex">
        <button @click="previewInnerDocVue(innerDoc.id ? innerDoc.id : '')">
<!--          <img src="@/shared/assets/icons/view.svg" alt="Предпросмотр">-->
          <span class="simple-button settings" title="Предпросмотр"><i class="far fa-eye"></i></span>
        </button>
        <button @click="sendInnerDocVue(innerDoc.id ? innerDoc.id : '')">
<!--          <img style="margin-left: 5px;" src="@/shared/assets/icons/send.svg" alt="Отправить">-->
          <span style="margin-left: 5px;" class="simple-button settings" title="Отправить"><i class="ti-write"></i></span>
        </button>
        <button @click="editInnerDocVue(innerDoc.id ? innerDoc.id : '')">
<!--          <img src="@/shared/assets/icons/edit.svg" alt="Редактировать" class="w-6 h-6">-->
          <span style="margin-left: 5px;" class="simple-button settings" title="Редактировать"><i class="jw-action-icon-settings"></i></span>
        </button>
        <button @click="handleRemoveDealDoc($event)">
<!--          <img src="@/shared/assets/icons/trash.svg" alt="Удалить" class="w-6 h-6">-->
          <span style="margin-left: 5px;" class="simple-button delete" title="Удалить"><i class="jw-action-icon-delete"></i></span>
        </button>
      </div>

    </div>
  </div>
</template>


<script setup>
import { computed } from 'vue';
import { useConfirm } from 'primevue/useconfirm';
import { useToast } from 'primevue/usetoast';
import dayjs from 'dayjs';
import 'dayjs/locale/ru';

console.log('Запуск InnerDocCard');

const props = defineProps({
  innerDoc: {
    type: Object,
    required: true,
  },
  dealClients: {
    type: Object,
    default: () => ({ side_one_clients: [], side_two_clients: [] })
  }
});

const emit = defineEmits(['remove']);

const confirm = useConfirm();
const toast = useToast();

const currentDeal = computed(() => {
  console.log('currentDeal', props.innerDoc.deals);
  return props.innerDoc.deals?.[0] || {};
});

// Получаем pivot данные для текущего документа
const currentPivot = computed(() => {
  return props.innerDoc.deals?.[0]?.pivot;
});

// Получаем имя клиента по ID
const getClientName = (client) => {
  return client?.fio || `${client.client_id}`;
};

const handleEditInnerDoc = () => {
  emit('edit', props.innerDoc);
};

const handleRemoveDealDoc = (event) => {
  confirm.require({
    target: event.currentTarget,
    message: `Вы уверены, что хотите удалить документ "${props.innerDoc.name}"?`,
    header: 'Подтверждение удаления',
    icon: 'pi pi-exclamation-triangle',
    acceptLabel: 'Удалить',
    rejectLabel: 'Отмена',
    acceptClass: 'p-button-danger',
    accept: async () => {
      try {
        emit('remove', props.innerDoc.id);
        toast.add({
          severity: 'success',
          summary: 'Успешно',
          detail: 'Документ удалён',
          life: 3000
        });
      } catch (error) {
        toast.add({
          severity: 'error',
          summary: 'Ошибка',
          detail: 'Не удалось удалить документ',
          life: 3000
        });
      }
    },
    reject: () => {
      toast.add({
        severity: 'info',
        summary: 'Отменено',
        detail: 'Удаление отменено',
        life: 2000
      });
    }
  });
};

// const formatDate = (dateString) => {
//   return new Date(dateString).toLocaleDateString('ru-RU', {
//     day: '2-digit',
//     month: '2-digit',
//     year: 'numeric',
//     hour: '2-digit',
//     minute: '2-digit'
//   });
// };
const formatDate = (dateString) => {
  if (!dateString) return '—';
  // Поддерживаем разные форматы
  const parsed = dayjs(dateString, [
    'YYYY-MM-DD HH:mm:ss',
    'DD.MM.YYYY HH:mm:ss',
    'DD.MM.YY HH:mm',
    'DD.MM.YYYY',
    'YYYY-MM-DDTHH:mm:ssZ'
  ], true); // strict parsing

  return parsed.isValid()
      ? parsed.locale('ru').format('DD.MM.YYYY HH:mm')
      : '—';
};


const previewInnerDocVue = (docId) => {
  if (docId) {
    previewInnerDoc(docId);
  } else {
    console.error('ID документа не найден!');
  }
};

const sendInnerDocVue = (docId) => {
  if (docId) {
    sendInnerDocWin(docId);
  } else {
    console.error('ID документа не найден!');
  }
};

const editInnerDocVue = (docId) => {
  if (docId) {
    editInnerDoc(docId);
  } else {
    console.error('ID документа не найден!');
  }
};

</script>

<style scoped>
.addDeal__form {
  .inner-doc {
    background: linear-gradient(360deg, #F5F5F5 0%, #FFFFFF 100%);
    border: 1px solid #E0E0E0;
    border-radius: 5px;
    padding: 10px;

    a {
      border: none;
    }
    h3 {
      font-family: 'Lato', sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 18px;
      line-height: 22px;
      color: #000000;
    }
    .inner-doc-title {
      color: #757575;
      font-family: 'Lato',sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 18px;
      line-height: 22px;
    }
    .inner-doc-small-gray {
      color: #757575;
      font-family: 'Lato', sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 14px;
      line-height: 17px;
    }
  }
}
</style>