<script lang="ts" setup>
import { computed, ref } from 'vue'
import { router, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import DateRangePicker from '@/Components/Admin/DateRangePicker.vue'
import ReportChart from '@/Components/Admin/ReportChart.vue'
import type {
  ReportType,
  ReportMeta,
  RevenueReportData,
  ProfitLossReportData,
  TaxReportData,
  AgingReportData,
  RefundReportData,
  SubscriptionReportData,
} from '@/types'

defineOptions({ layout: AdminLayout })

type ReportData = RevenueReportData | ProfitLossReportData | TaxReportData | AgingReportData | RefundReportData | SubscriptionReportData

interface Props {
  reportType: ReportType
  reportData: ReportData
  reportMeta: ReportMeta
}

const props = defineProps<Props>()

const dateRange = ref({
  start_date: props.reportMeta.start_date ?? '',
  end_date: props.reportMeta.end_date ?? '',
})

const serviceTypeFilter = ref<string | null>(props.reportMeta.service_type ?? null)

const reportTitles: Record<ReportType, string> = {
  revenue: 'Revenue Report',
  profit_loss: 'Profit & Loss Report',
  tax: 'Tax Report',
  aging: 'Aging Report',
  refund: 'Refund Report',
  subscription: 'Subscription Report',
}

const reportTitle = computed<string>(() => reportTitles[props.reportType] ?? 'Report')

const showDateRange = computed<boolean>(() => props.reportType !== 'aging')
const showServiceTypeFilter = computed<boolean>(() => props.reportType === 'revenue')

const serviceTypeOptions = [
  { title: 'All Types', value: null },
  { title: 'VPS', value: 'vps' },
  { title: 'Dedicated', value: 'dedicated' },
  { title: 'Hosting', value: 'hosting' },
  { title: 'Game', value: 'game' },
]

function formatCurrency(value: number | string): string {
  const num = typeof value === 'string' ? parseFloat(value) : value
  return `$${num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}

function regenerate(): void {
  const payload: Record<string, unknown> = { report_type: props.reportType }
  if (showDateRange.value) {
    payload.start_date = dateRange.value.start_date
    payload.end_date = dateRange.value.end_date
  }
  if (showServiceTypeFilter.value && serviceTypeFilter.value) {
    payload.service_type = serviceTypeFilter.value
  }
  router.post('/reports/generate', payload)
}

function exportReport(format: string): void {
  const form = useForm({
    report_type: props.reportType,
    start_date: dateRange.value.start_date || null,
    end_date: dateRange.value.end_date || null,
    service_type: serviceTypeFilter.value,
    format,
  })
  form.post('/reports/export', {
    forceFormData: false,
  })
}

// Type-specific computed data
const revenueData = computed<RevenueReportData | null>(() =>
  props.reportType === 'revenue' ? props.reportData as RevenueReportData : null,
)
const profitLossData = computed<ProfitLossReportData | null>(() =>
  props.reportType === 'profit_loss' ? props.reportData as ProfitLossReportData : null,
)
const taxData = computed<TaxReportData | null>(() =>
  props.reportType === 'tax' ? props.reportData as TaxReportData : null,
)
const agingData = computed<AgingReportData | null>(() =>
  props.reportType === 'aging' ? props.reportData as AgingReportData : null,
)
const refundData = computed<RefundReportData | null>(() =>
  props.reportType === 'refund' ? props.reportData as RefundReportData : null,
)
const subscriptionData = computed<SubscriptionReportData | null>(() =>
  props.reportType === 'subscription' ? props.reportData as SubscriptionReportData : null,
)

// Chart data transforms
const revenueChartData = computed(() =>
  revenueData.value?.by_period.map(p => ({ name: p.period, value: p.amount })) ?? [],
)
const revenueGatewayChartData = computed(() =>
  revenueData.value?.by_gateway.map(g => ({ name: g.gateway, value: g.amount })) ?? [],
)
const taxCountryChartData = computed(() =>
  taxData.value?.by_country.map(c => ({ name: c.country, value: c.amount })) ?? [],
)
const refundMonthChartData = computed(() =>
  refundData.value?.by_month.map(m => ({ name: m.month, value: m.amount })) ?? [],
)

// Aging table headers
const agingInvoiceHeaders = [
  { title: 'Invoice #', key: 'invoice_number' },
  { title: 'Customer', key: 'customer' },
  { title: 'Amount', key: 'amount' },
  { title: 'Due Date', key: 'due_date' },
  { title: 'Days Overdue', key: 'days_overdue' },
]

function agingBracketColor(days: number): string {
  if (days <= 30) return 'success'
  if (days <= 60) return 'warning'
  if (days <= 90) return 'error'
  return 'error'
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="d-flex align-center gap-2">
          <VBtn
            icon="tabler-arrow-left"
            variant="text"
            size="small"
            @click="router.visit('/reports')"
          />
          <div class="text-h4 font-weight-bold">
            {{ reportTitle }}
          </div>
        </div>
        <div v-if="reportMeta.start_date" class="text-body-2 text-medium-emphasis ms-10">
          {{ reportMeta.start_date }} to {{ reportMeta.end_date }}
          <span v-if="reportMeta.service_type"> &middot; {{ reportMeta.service_type }}</span>
        </div>
      </div>
      <div class="d-flex gap-2">
        <VBtn
          color="error"
          variant="tonal"
          size="small"
          prepend-icon="tabler-file-type-pdf"
          @click="exportReport('pdf')"
        >
          PDF
        </VBtn>
        <VBtn
          color="success"
          variant="tonal"
          size="small"
          prepend-icon="tabler-file-type-csv"
          @click="exportReport('csv')"
        >
          CSV
        </VBtn>
        <VBtn
          color="info"
          variant="tonal"
          size="small"
          prepend-icon="tabler-braces"
          @click="exportReport('json')"
        >
          JSON
        </VBtn>
      </div>
    </div>

    <!-- Filters -->
    <VCard v-if="showDateRange" class="mb-6">
      <VCardText>
        <DateRangePicker v-model="dateRange" />
        <VRow v-if="showServiceTypeFilter" class="mt-2">
          <VCol cols="12" sm="4">
            <VSelect
              v-model="serviceTypeFilter"
              :items="serviceTypeOptions"
              label="Service Type"
              density="compact"
              variant="outlined"
              clearable
            />
          </VCol>
        </VRow>
        <div class="d-flex justify-end mt-2">
          <VBtn color="primary" @click="regenerate">
            <VIcon icon="tabler-refresh" start />
            Regenerate
          </VBtn>
        </div>
      </VCardText>
    </VCard>

    <!-- Revenue Report -->
    <template v-if="reportType === 'revenue' && revenueData">
      <VRow class="mb-4">
        <VCol cols="12">
          <VCard>
            <VCardText class="text-center py-6">
              <div class="text-h3 font-weight-bold text-success">
                {{ formatCurrency(revenueData.total_revenue) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Total Revenue
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>

      <VRow class="mb-4">
        <VCol cols="12" md="8">
          <VCard>
            <VCardTitle>Revenue by Period</VCardTitle>
            <VCardText>
              <ReportChart
                v-if="revenueChartData.length"
                type="bar"
                :data="revenueChartData"
              />
              <div v-else class="text-center py-8 text-medium-emphasis">
                No data for this period
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" md="4">
          <VCard>
            <VCardTitle>By Gateway</VCardTitle>
            <VCardText>
              <ReportChart
                v-if="revenueGatewayChartData.length"
                type="pie"
                :data="revenueGatewayChartData"
                name-key="name"
                value-key="value"
              />
              <div v-else class="text-center py-8 text-medium-emphasis">
                No data
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>

      <VRow>
        <VCol cols="12" md="6">
          <VCard>
            <VCardTitle>By Service Type</VCardTitle>
            <VCardText>
              <VTable density="compact">
                <thead>
                  <tr>
                    <th>Type</th>
                    <th class="text-right">
                      Amount
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="row in revenueData.by_service_type" :key="row.type">
                    <td>
                      <VChip size="small" color="primary" variant="tonal">
                        {{ row.type }}
                      </VChip>
                    </td>
                    <td class="text-right">
                      {{ formatCurrency(row.amount) }}
                    </td>
                  </tr>
                  <tr v-if="!revenueData.by_service_type.length">
                    <td colspan="2" class="text-center text-medium-emphasis">
                      No data
                    </td>
                  </tr>
                </tbody>
              </VTable>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" md="6">
          <VCard>
            <VCardTitle>By Plan</VCardTitle>
            <VCardText>
              <VTable density="compact">
                <thead>
                  <tr>
                    <th>Plan</th>
                    <th class="text-right">
                      Amount
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="row in revenueData.by_plan" :key="row.plan">
                    <td>{{ row.plan }}</td>
                    <td class="text-right">
                      {{ formatCurrency(row.amount) }}
                    </td>
                  </tr>
                  <tr v-if="!revenueData.by_plan.length">
                    <td colspan="2" class="text-center text-medium-emphasis">
                      No data
                    </td>
                  </tr>
                </tbody>
              </VTable>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </template>

    <!-- Profit & Loss Report -->
    <template v-if="reportType === 'profit_loss' && profitLossData">
      <VRow class="mb-4">
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div class="text-h5 font-weight-bold text-success">
                {{ formatCurrency(profitLossData.revenue) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Revenue
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div class="text-h5 font-weight-bold text-error">
                {{ formatCurrency(profitLossData.refunds) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Refunds
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div class="text-h5 font-weight-bold text-warning">
                {{ formatCurrency(profitLossData.gateway_fees) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Gateway Fees
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div
                class="text-h5 font-weight-bold"
                :class="profitLossData.net_profit >= 0 ? 'text-success' : 'text-error'"
              >
                {{ formatCurrency(profitLossData.net_profit) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Net Profit
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>

      <VRow>
        <VCol cols="12" md="8">
          <VCard>
            <VCardTitle>Profit & Loss Statement</VCardTitle>
            <VCardText>
              <VTable density="compact">
                <tbody>
                  <tr>
                    <td class="font-weight-bold text-uppercase text-body-2 text-medium-emphasis" colspan="2">
                      Revenue
                    </td>
                  </tr>
                  <tr>
                    <td>Gross Revenue</td>
                    <td class="text-right text-success">
                      {{ formatCurrency(profitLossData.revenue) }}
                    </td>
                  </tr>
                  <tr>
                    <td class="font-weight-bold text-uppercase text-body-2 text-medium-emphasis" colspan="2">
                      Expenses
                    </td>
                  </tr>
                  <tr>
                    <td>Refunds</td>
                    <td class="text-right text-error">
                      ({{ formatCurrency(profitLossData.refunds) }})
                    </td>
                  </tr>
                  <tr>
                    <td>Gateway Fees</td>
                    <td class="text-right text-error">
                      ({{ formatCurrency(profitLossData.gateway_fees) }})
                    </td>
                  </tr>
                  <tr>
                    <td>Infrastructure Cost (Est.)</td>
                    <td class="text-right text-error">
                      ({{ formatCurrency(profitLossData.infrastructure_cost) }})
                    </td>
                  </tr>
                  <tr>
                    <td colspan="2">
                      <VDivider />
                    </td>
                  </tr>
                  <tr>
                    <td class="font-weight-bold text-subtitle-1">
                      Net Profit
                    </td>
                    <td
                      class="text-right font-weight-bold text-subtitle-1"
                      :class="profitLossData.net_profit >= 0 ? 'text-success' : 'text-error'"
                    >
                      {{ formatCurrency(profitLossData.net_profit) }}
                    </td>
                  </tr>
                </tbody>
              </VTable>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" md="4">
          <VCard>
            <VCardText class="text-center py-8">
              <div
                class="text-h2 font-weight-bold"
                :class="profitLossData.margin_percentage >= 0 ? 'text-success' : 'text-error'"
              >
                {{ profitLossData.margin_percentage }}%
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Profit Margin
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </template>

    <!-- Tax Report -->
    <template v-if="reportType === 'tax' && taxData">
      <VRow class="mb-4">
        <VCol cols="12">
          <VCard>
            <VCardText class="text-center py-6">
              <div class="text-h3 font-weight-bold text-warning">
                {{ formatCurrency(taxData.total_tax) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Total Tax Collected
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>

      <VRow>
        <VCol cols="12" md="5">
          <VCard>
            <VCardTitle>Tax by Country</VCardTitle>
            <VCardText>
              <ReportChart
                v-if="taxCountryChartData.length"
                type="pie"
                :data="taxCountryChartData"
              />
              <div v-else class="text-center py-8 text-medium-emphasis">
                No tax data
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" md="7">
          <VCard>
            <VCardTitle>Breakdown by Country</VCardTitle>
            <VCardText>
              <VTable density="compact">
                <thead>
                  <tr>
                    <th>Country</th>
                    <th class="text-right">
                      Tax Amount
                    </th>
                    <th class="text-center">
                      Invoices
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="row in taxData.by_country" :key="row.country">
                    <td>{{ row.country }}</td>
                    <td class="text-right">
                      {{ formatCurrency(row.amount) }}
                    </td>
                    <td class="text-center">
                      {{ row.invoice_count }}
                    </td>
                  </tr>
                  <tr v-if="!taxData.by_country.length">
                    <td colspan="3" class="text-center text-medium-emphasis">
                      No tax data for this period
                    </td>
                  </tr>
                </tbody>
              </VTable>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </template>

    <!-- Aging Report -->
    <template v-if="reportType === 'aging' && agingData">
      <VRow class="mb-4">
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div class="text-h5 font-weight-bold text-success">
                {{ agingData.current.count }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                0-30 Days ({{ formatCurrency(agingData.current.amount) }})
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div class="text-h5 font-weight-bold text-warning">
                {{ agingData.days_31_60.count }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                31-60 Days ({{ formatCurrency(agingData.days_31_60.amount) }})
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div class="text-h5 font-weight-bold text-error">
                {{ agingData.days_61_90.count }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                61-90 Days ({{ formatCurrency(agingData.days_61_90.amount) }})
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div class="text-h5 font-weight-bold text-error">
                {{ agingData.days_90_plus.count }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                90+ Days ({{ formatCurrency(agingData.days_90_plus.amount) }})
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>

      <VRow>
        <VCol cols="12">
          <VCard>
            <VCardTitle class="d-flex align-center justify-space-between">
              <span>Outstanding Invoices</span>
              <VChip size="small" color="error" variant="tonal">
                {{ agingData.total.count }} invoices &middot; {{ formatCurrency(agingData.total.amount) }}
              </VChip>
            </VCardTitle>
            <VCardText>
              <VDataTable
                :headers="agingInvoiceHeaders"
                :items="agingData.invoices"
                density="compact"
                :items-per-page="15"
              >
                <template #item.amount="{ item }">
                  {{ formatCurrency(item.amount) }}
                </template>
                <template #item.days_overdue="{ item }">
                  <VChip
                    :color="agingBracketColor(item.days_overdue)"
                    size="small"
                    variant="tonal"
                  >
                    {{ item.days_overdue }} days
                  </VChip>
                </template>
              </VDataTable>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </template>

    <!-- Refund Report -->
    <template v-if="reportType === 'refund' && refundData">
      <VRow class="mb-4">
        <VCol cols="12" sm="6">
          <VCard>
            <VCardText class="text-center py-6">
              <div class="text-h3 font-weight-bold text-error">
                {{ formatCurrency(refundData.total_refunds) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Total Refunds
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6">
          <VCard>
            <VCardText class="text-center py-6">
              <div class="text-h3 font-weight-bold">
                {{ refundData.refund_count }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Refund Count
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>

      <VRow>
        <VCol cols="12" md="8">
          <VCard>
            <VCardTitle>Refunds by Month</VCardTitle>
            <VCardText>
              <ReportChart
                v-if="refundMonthChartData.length"
                type="bar"
                :data="refundMonthChartData"
              />
              <div v-else class="text-center py-8 text-medium-emphasis">
                No refund data
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" md="4">
          <VCard>
            <VCardTitle>By Gateway</VCardTitle>
            <VCardText>
              <VTable density="compact">
                <thead>
                  <tr>
                    <th>Gateway</th>
                    <th class="text-right">
                      Amount
                    </th>
                    <th class="text-center">
                      Count
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="row in refundData.by_gateway" :key="row.gateway">
                    <td>{{ row.gateway }}</td>
                    <td class="text-right">
                      {{ formatCurrency(row.amount) }}
                    </td>
                    <td class="text-center">
                      {{ row.count }}
                    </td>
                  </tr>
                  <tr v-if="!refundData.by_gateway.length">
                    <td colspan="3" class="text-center text-medium-emphasis">
                      No refunds
                    </td>
                  </tr>
                </tbody>
              </VTable>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </template>

    <!-- Subscription Report -->
    <template v-if="reportType === 'subscription' && subscriptionData">
      <VRow class="mb-4">
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div class="text-h5 font-weight-bold text-success">
                {{ subscriptionData.new_subscriptions }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                New Subscriptions
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div class="text-h5 font-weight-bold text-error">
                {{ subscriptionData.cancelled_subscriptions }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Cancelled
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div class="text-h5 font-weight-bold text-warning">
                {{ subscriptionData.churn_rate }}%
              </div>
              <div class="text-body-2 text-medium-emphasis">
                Churn Rate
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6" lg="3">
          <VCard>
            <VCardText class="text-center">
              <div
                class="text-h5 font-weight-bold"
                :class="subscriptionData.mrr_change >= 0 ? 'text-success' : 'text-error'"
              >
                {{ subscriptionData.mrr_change >= 0 ? '+' : '' }}{{ formatCurrency(subscriptionData.mrr_change) }}
              </div>
              <div class="text-body-2 text-medium-emphasis">
                MRR Change
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>

      <VRow class="mb-4">
        <VCol cols="12" sm="6">
          <VCard>
            <VCardTitle>MRR at Start</VCardTitle>
            <VCardText class="text-center">
              <div class="text-h4 font-weight-bold text-primary">
                {{ formatCurrency(subscriptionData.mrr_start) }}
              </div>
            </VCardText>
          </VCard>
        </VCol>
        <VCol cols="12" sm="6">
          <VCard>
            <VCardTitle>MRR at End</VCardTitle>
            <VCardText class="text-center">
              <div class="text-h4 font-weight-bold text-primary">
                {{ formatCurrency(subscriptionData.mrr_end) }}
              </div>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>

      <VRow>
        <VCol cols="12">
          <VCard>
            <VCardTitle>Breakdown by Plan</VCardTitle>
            <VCardText>
              <VTable density="compact">
                <thead>
                  <tr>
                    <th>Plan</th>
                    <th class="text-center">
                      New
                    </th>
                    <th class="text-center">
                      Cancelled
                    </th>
                    <th class="text-center">
                      Active
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="row in subscriptionData.by_plan" :key="row.plan">
                    <td>{{ row.plan }}</td>
                    <td class="text-center text-success">
                      {{ row.new }}
                    </td>
                    <td class="text-center text-error">
                      {{ row.cancelled }}
                    </td>
                    <td class="text-center">
                      {{ row.active }}
                    </td>
                  </tr>
                  <tr v-if="!subscriptionData.by_plan.length">
                    <td colspan="4" class="text-center text-medium-emphasis">
                      No subscription data
                    </td>
                  </tr>
                </tbody>
              </VTable>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </template>
  </div>
</template>
