<template>
  <div class="p-6">
    <h1 class="text-[1.75rem] font-bold font-[family-name:var(--font-heading)] tracking-tight text-text-primary mb-6">Invoices</h1>

    <!-- View tabs -->
    <div class="flex gap-6 mb-6 border-b border-border-subtle">
      <button
        @click="view = 'list'"
        class="pb-2 text-[0.8125rem] transition-colors duration-150 -mb-px"
        :class="view === 'list'
          ? 'text-text-primary border-b-2 border-accent'
          : 'text-text-tertiary hover:text-text-secondary'"
      >
        List
      </button>
      <button
        @click="view = 'create'"
        class="pb-2 text-[0.8125rem] transition-colors duration-150 -mb-px"
        :class="view === 'create'
          ? 'text-text-primary border-b-2 border-accent'
          : 'text-text-tertiary hover:text-text-secondary'"
      >
        Create
      </button>
    </div>

    <!-- List View -->
    <div v-if="view === 'list'">
      <div v-if="invoicesStore.invoices.length > 0" class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-border-subtle bg-bg-surface">
              <th class="px-4 py-3 text-left text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Invoice #</th>
              <th class="px-4 py-3 text-left text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Client</th>
              <th class="px-4 py-3 text-left text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Date</th>
              <th class="px-4 py-3 text-right text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Amount</th>
              <th class="px-4 py-3 text-center text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Status</th>
              <th class="px-4 py-3 w-24"></th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="invoice in invoicesStore.invoices"
              :key="invoice.id"
              class="group border-b border-border-subtle hover:bg-bg-elevated transition-colors duration-150"
            >
              <td class="px-4 py-3 text-[0.75rem] font-medium text-text-primary">
                {{ invoice.invoice_number }}
              </td>
              <td class="px-4 py-3 text-[0.75rem] text-text-primary">
                {{ getClientName(invoice.client_id) }}
              </td>
              <td class="px-4 py-3 text-[0.75rem] text-text-secondary">
                {{ formatDate(invoice.date) }}
              </td>
              <td class="px-4 py-3 text-right text-[0.75rem] font-mono text-accent-text">
                ${{ invoice.total.toFixed(2) }}
              </td>
              <td class="px-4 py-3 text-center">
                <span
                  class="text-[0.6875rem] font-medium"
                  :class="{
                    'text-status-running': invoice.status === 'paid',
                    'text-status-warning': invoice.status === 'pending',
                    'text-status-error': invoice.status === 'overdue' || invoice.status === 'draft'
                  }"
                >
                  {{ invoice.status }}
                </span>
              </td>
              <td class="px-4 py-3">
                <div class="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity duration-100">
                  <button
                    @click="viewInvoice(invoice)"
                    class="p-1.5 text-text-tertiary hover:text-text-secondary transition-colors duration-150"
                    title="View"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                      <path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>
                  </button>
                  <button
                    @click="exportPDF(invoice)"
                    class="p-1.5 text-text-tertiary hover:text-text-secondary transition-colors duration-150"
                    title="Export PDF"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                  </button>
                  <button
                    @click="confirmDelete(invoice)"
                    class="p-1.5 text-text-tertiary hover:text-status-error transition-colors duration-150"
                    title="Delete"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div v-else class="flex flex-col items-center justify-center py-16">
        <FileText class="w-12 h-12 text-text-tertiary" :stroke-width="1.5" />
        <p class="text-sm text-text-secondary mt-4">No invoices yet</p>
        <p class="text-xs text-text-tertiary mt-2 max-w-xs text-center">Create invoices from your tracked time to bill clients.</p>
        <button
          @click="view = 'create'"
          class="mt-4 px-4 py-2 bg-accent text-bg-base text-xs font-medium rounded-lg hover:bg-accent-hover transition-colors"
        >
          Create Invoice
        </button>
      </div>
    </div>

    <!-- Create View -->
    <div v-else-if="view === 'create'" class="max-w-lg">
      <h2 class="text-[1.25rem] font-semibold font-[family-name:var(--font-heading)] text-text-primary mb-4">Create Invoice</h2>

      <form @submit.prevent="handleCreate" class="space-y-4">
        <!-- Client -->
        <div>
          <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Client *</label>
          <AppSelect
            v-model="createForm.client_id"
            :options="clientsStore.clients"
            label-key="name"
            value-key="id"
            placeholder="Select a client"
            :placeholder-value="0"
          />
        </div>

        <!-- Date -->
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Invoice Date *</label>
            <AppDatePicker
              v-model="createForm.date"
              placeholder="Invoice date"
            />
          </div>
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Due Date</label>
            <AppDatePicker
              v-model="createForm.due_date"
              placeholder="Due date"
            />
          </div>
        </div>

        <!-- Tax Rate -->
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Tax Rate (%)</label>
            <input
              v-model.number="createForm.tax_rate"
              type="number"
              min="0"
              max="100"
              step="0.01"
              class="w-full px-3 py-2 bg-bg-inset border border-border-subtle rounded-lg text-[0.8125rem] text-text-primary focus:outline-none focus:border-border-visible"
            />
          </div>
          <div>
            <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Discount ($)</label>
            <input
              v-model.number="createForm.discount"
              type="number"
              min="0"
              step="0.01"
              class="w-full px-3 py-2 bg-bg-inset border border-border-subtle rounded-lg text-[0.8125rem] text-text-primary focus:outline-none focus:border-border-visible"
            />
          </div>
        </div>

        <!-- Notes -->
        <div>
          <label class="block text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1.5">Notes</label>
          <textarea
            v-model="createForm.notes"
            rows="3"
            class="w-full px-3 py-2 bg-bg-inset border border-border-subtle rounded-lg text-[0.8125rem] text-text-primary focus:outline-none focus:border-border-visible"
            placeholder="Additional notes"
          ></textarea>
        </div>

        <!-- Calculated Total -->
        <div class="bg-bg-inset rounded-lg p-4">
          <div class="flex justify-between text-[0.75rem] text-text-secondary mb-2">
            <span>Subtotal:</span>
            <span class="font-mono">${{ calculateSubtotal().toFixed(2) }}</span>
          </div>
          <div class="flex justify-between text-[0.75rem] text-text-secondary mb-2">
            <span>Tax ({{ createForm.tax_rate }}%):</span>
            <span class="font-mono">${{ calculateTax().toFixed(2) }}</span>
          </div>
          <div class="flex justify-between text-[0.75rem] text-text-secondary mb-2">
            <span>Discount:</span>
            <span class="font-mono">-${{ createForm.discount.toFixed(2) }}</span>
          </div>
          <div class="flex justify-between text-text-primary font-medium text-[0.8125rem] pt-2 border-t border-border-subtle">
            <span>Total:</span>
            <span class="font-mono text-accent-text">${{ calculateTotal().toFixed(2) }}</span>
          </div>
        </div>

        <!-- Buttons -->
        <div class="flex justify-end gap-3 pt-4">
          <button
            type="button"
            @click="view = 'list'"
            class="px-4 py-2 border border-border-subtle text-text-secondary rounded-lg hover:bg-bg-elevated transition-colors duration-150"
          >
            Cancel
          </button>
          <button
            type="submit"
            class="px-4 py-2 bg-accent text-bg-base font-medium rounded-lg hover:bg-accent-hover transition-colors duration-150"
          >
            Create Invoice
          </button>
        </div>
      </form>
    </div>

    <!-- Invoice Detail Dialog -->
    <div
      v-if="showDetailDialog"
      class="fixed inset-0 bg-black/70 backdrop-blur-[4px] flex items-center justify-center z-50"
      @click.self="showDetailDialog = false"
    >
      <div class="bg-bg-surface border border-border-subtle rounded-lg shadow-[0_1px_3px_rgba(0,0,0,0.3)] w-full max-w-2xl mx-4 p-6 max-h-[90vh] overflow-y-auto animate-modal-enter">
        <div class="flex items-start justify-between mb-6">
          <div>
            <h2 class="text-[1.75rem] font-bold font-[family-name:var(--font-heading)] tracking-tight text-text-primary">{{ selectedInvoice?.invoice_number }}</h2>
            <p class="text-[0.75rem] text-text-secondary">{{ getClientName(selectedInvoice?.client_id || 0) }}</p>
          </div>
          <button
            @click="showDetailDialog = false"
            class="p-2 text-text-tertiary hover:text-text-secondary transition-colors duration-150"
          >
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
              <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div class="space-y-4">
          <div class="grid grid-cols-2 gap-4">
            <div>
              <p class="text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1">Invoice Date</p>
              <p class="text-[0.8125rem] text-text-primary">{{ formatDate(selectedInvoice?.date || '') }}</p>
            </div>
            <div>
              <p class="text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1">Due Date</p>
              <p class="text-[0.8125rem] text-text-primary">{{ selectedInvoice?.due_date ? formatDate(selectedInvoice.due_date) : '-' }}</p>
            </div>
          </div>

          <div class="border-t border-border-subtle pt-4">
            <div class="flex justify-between text-[0.75rem] text-text-secondary mb-2">
              <span>Subtotal:</span>
              <span class="font-mono">${{ (selectedInvoice?.subtotal || 0).toFixed(2) }}</span>
            </div>
            <div class="flex justify-between text-[0.75rem] text-text-secondary mb-2">
              <span>Tax ({{ selectedInvoice?.tax_rate || 0 }}%):</span>
              <span class="font-mono">${{ (selectedInvoice?.tax_amount || 0).toFixed(2) }}</span>
            </div>
            <div class="flex justify-between text-[0.75rem] text-text-secondary mb-2">
              <span>Discount:</span>
              <span class="font-mono">-${{ (selectedInvoice?.discount || 0).toFixed(2) }}</span>
            </div>
            <div class="flex justify-between text-text-primary font-medium text-[0.8125rem] pt-2 border-t border-border-subtle">
              <span>Total:</span>
              <span class="font-mono text-accent-text">${{ (selectedInvoice?.total || 0).toFixed(2) }}</span>
            </div>
          </div>

          <div v-if="selectedInvoice?.notes" class="border-t border-border-subtle pt-4">
            <p class="text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1">Notes</p>
            <p class="text-[0.8125rem] text-text-primary">{{ selectedInvoice.notes }}</p>
          </div>
        </div>

        <div class="flex justify-end gap-3 mt-6">
          <button
            @click="exportPDF(selectedInvoice!)"
            class="px-4 py-2 bg-accent text-bg-base font-medium rounded-lg hover:bg-accent-hover transition-colors duration-150"
          >
            Export PDF
          </button>
        </div>
      </div>
    </div>

    <!-- Delete Confirmation Dialog -->
    <div
      v-if="showDeleteDialog"
      class="fixed inset-0 bg-black/70 backdrop-blur-[4px] flex items-center justify-center z-50"
      @click.self="showDeleteDialog = false"
    >
      <div class="bg-bg-surface border border-border-subtle rounded-lg shadow-[0_1px_3px_rgba(0,0,0,0.3)] w-full max-w-sm mx-4 p-6 animate-modal-enter">
        <h2 class="text-[1.125rem] font-semibold font-[family-name:var(--font-heading)] text-text-primary mb-2">Delete Invoice</h2>
        <p class="text-[0.75rem] text-text-secondary mb-6">
          Are you sure you want to delete invoice "{{ invoiceToDelete?.invoice_number }}"? This action cannot be undone.
        </p>
        <div class="flex justify-end gap-3">
          <button
            @click="showDeleteDialog = false"
            class="px-4 py-2 border border-border-subtle text-text-secondary rounded-lg hover:bg-bg-elevated transition-colors duration-150"
          >
            Cancel
          </button>
          <button
            @click="handleDelete"
            class="px-4 py-2 border border-status-error text-status-error font-medium rounded-lg hover:bg-status-error/10 transition-colors duration-150"
          >
            Delete
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { FileText } from 'lucide-vue-next'
import AppSelect from '../components/AppSelect.vue'
import AppDatePicker from '../components/AppDatePicker.vue'
import { useInvoicesStore, type Invoice } from '../stores/invoices'
import { useClientsStore } from '../stores/clients'
import { useToastStore } from '../stores/toast'
import { generateInvoicePdf } from '../utils/invoicePdf'

