<template>
  <AppLayout>
    <div class="billing">
      <header class="page-header">
        <h1>Billing & Plans</h1>
        <p class="subtitle">Manage your subscription and view usage</p>
      </header>

      <div v-if="loading" class="loading">Loading...</div>

      <template v-else>
        <!-- Current Plan Card -->
        <section class="card current-plan">
          <div class="plan-header">
            <div>
              <h2>Current Plan</h2>
              <div class="plan-badge" :class="currentPlan.toLowerCase()">
                {{ currentPlan }}
              </div>
            </div>
            <button
              v-if="subscription?.subscriptionId"
              class="btn btn-secondary"
              @click="openPortal"
              :disabled="portalLoading"
            >
              {{ portalLoading ? 'Loading...' : 'Manage Subscription' }}
            </button>
          </div>

          <div v-if="subscription?.cancelAtPeriodEnd" class="cancel-notice">
            Your subscription will be canceled on {{ formatDate(subscription.currentPeriodEnd) }}.
            You'll be downgraded to the Free plan after this date.
          </div>

          <div class="usage-section" v-if="usage">
            <h3>Usage This Month</h3>
            <div class="usage-grid">
              <div class="usage-item">
                <div class="usage-bar">
                  <div
                    class="usage-fill"
                    :style="{ width: getUsagePercent(usage.workspaces, usage.limits.maxWorkspaces) + '%' }"
                    :class="{ warning: getUsagePercent(usage.workspaces, usage.limits.maxWorkspaces) > 80 }"
                  ></div>
                </div>
                <div class="usage-label">
                  <span>Workspaces</span>
                  <span>{{ usage.workspaces }} / {{ formatLimit(usage.limits.maxWorkspaces) }}</span>
                </div>
              </div>

              <div class="usage-item">
                <div class="usage-bar">
                  <div
                    class="usage-fill"
                    :style="{ width: getUsagePercent(usage.links, usage.limits.maxLinks) + '%' }"
                    :class="{ warning: getUsagePercent(usage.links, usage.limits.maxLinks) > 80 }"
                  ></div>
                </div>
                <div class="usage-label">
                  <span>Links</span>
                  <span>{{ usage.links }} / {{ formatLimit(usage.limits.maxLinks) }}</span>
                </div>
              </div>

              <div class="usage-item">
                <div class="usage-bar">
                  <div
                    class="usage-fill"
                    :style="{ width: getUsagePercent(usage.qrCodes, usage.limits.maxQRCodes) + '%' }"
                    :class="{ warning: getUsagePercent(usage.qrCodes, usage.limits.maxQRCodes) > 80 }"
                  ></div>
                </div>
                <div class="usage-label">
                  <span>QR Codes</span>
                  <span>{{ usage.qrCodes }} / {{ formatLimit(usage.limits.maxQRCodes) }}</span>
                </div>
              </div>

              <div class="usage-item">
                <div class="usage-bar">
                  <div
                    class="usage-fill"
                    :style="{ width: getUsagePercent(usage.eventsThisMonth, usage.limits.maxEventsPerMonth) + '%' }"
                    :class="{ warning: getUsagePercent(usage.eventsThisMonth, usage.limits.maxEventsPerMonth) > 80 }"
                  ></div>
                </div>
                <div class="usage-label">
                  <span>Events</span>
                  <span>{{ formatNumber(usage.eventsThisMonth) }} / {{ formatLimit(usage.limits.maxEventsPerMonth) }}</span>
                </div>
              </div>
            </div>
          </div>
        </section>

        <!-- Plan Comparison -->
        <section class="plans-section">
          <h2>Available Plans</h2>
          <div class="plans-grid">
            <div class="plan-card" :class="{ current: currentPlan === 'Free' }">
              <div class="plan-name">Free</div>
              <div class="plan-price">
                <span class="amount">$0</span>
                <span class="period">/month</span>
              </div>
              <ul class="plan-features">
                <li>1 workspace</li>
                <li>50 links</li>
                <li>25 QR codes</li>
                <li>10,000 events/month</li>
                <li>Basic analytics</li>
              </ul>
              <button
                v-if="currentPlan === 'Free'"
                class="btn btn-secondary"
                disabled
              >
                Current Plan
              </button>
            </div>

            <div class="plan-card featured" :class="{ current: currentPlan === 'Pro' }">
              <div class="popular-badge">Most Popular</div>
              <div class="plan-name">Pro</div>
              <div class="plan-price">
                <span class="amount">$29</span>
                <span class="period">/month</span>
              </div>
              <ul class="plan-features">
                <li>5 workspaces</li>
                <li>5,000 links</li>
                <li>1,000 QR codes</li>
                <li>100,000 events/month</li>
                <li>3 custom domains</li>
                <li>Password protection</li>
                <li>Advanced analytics</li>
              </ul>
              <button
                v-if="currentPlan === 'Pro'"
                class="btn btn-secondary"
                disabled
              >
                Current Plan
              </button>
              <button
                v-else-if="currentPlan === 'Free'"
                class="btn btn-primary"
                @click="upgrade('Pro')"
                :disabled="upgrading"
              >
                {{ upgrading ? 'Loading...' : 'Upgrade to Pro' }}
              </button>
              <button
                v-else
                class="btn btn-secondary"
                @click="openPortal"
              >
                Downgrade
              </button>
            </div>

            <div class="plan-card" :class="{ current: currentPlan === 'Business' }">
              <div class="plan-name">Business</div>
              <div class="plan-price">
                <span class="amount">$99</span>
                <span class="period">/month</span>
              </div>
              <ul class="plan-features">
                <li>Unlimited workspaces</li>
                <li>Unlimited links</li>
                <li>Unlimited QR codes</li>
                <li>Unlimited events</li>
                <li>Unlimited custom domains</li>
                <li>Password protection</li>
                <li>Priority support</li>
                <li>API access</li>
              </ul>
              <button
                v-if="currentPlan === 'Business'"
                class="btn btn-secondary"
                disabled
              >
                Current Plan
              </button>
              <button
                v-else
                class="btn btn-primary"
                @click="upgrade('Business')"
                :disabled="upgrading"
              >
                {{ upgrading ? 'Loading...' : 'Upgrade to Business' }}
              </button>
            </div>
          </div>
        </section>
      </template>

      <div v-if="error" class="error-message">{{ error }}</div>
    </div>
  </AppLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { billingApi } from '../../api/billing.js';
