<template>
  <div class="flex flex-col h-full">
    <LayoutHeader :title="$t('payments.title')">
      <template #right>
        <Button variant="subtle" @click="exportReport">
          <template #prefix>
            <FeatherIcon name="download" class="h-4 w-4" />
          </template>
          {{ $t('common.export') }}
        </Button>
      </template>
    </LayoutHeader>

    <div class="flex-1 overflow-auto">
      <!-- Tabs -->
      <div class="border-b px-5">
        <nav class="flex gap-2">
          <button
            v-for="tab in tabs"
            :key="tab.id"
            class="px-4 py-2 text-sm font-medium transition-colors"
            :class="
              activeTab === tab.id
                ? 'border-b-2 border-ink-gray-9 text-ink-gray-9'
                : 'text-ink-gray-5 hover:text-ink-gray-7'
            "
            @click="activeTab = tab.id"
          >
            {{ $t(tab.label) }}
          </button>
        </nav>
      </div>

      <div class="p-5">
        <!-- Overview Tab -->
        <div v-if="activeTab === 'overview'" class="space-y-6">
          <!-- Stats -->
          <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <StatCard
              :label="$t('payments.totalRevenue')"
              :value="stats.totalRevenue"
              iconName="dollar-sign"
              color="green"
              format="currency"
              :trend="stats.revenueGrowth"
            />
            <StatCard
              :label="$t('payments.activeSubscriptions')"
              :value="stats.activeSubscriptions"
              iconName="users"
              color="blue"
              :trend="stats.subscriptionGrowth"
            />
            <StatCard
              :label="$t('payments.frozenAccounts')"
              :value="stats.frozenAccounts"
              iconName="alert-circle"
              color="red"
            />
            <StatCard
              label="Avg Revenue/User"
              :value="stats.avgRevenuePerUser"
              iconName="trending-up"
              color="purple"
              format="currency"
            />
          </div>

          <!-- Revenue Chart -->
          <ChartCard :title="$t('payments.revenueTrend')">
            <div class="h-full flex items-center justify-center">
              <div class="w-full">
                <div class="flex justify-between text-sm text-ink-gray-4 mb-2">
                  <span v-for="label in revenueData.labels" :key="label">{{ label }}</span>
                </div>
                <div class="relative h-32">
                  <div class="absolute inset-0 flex items-end justify-between gap-2">
                    <div
                      v-for="(value, idx) in revenueData.datasets[0].values"
                      :key="idx"
                      class="flex-1 bg-green-500 rounded-t transition-all"
                      :style="{ height: `${(value / 250000) * 100}%` }"
                    ></div>
                  </div>
                </div>
              </div>
            </div>
          </ChartCard>

          <!-- Recent Payments -->
          <div class="rounded-lg border overflow-hidden">
            <div class="p-4 border-b">
              <h3 class="text-base font-medium text-ink-gray-9">
                Recent Payments
              </h3>
            </div>
            <table class="min-w-full divide-y">
              <thead class="bg-surface-gray-2">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Customer</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Amount</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Date</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Status</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Method</th>
                </tr>
              </thead>
              <tbody class="divide-y">
                <tr v-for="payment in paymentHistory" :key="payment.id">
                  <td class="px-6 py-4 text-sm text-ink-gray-9">{{ payment.customerName }}</td>
                  <td class="px-6 py-4 text-sm font-medium text-ink-gray-9">
                    {{ formatCurrency(payment.amount) }}
                  </td>
                  <td class="px-6 py-4 text-sm text-ink-gray-7">{{ payment.date }}</td>
                  <td class="px-6 py-4">
                    <Badge
                      :variant="payment.status === 'completed' ? 'success' : 'error'"
                      :label="payment.status"
                    />
                  </td>
                  <td class="px-6 py-4 text-sm text-ink-gray-7">{{ payment.method }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Customers Tab -->
        <div v-else-if="activeTab === 'customers'">
          <div class="rounded-lg border overflow-hidden">
            <table class="min-w-full divide-y">
              <thead class="bg-surface-gray-2">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">{{ $t('payments.customer.name') }}</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">{{ $t('payments.customer.email') }}</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">{{ $t('payments.connections') }}</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">{{ $t('payments.customer.amount') }}</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">{{ $t('payments.customer.status') }}</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">{{ $t('payments.customer.lastPayment') }}</th>
                </tr>
              </thead>
              <tbody class="divide-y">
                <tr v-for="customer in customers" :key="customer.id">
                  <td class="px-6 py-4 text-sm font-medium text-ink-gray-9">{{ customer.name }}</td>
                  <td class="px-6 py-4 text-sm text-ink-gray-7">{{ customer.email }}</td>
                  <td class="px-6 py-4 text-sm text-ink-gray-7">{{ customer.connections }}</td>
                  <td class="px-6 py-4 text-sm font-medium text-ink-gray-9">
                    {{ formatCurrency(customer.monthlyAmount) }}/mo
                  </td>
                  <td class="px-6 py-4">
                    <Badge
                      :variant="customer.status === 'active' ? 'success' : 'info'"
                      :label="customer.status"
                    />
                  </td>
                  <td class="px-6 py-4 text-sm text-ink-gray-7">{{ customer.lastPayment }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Frozen Tab -->
        <div v-else-if="activeTab === 'frozen'">
          <div v-if="frozenAccounts.length" class="rounded-lg border overflow-hidden">
            <table class="min-w-full divide-y">
              <thead class="bg-surface-gray-2">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Customer</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Email</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Amount Due</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-ink-gray-5 uppercase">Reason</th>
                  <th class="px-6 py-3 text-right text-xs font-medium text-ink-gray-5 uppercase">Actions</th>
                </tr>
              </thead>
              <tbody class="divide-y">
                <tr v-for="account in frozenAccounts" :key="account.id">
                  <td class="px-6 py-4 text-sm font-medium text-ink-gray-9">{{ account.name }}</td>
                  <td class="px-6 py-4 text-sm text-ink-gray-7">{{ account.email }}</td>
                  <td class="px-6 py-4 text-sm font-medium text-red-600">
                    {{ formatCurrency(account.monthlyAmount) }}
                  </td>
                  <td class="px-6 py-4 text-sm text-ink-gray-7">{{ account.frozenReason }}</td>
                  <td class="px-6 py-4 text-right">
                    <Button variant="subtle" size="sm" @click="unfreezeAccount(account)">
                      Unfreeze
                    </Button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <EmptyState
            v-else
            icon="credit-card"
            title="No frozen accounts"
            description="All accounts are in good standing"
          />
        </div>

        <!-- Reports Tab -->
        <div v-else-if="activeTab === 'reports'" class="space-y-4">
          <div class="rounded-lg border p-5">
            <h3 class="text-base font-medium text-ink-gray-9 mb-4">
              Generate Report
            </h3>
            <div class="grid gap-4 sm:grid-cols-3">
              <FormControl
                v-model="reportParams.type"
                label="Report Type"
                type="select"
                :options="reportTypes"
              />
              <FormControl
                v-model="reportParams.startDate"
                label="Start Date"
                type="date"
              />
              <FormControl
                v-model="reportParams.endDate"
                label="End Date"
                type="date"
              />
            </div>
            <div class="mt-4">
              <Button variant="solid" @click="generateReport">
                <template #prefix>
                  <FeatherIcon name="file-text" class="h-4 w-4" />
                </template>
                Generate Report
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Button, Badge, FormControl, FeatherIcon } from 'frappe-ui'
import LayoutHeader from '@/components/Common/LayoutHeader.vue'
import StatCard from '@/components/Common/StatCard.vue'
import ChartCard from '@/components/Common/ChartCard.vue'
import EmptyState from '@/components/Common/EmptyState.vue'
import {
  paymentStats,
  revenueData,
  customers as mockCustomers,
  frozenAccounts as mockFrozenAccounts,
  paymentHistory as mockPaymentHistory,
} from '@/mocks/payments'

const activeTab = ref('overview')

const tabs = [
  { id: 'overview', label: 'payments.overview' },
  { id: 'customers', label: 'payments.customers' },
  { id: 'frozen', label: 'payments.frozen' },
  { id: 'reports', label: 'payments.reports' },
]

const stats = ref(paymentStats)
const customers = ref(mockCustomers)
const frozenAccounts = ref(mockFrozenAccounts)
const paymentHistory = ref(mockPaymentHistory)

const reportParams = ref({
  type: 'revenue',
  startDate: '',
  endDate: '',
})

const reportTypes = [
  { label: 'Revenue Report', value: 'revenue' },
  { label: 'Customer Report', value: 'customers' },
  { label: 'Payment History', value: 'payments' },
]

function formatCurrency(value) {
  return new Intl.NumberFormat('ru-RU', {
    style: 'currency',
    currency: 'RUB',
    minimumFractionDigits: 0,
  }).format(value)
}

function exportReport() {
  console.log('Exporting report...')
}

function unfreezeAccount(account) {
  console.log('Unfreezing account:', account.name)
}

function generateReport() {
  console.log('Generating report:', reportParams.value)
}
</script>