const invoicesStore = useInvoicesStore()
const clientsStore = useClientsStore()
const toastStore = useToastStore()

// View state
const view = ref<'list' | 'create'>('list')

// Dialog state
const showDetailDialog = ref(false)
const showDeleteDialog = ref(false)
const selectedInvoice = ref<Invoice | null>(null)
const invoiceToDelete = ref<Invoice | null>(null)

// Create form
const createForm = reactive({
  client_id: 0,
  date: new Date().toISOString().split('T')[0],
  due_date: '',
  tax_rate: 0,
  discount: 0,
  notes: ''
})

// Get client name by ID
function getClientName(clientId: number): string {
  const client = clientsStore.clients.find(c => c.id === clientId)
  return client?.name || 'Unknown Client'
}

// Format date
function formatDate(dateString: string): string {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric'
  })
}

// Calculate subtotal (simplified - would need line items in a real app)
function calculateSubtotal(): number {
  return 0
}

// Calculate tax
function calculateTax(): number {
  return calculateSubtotal() * (createForm.tax_rate / 100)
}

// Calculate total
function calculateTotal(): number {
  return calculateSubtotal() + calculateTax() - createForm.discount
}

// View invoice details
function viewInvoice(invoice: Invoice) {
  selectedInvoice.value = invoice
  showDetailDialog.value = true
}

