<!-- /src/views/payments/PaymentListView.vue -->
<template>
  <div class="payment-list-view">
    <PageHeader :title="$t('payments.title')" :subtitle="$t('payments.subtitle')">
      <PermissionGate permission="payments:create">
        <Button :label="$t('payments.addPayment')" icon="pi pi-plus" severity="success" @click="openCreateModal" />
      </PermissionGate>
    </PageHeader>

    <DataTableWrapper
      :items="items"
      :totalCount="totalCount"
      :page="queryParams.page"
      :limit="queryParams.limit"
      :sortBy="queryParams.sortBy"
      :sortOrder="queryParams.sortOrder"
      :loading="isLoading"
      @page-change="onPageChange"
      @sort-change="onSort"
      @search-change="onSearch"
    >
      <Column field="user" header="نام دانشجو / کاربر">
        <template #body="{ data }">
          <router-link :to="`/payments/view/${data._id || data.id}`" class="font-bold text-color hover:text-primary">
            {{ data.user?.name || data.userName || 'کاربر' }}
          </router-link>
        </template>
      </Column>

      <Column field="classes" header="کلاس‌های مربوطه">
        <template #body="{ data }">
          <div class="flex flex-wrap gap-1" v-if="data.classes && data.classes.length">
            <Tag v-for="c in data.classes" :key="c._id || c" :value="c.name || 'کلاس'" severity="info" class="text-xs" />
          </div>
          <span v-else-if="data.course" class="text-muted text-xs">{{ data.course?.title }}</span>
          <span v-else class="text-muted text-xs">-</span>
        </template>
      </Column>

      <Column field="amount" header="مبلغ کل (تومان)" sortable>
        <template #body="{ data }">
          <div>{{ toPersianDigits(getPayableAmount(data).toLocaleString()) }} تومان</div>
          <small v-if="data.discount" class="text-muted text-xs">
            تخفیف {{ toPersianDigits((data.discount || 0).toLocaleString()) }} تومان
          </small>
        </template>
      </Column>

      <Column field="paidAmount" header="مبلغ پرداختی">
        <template #body="{ data }">
          {{ toPersianDigits((data.paidAmount || 0).toLocaleString()) }} تومان
        </template>
      </Column>

      <Column field="dueDate" header="تاریخ سررسید" sortable>
        <template #body="{ data }">
          {{ formatJalali(data.dueDate) }}
        </template>
      </Column>

      <Column field="status" header="وضعیت">
        <template #body="{ data }">
          <StatusTag :status="data.status" type="payment" />
        </template>
      </Column>

      <Column header="عملیات" style="width: 110px">
        <template #body="{ data }">
          <div class="flex align-items-center gap-1">
            <PermissionGate permission="payments:read">
              <Button icon="pi pi-eye" text rounded size="small" v-tooltip.top="'مشاهده'" @click="$router.push(`/payments/view/${data._id || data.id}`)" />
            </PermissionGate>

            <PermissionGate permission="payments:delete">
              <Button icon="pi pi-trash" text rounded size="small" severity="danger" v-tooltip.top="'حذف'" @click="confirmDelete(data)" />
            </PermissionGate>
          </div>
        </template>
      </Column>
    </DataTableWrapper>

    <!-- Create Payment Modal -->
    <Dialog v-model:visible="showCreateModal" header="ایجاد صورتحساب جدید" modal :style="{ width: '520px' }">
      <div class="flex flex-column gap-3 py-2">
        <div class="flex flex-column gap-2">
          <label class="font-semibold text-sm">انتخاب یک یا چند کلاس *</label>
          <MultiSelect
            v-model="createForm.classes"
            :options="classesList"
            optionLabel="name"
            optionValue="_id"
            display="chip"
            filter
            placeholder="ابتدا کلاس‌ها را انتخاب کنید"
            class="w-full text-sm"
            @change="onClassesSelected"
          />
        </div>

        <div class="flex flex-column gap-2">
          <label class="font-semibold text-sm">انتخاب کاربر / دانشجو *</label>
          <Dropdown
            v-model="createForm.user"
            :options="eligibleUsers"
            optionLabel="fullName"
            optionValue="_id"
            filter
            :placeholder="createForm.classes?.length ? 'دانشجوی ثبت‌نام‌شده را انتخاب کنید' : 'ابتدا کلاس را انتخاب کنید'"
            class="w-full text-sm"
            :disabled="!createForm.classes?.length"
          />
          <small v-if="createForm.classes?.length && !eligibleUsers.length" class="text-orange-500">
            هیچ دانشجوی ثبت‌نام‌شده‌ای در کلاس‌های انتخاب‌شده یافت نشد
          </small>
        </div>

        <div class="flex flex-column gap-2">
          <label class="font-semibold text-sm" for="invoice-amount">مبلغ کل صورتحساب (تومان) *</label>
          <InputNumber inputId="invoice-amount" v-model="createForm.amount" class="w-full text-sm" suffix=" تومان" :min="0" />
        </div>

        <div class="flex align-items-center gap-2">
          <Checkbox v-model="hasDiscount" binary inputId="invoice-discount" />
          <label for="invoice-discount" class="font-semibold text-sm cursor-pointer">تخفیف ؟</label>
        </div>

        <div v-if="hasDiscount" class="flex flex-column gap-2">
          <label class="font-semibold text-sm" for="invoice-discount-amount">مبلغ تخفیف (تومان)</label>
          <InputNumber
            inputId="invoice-discount-amount"
            v-model="createForm.discount"
            class="w-full text-sm"
            suffix=" تومان"
            :min="0"
            :max="createForm.amount || 0"
          />
          <small class="font-semibold text-color">
            مبلغ نهایی: {{ toPersianDigits(createPayableAmount.toLocaleString()) }} تومان
          </small>
        </div>

        <div class="flex flex-column gap-2">
          <label class="font-semibold text-sm">تاریخ سررسید *</label>
          <DatePicker v-model="createForm.dueDate" class="w-full text-sm" placeholder="1403/01/01" />
        </div>

        <div class="flex flex-column gap-2">
          <label class="font-semibold text-sm" for="invoice-notes">یادداشت</label>
          <Textarea
            id="invoice-notes"
            v-model="createForm.notes"
            rows="3"
            class="w-full text-sm"
            maxlength="5000"
            placeholder="یادداشت داخلی درباره این صورتحساب…"
          />
        </div>

        <NotifyChannelsField :notify="createNotify" />
      </div>
      <template #footer>
        <Button label="انصراف" text severity="secondary" @click="showCreateModal = false" />
        <Button label="ایجاد صورتحساب" icon="pi pi-check" severity="success" :loading="isCreating" @click="handleCreatePayment" />
      </template>
    </Dialog>

    <ConfirmDeleteDialog
      v-model="deleteDialogVisible"
      :loading="isDeleting"
      @confirm="handleDelete"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useDataTable } from '@/composables/useDataTable';