import { usageApi } from '../../api/usage.js';
import { useWorkspaceStore } from '../../stores/workspace.js';
import AppLayout from '../../components/layout/AppLayout.vue';

const route = useRoute();
const workspaceStore = useWorkspaceStore();

const loading = ref(true);
const upgrading = ref(false);
const portalLoading = ref(false);
const error = ref('');
const usage = ref(null);
const subscription = ref(null);

const currentPlan = computed(() => usage.value?.plan || 'Free');

onMounted(async () => {
  // Check for success from checkout
  if (route.query.session_id) {
    // Payment was successful, refresh data
    setTimeout(() => loadData(), 1000);
  } else {
    loadData();
  }
});

async function loadData() {
  loading.value = true;
  error.value = '';

  try {
    const workspaceId = workspaceStore.currentWorkspace?.id;

    const [usageData, subData] = await Promise.all([
      usageApi.get(workspaceId),
      workspaceId ? billingApi.getSubscription(workspaceId) : Promise.resolve(null),
    ]);

    usage.value = usageData;
    subscription.value = subData;
  } catch (err) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
}

async function upgrade(plan) {
  upgrading.value = true;
  error.value = '';

  try {
    const workspaceId = workspaceStore.currentWorkspace?.id;
    if (!workspaceId) {
      throw new Error('No workspace selected');
    }

    const successUrl = window.location.origin + '/billing';
    const cancelUrl = window.location.origin + '/billing';

    const { url } = await billingApi.createCheckoutSession(
      workspaceId,
      plan,
      successUrl,
      cancelUrl
    );

    window.location.href = url;
  } catch (err) {
    error.value = err.message;
    upgrading.value = false;
  }
}

async function openPortal() {
  portalLoading.value = true;
  error.value = '';

  try {
    const returnUrl = window.location.origin + '/billing';
    const { url } = await billingApi.createPortalSession(returnUrl);
    window.location.href = url;
  } catch (err) {
    error.value = err.message;
    portalLoading.value = false;
  }
}