// Confirm delete
function confirmDelete(invoice: Invoice) {
  invoiceToDelete.value = invoice
  showDeleteDialog.value = true
}

// Handle delete
async function handleDelete() {
  if (invoiceToDelete.value?.id) {
    await invoicesStore.deleteInvoice(invoiceToDelete.value.id)
  }
  showDeleteDialog.value = false
  invoiceToDelete.value = null
}

// Handle create
async function handleCreate() {
  if (!createForm.client_id) {
    toastStore.info('Please select a client')
    return
  }

  const subtotal = calculateSubtotal()
  const taxAmount = subtotal * (createForm.tax_rate / 100)
  const total = subtotal + taxAmount - createForm.discount

  const invoice: Invoice = {
    client_id: createForm.client_id,
    invoice_number: `INV-${Date.now()}`,
    date: createForm.date,
    due_date: createForm.due_date || undefined,
    subtotal,
    tax_rate: createForm.tax_rate,
    tax_amount: taxAmount,
    discount: createForm.discount,
    total,
    notes: createForm.notes || undefined,
    status: 'pending'
  }

  await invoicesStore.createInvoice(invoice)
  view.value = 'list'
}

// Export PDF using client-side jsPDF
function exportPDF(invoice: Invoice) {
  const client = clientsStore.clients.find(c => c.id === invoice.client_id)
  if (!client) {
    console.error('Client not found for invoice')
    return
  }

  const doc = generateInvoicePdf(invoice, client, [])
  doc.save(`${invoice.invoice_number}.pdf`)
}

// Load data on mount
onMounted(async () => {
  await Promise.all([
    invoicesStore.fetchInvoices(),
    clientsStore.fetchClients()
  ])
})
</script>