import { usePersianDate } from '@/composables/usePersianDate';
import { useToast } from '@/composables/useToast';
import { paymentApi } from '@/api/paymentApi';
import { userApi } from '@/api/userApi';
import { classApi } from '@/api/classApi';
import PageHeader from '@/components/common/PageHeader.vue';
import DataTableWrapper from '@/components/common/DataTableWrapper.vue';
import ConfirmDeleteDialog from '@/components/common/ConfirmDeleteDialog.vue';
import PermissionGate from '@/components/common/PermissionGate.vue';
import StatusTag from '@/components/common/StatusTag.vue';
import NotifyChannelsField from '@/components/common/NotifyChannelsField.vue';
import { getPayableAmount } from '@/utils/paymentAmount';
import Button from 'primevue/button';
import Column from 'primevue/column';
import Tag from 'primevue/tag';
import Dialog from 'primevue/dialog';
import Dropdown from 'primevue/select';
import MultiSelect from 'primevue/multiselect';
import InputNumber from 'primevue/inputnumber';
import Checkbox from 'primevue/checkbox';
import Textarea from 'primevue/textarea';
import DatePicker from 'vue3-persian-datetime-picker';

const { toPersianDigits, formatJalali } = usePersianDate();
const { showSuccess, showError } = useToast();

const {
  items,
  totalCount,
  isLoading,
  queryParams,
  loadData,
  onPageChange,
  onSort,
  onSearch
} = useDataTable(paymentApi.getAll);

const showCreateModal = ref(false);
const usersList = ref([]);
const classesList = ref([]);
const isCreating = ref(false);

const createForm = reactive({
  user: null,
  classes: [],
  amount: 0,
  discount: 0,
  notes: '',
  dueDate: ''
});
const hasDiscount = ref(false);
const createNotify = reactive({ sms: true, email: true, bot: true });
const createPayableAmount = computed(() => getPayableAmount({
  amount: createForm.amount,
  discount: hasDiscount.value ? createForm.discount : 0
}));