function getUsagePercent(used, limit) {
  if (limit === 2147483647 || limit === -1) return 0; // Unlimited
  return Math.min(100, (used / limit) * 100);
}

function formatLimit(limit) {
  if (limit === 2147483647 || limit === -1) return 'Unlimited';
  return formatNumber(limit);
}

function formatNumber(num) {
  if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
  if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
  return num.toString();
}

function formatDate(dateStr) {
  if (!dateStr) return '';
  return new Date(dateStr).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
}
</script>

<style scoped>
.billing {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.page-header {
  margin-bottom: 2rem;
}

.page-header h1 {
  font-size: 1.75rem;
  font-weight: 600;
  margin: 0 0 0.5rem;
}

.subtitle {
  color: #6b7280;
  margin: 0;
}

.loading {
  text-align: center;
  padding: 3rem;
  color: #6b7280;
}

.card {
  background: white;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.current-plan .plan-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1.5rem;
}

.current-plan h2 {
  font-size: 1.125rem;
  font-weight: 600;
  margin: 0 0 0.5rem;
}

.plan-badge {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.875rem;
  font-weight: 500;
}

.plan-badge.free {
  background: #e5e7eb;
  color: #374151;
}

.plan-badge.pro {
  background: #dbeafe;
  color: #1d4ed8;
}

.plan-badge.business {
  background: #fef3c7;
  color: #b45309;
}

.cancel-notice {
  background: #fef3c7;
  border: 1px solid #fcd34d;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1.5rem;
  color: #92400e;
}

.usage-section h3 {
  font-size: 1rem;
  font-weight: 600;
  margin: 0 0 1rem;
  color: #374151;
}

.usage-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.usage-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.usage-bar {
  height: 8px;
  background: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}

.usage-fill {
  height: 100%;
  background: #3b82f6;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.usage-fill.warning {
  background: #f59e0b;
}

.usage-label {
  display: flex;
  justify-content: space-between;
  font-size: 0.875rem;
  color: #6b7280;
}

.plans-section {
  margin-top: 2rem;
}

.plans-section h2 {
  font-size: 1.25rem;
  font-weight: 600;
  margin: 0 0 1.5rem;
}

.plans-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
}

.plan-card {
  background: white;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  padding: 1.5rem;
  position: relative;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.plan-card:hover {
  border-color: #d1d5db;
}

.plan-card.featured {
  border-color: #3b82f6;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.15);
}

.plan-card.current {
  background: #f9fafb;
}

.popular-badge {
  position: absolute;
  top: -12px;
  left: 50%;
  transform: translateX(-50%);
  background: #3b82f6;
  color: white;
  font-size: 0.75rem;
  font-weight: 600;
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
}

.plan-name {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.plan-price {
  margin-bottom: 1.5rem;
}

.plan-price .amount {
  font-size: 2rem;
  font-weight: 700;
}

.plan-price .period {
  color: #6b7280;
}

.plan-features {
  list-style: none;
  padding: 0;
  margin: 0 0 1.5rem;
}

.plan-features li {
  padding: 0.5rem 0;
  padding-left: 1.5rem;
  position: relative;
  color: #374151;
}

.plan-features li::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 16px;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='%2310b981'%3E%3Cpath fill-rule='evenodd' d='M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z' clip-rule='evenodd'/%3E%3C/svg%3E") no-repeat center;
}

.btn {
  width: 100%;
  padding: 0.75rem 1rem;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-primary {
  background: #3b82f6;
  color: white;
  border: none;
}

.btn-primary:hover:not(:disabled) {
  background: #2563eb;
}

.btn-secondary {
  background: white;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover:not(:disabled) {
  background: #f9fafb;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.error-message {
  background: #fee2e2;
  border: 1px solid #fecaca;
  border-radius: 8px;
  padding: 1rem;
  color: #dc2626;
  margin-top: 1rem;
}

@media (max-width: 768px) {
  .billing {
    padding: 1rem;
  }

  .current-plan .plan-header {
    flex-direction: column;
    gap: 1rem;
  }

  .plans-grid {
    grid-template-columns: 1fr;
  }
}
</style>