const deleteDialogVisible = ref(false);
const selectedPayment = ref(null);
const isDeleting = ref(false);

const studentIdOf = (student) => String(student?._id || student?.id || student);

const eligibleUsers = computed(() => {
  if (!createForm.classes?.length) return [];

  const selectedIds = new Set(createForm.classes.map(String));
  const selectedClasses = classesList.value.filter((c) =>
    selectedIds.has(String(c._id || c.id))
  );
  if (!selectedClasses.length) return [];

  // Intersection: user must be registered in every selected class
  let eligibleIds = null;
  selectedClasses.forEach((cls) => {
    const ids = new Set((cls.students || []).map(studentIdOf));
    if (eligibleIds === null) {
      eligibleIds = ids;
    } else {
      eligibleIds = new Set([...eligibleIds].filter((id) => ids.has(id)));
    }
  });

  return usersList.value.filter((u) => eligibleIds?.has(String(u._id || u.id)));
});

const onClassesSelected = () => {
  if (createForm.user && !eligibleUsers.value.some((u) => (u._id || u.id) === createForm.user)) {
    createForm.user = null;
  }

  if (!createForm.classes || createForm.classes.length === 0) {
    createForm.amount = 0;
    createForm.discount = 0;
    return;
  }
  let totalFee = 0;
  createForm.classes.forEach((classId) => {
    const c = classesList.value.find((item) => (item._id || item.id) === classId);
    if (c) {
      totalFee += (c.tuitionFee || c.course?.price || 0);
    }
  });
  if (totalFee > 0) {
    createForm.amount = totalFee;
  }
  if ((createForm.discount || 0) > (createForm.amount || 0)) {
    createForm.discount = createForm.amount || 0;
  }
};

const resetCreateForm = () => {
  createForm.user = null;
  createForm.classes = [];
  createForm.amount = 0;
  createForm.discount = 0;
  createForm.notes = '';
  createForm.dueDate = '';
  hasDiscount.value = false;
  createNotify.sms = true;
  createNotify.email = true;
  createNotify.bot = true;
};

const openCreateModal = () => {
  resetCreateForm();
  showCreateModal.value = true;
};

const fetchDropdownData = async () => {
  try {
    const [uRes, cRes] = await Promise.all([
      userApi.getAll({ limit: 200 }),
      classApi.getAll({ limit: 100 })
    ]);
    const uData = uRes.data || uRes;
    const rawUsers = uData.items || uData.users || uData || [];
    usersList.value = rawUsers.map((u) => ({ ...u, fullName: u.name || '' }));

    const cData = cRes.data || cRes;
    classesList.value = cData.items || cData.classes || cData || [];
  } catch (e) {
    console.warn('Dropdown fetch error:', e);
  }
};

const handleCreatePayment = async () => {
  if (!createForm.classes?.length) { showError('لطفا کلاس را انتخاب کنید'); return; }
  if (!createForm.user) { showError('لطفا کاربر را انتخاب کنید'); return; }
  if (!createForm.amount) { showError('لطفا مبلغ را وارد کنید'); return; }
  if (!createForm.dueDate) { showError('لطفا تاریخ سررسید را وارد کنید'); return; }

  if (hasDiscount.value && (createForm.discount || 0) > createForm.amount) {
    showError('مبلغ تخفیف نمی‌تواند بیشتر از مبلغ کل باشد');
    return;
  }

  isCreating.value = true;
  try {
    await paymentApi.create({
      ...createForm,
      discount: hasDiscount.value ? (createForm.discount || 0) : 0,
      notify: { ...createNotify }
    });
    showSuccess('صورتحساب جدید با موفقیت ایجاد شد');
    showCreateModal.value = false;
    loadData();
  } catch (err) {
    showError(err);
  } finally {
    isCreating.value = false;
  }
};

const confirmDelete = (payment) => {
  selectedPayment.value = payment;
  deleteDialogVisible.value = true;
};

const handleDelete = async () => {
  if (!selectedPayment.value) return;
  isDeleting.value = true;
  try {
    await paymentApi.delete(selectedPayment.value._id || selectedPayment.value.id);
    showSuccess('صورتحساب با موفقیت حذف شد');
    deleteDialogVisible.value = false;
    loadData();
  } catch (err) {
    showError(err);
  } finally {
    isDeleting.value = false;
  }
};

onMounted(() => {
  loadData();
  fetchDropdownData();
});
</script>
