<script>
  import { onMount } from 'svelte';
  import { fetchCounters, createCounter, updateCounter, deleteCounter } from '$lib/api/counters.js';
  import { success as toastSuccess, error as toastError } from '$lib/utils/toast.js';
  import DataTable from '$lib/components/DataTable.svelte';
  import Modal from '$lib/components/Modal.svelte';
  import HelpTooltip from '$lib/components/HelpTooltip.svelte';
  import { 
    Plus, 
    Edit2, 
    Trash2, 
    ArrowLeft, 
    Search, 
    Hash, 
    AlertCircle,
    Loader2,
    Info
  } from 'lucide-svelte';

  let loading = $state(false);
  let counters = $state([]);
  let searchQuery = $state('');
  let modalOpen = $state(false);
  let modalMode = $state('create');
  let saving = $state(false);
  let deleting = $state(false);
  let formErrors = $state({});
  let formData = $state({ 
    CounterID: null, 
    CounterDesc: '', 
    CounterValue: 0, 
    CounterStart: 0, 
    CounterEnd: null, 
    CounterReset: '' 
  });
  let deleteConfirmOpen = $state(false);
  let deleteItem = $state(null);

  const resetOptions = [
    { value: '', label: 'None (Manual)' },
    { value: 'D', label: 'Daily' },
    { value: 'M', label: 'Monthly' },
    { value: 'Y', label: 'Yearly' },
  ];

  const resetLabels = {
    'D': 'Daily',
    'M': 'Monthly', 
    'Y': 'Yearly',
    '': 'Manual',
  };

  const resetBadges = {
    'D': { label: 'D', class: 'badge-primary', description: 'Daily Reset' },
    'M': { label: 'M', class: 'badge-secondary', description: 'Monthly Reset' },
    'Y': { label: 'Y', class: 'badge-accent', description: 'Yearly Reset' },
    '': { label: '-', class: 'badge-ghost', description: 'Manual Reset' },
  };

  const columns = [
    { key: 'CounterDesc', label: 'Description', class: 'font-medium' },
    { key: 'CounterValue', label: 'Current Value', class: 'text-center' },
    { key: 'CounterStart', label: 'Start Value', class: 'text-center' },
    { key: 'CounterEnd', label: 'End Value', class: 'text-center' },
    { key: 'CounterResetBadge', label: 'Reset Pattern', class: 'text-center' },
    { key: 'actions', label: 'Actions', class: 'w-32 text-center' },
  ];

  // Filter counters based on search query
  let filteredCounters = $derived(
    searchQuery.trim() === '' 
      ? counters 
      : counters.filter(c => 
          (c.CounterDesc || '').toLowerCase().includes(searchQuery.toLowerCase().trim())
        )
  );

  onMount(async () => {
    await loadCounters();
  });

  async function loadCounters() {
    loading = true;
    try {
      const response = await fetchCounters();
      counters = Array.isArray(response.data) ? response.data : [];
    } catch (err) {
      toastError(err.message || 'Failed to load counters');
      counters = [];
    } finally {
      loading = false;
    }
  }

  function openCreateModal() {
    modalMode = 'create';
    formData = { 
      CounterID: null, 
      CounterDesc: '', 
      CounterValue: 0, 
      CounterStart: 0, 
      CounterEnd: null, 
      CounterReset: '' 
    };
    formErrors = {};
    modalOpen = true;
  }

  function openEditModal(row) {
    modalMode = 'edit';
    formData = {
      CounterID: row.CounterID,
      CounterDesc: row.CounterDesc || '',
      CounterValue: row.CounterValue || 0,
      CounterStart: row.CounterStart || 0,
      CounterEnd: row.CounterEnd || null,
      CounterReset: row.CounterReset || '',
    };
    formErrors = {};
    modalOpen = true;
  }

  function validateForm() {
    const errors = {};
    
    // Start value must be less than or equal to end value
    if (formData.CounterEnd !== null && formData.CounterEnd !== '' && formData.CounterEnd !== undefined) {
      if (formData.CounterStart > formData.CounterEnd) {
        errors.CounterStart = 'Start value cannot be greater than end value';
        errors.CounterEnd = 'End value must be greater than or equal to start value';
      }
    }
    
    // Current value must be between start and end (if end is set)
    if (formData.CounterEnd !== null && formData.CounterEnd !== '' && formData.CounterEnd !== undefined) {
      if (formData.CounterValue < formData.CounterStart) {
        errors.CounterValue = `Current value must be at least ${formData.CounterStart}`;
      }
      if (formData.CounterValue > formData.CounterEnd) {
        errors.CounterValue = `Current value cannot exceed ${formData.CounterEnd}`;
      }
    } else {
      // If no end value, current must still be >= start
      if (formData.CounterValue < formData.CounterStart) {
        errors.CounterValue = `Current value must be at least ${formData.CounterStart}`;
      }
    }
    
    formErrors = errors;
    return Object.keys(errors).length === 0;
  }

  async function handleSave() {
    if (!validateForm()) {
      return;
    }
    
    saving = true;
    try {
      if (modalMode === 'create') {
        await createCounter(formData);
        toastSuccess('Counter created successfully');
      } else {
        await updateCounter(formData.CounterID, formData);
        toastSuccess('Counter updated successfully');
      }
      modalOpen = false;
      await loadCounters();
    } catch (err) {
      toastError(err.message || 'Failed to save counter');
    } finally {
      saving = false;
    }
  }

  function confirmDelete(row) {
    deleteItem = row;
    deleteConfirmOpen = true;
  }

  async function handleDelete() {
    deleting = true;
    try {
      await deleteCounter(deleteItem.CounterID);
      toastSuccess('Counter deleted successfully');
      deleteConfirmOpen = false;
      await loadCounters();
    } catch (err) {
      toastError(err.message || 'Failed to delete counter');
    } finally {
      deleting = false;
    }
  }

  function getResetBadge(resetValue) {
    return resetBadges[resetValue] || resetBadges[''];
  }
</script>

<div class="p-4">
  <!-- Header -->
  <div class="flex items-center gap-4 mb-6">
    <a href="/master-data" class="btn btn-ghost btn-circle">
      <ArrowLeft class="w-5 h-5" />
    </a>
    <div class="flex-1">
      <h1 class="text-xl font-bold text-gray-800">Counters</h1>
      <p class="text-sm text-gray-600">Manage ID generation counters</p>
    </div>
    <button class="btn btn-primary" onclick={openCreateModal}>
      <Plus class="w-4 h-4 mr-2" />
      Add Counter
    </button>
  </div>

  <!-- Info Card -->
  <div class="alert alert-info mb-6">
    <Info class="w-5 h-5 shrink-0" />
    <div>
      <h3 class="font-bold">What are Counters?</h3>
      <p class="text-sm">
        Counters are used to automatically generate unique laboratory IDs (e.g., sample IDs, order IDs).
        They keep track of the next available number and can automatically reset based on a pattern.
      </p>
    </div>
  </div>

  <!-- Search Bar -->
  <div class="flex items-center gap-4 mb-4">
    <div class="form-control flex-1 max-w-md">
      <label class="input input-sm input-bordered w-full flex items-center gap-2">
        <Search class="w-4 h-4 text-base-content/50" />
        <input
          type="text"
          class="grow"
          placeholder="Search by counter description..."
          bind:value={searchQuery}
        />
        {#if searchQuery}
          <button 
            class="btn btn-ghost btn-xs btn-circle"
            onclick={() => searchQuery = ''}
            aria-label="Clear search"
          >
            ×
          </button>
        {/if}
      </label>
    </div>
    {#if searchQuery}
      <span class="text-sm text-base-content/70">
        {filteredCounters.length} result{filteredCounters.length === 1 ? '' : 's'}
      </span>
    {/if}
  </div>

  <!-- Data Table -->
  <div class="bg-base-100 rounded-lg shadow border border-base-200">
    {#if filteredCounters.length === 0 && !loading}
      <!-- Empty State -->
      <div class="flex flex-col items-center justify-center py-16 px-4">
        <div class="bg-base-200 rounded-full p-4 mb-4">
          <Hash class="w-8 h-8 text-base-content/40" />
        </div>
        <h3 class="text-base font-semibold text-base-content/70 mb-1">
          {#if searchQuery}
            No counters found
          {:else}
            No counters yet
          {/if}
        </h3>
        <p class="text-sm text-base-content/50 text-center max-w-sm mb-4">
          {#if searchQuery}
            No counters match your search "{searchQuery}". Try a different search term.
          {:else}
            Create your first counter to start generating unique laboratory IDs.
          {/if}
        </p>
        {#if !searchQuery}
          <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
            <Plus class="w-4 h-4 mr-2" />
            Create Counter
          </button>
        {:else}
          <button class="btn btn-ghost btn-sm" onclick={() => searchQuery = ''}>
            Clear Search
          </button>
        {/if}
      </div>
    {:else}
      <DataTable
        {columns}
        data={filteredCounters.map((c) => ({
          ...c,
          CounterResetLabel: resetLabels[c.CounterReset] || c.CounterReset || 'Manual',
          CounterResetBadge: c.CounterReset,
          CounterEnd: c.CounterEnd || '-',
        }))}
        {loading}
        emptyMessage="No counters found"
        hover={true}
        bordered={false}
      >
        {#snippet cell({ column, row, value })}
          {#if column.key === 'actions'}
            <div class="flex justify-center gap-2">
              <button class="btn btn-sm btn-ghost" onclick={() => openEditModal(row)} title="Edit">
                <Edit2 class="w-4 h-4" />
              </button>
              <button class="btn btn-sm btn-ghost text-error" onclick={() => confirmDelete(row)} title="Delete">
                <Trash2 class="w-4 h-4" />
              </button>
            </div>
          {:else if column.key === 'CounterResetBadge'}
            {@const badge = getResetBadge(row.CounterReset)}
            <div class="tooltip" data-tip={badge.description}>
              <span class="badge {badge.class} badge-sm">{badge.label}</span>
            </div>
          {:else}
            {value}
          {/if}
        {/snippet}
      </DataTable>
    {/if}
  </div>
</div>

<!-- Create/Edit Modal -->
<Modal bind:open={modalOpen} title={modalMode === 'create' ? 'Add Counter' : 'Edit Counter'} size="md">
  <form class="space-y-3" onsubmit={(e) => { e.preventDefault(); handleSave(); }}>
    <!-- Description -->
    <div class="form-control">
      <label class="label" for="counterDesc">
        <span class="label-text text-sm font-medium">Counter Description</span>
        <span class="label-text-alt text-xs text-error">*</span>
      </label>
      <input
        id="counterDesc"
        type="text"
        class="input input-sm input-bordered w-full"
        class:input-error={formErrors.CounterDesc}
        bind:value={formData.CounterDesc}
        placeholder="e.g., Sample ID Counter, Order Number"
        required
      />
      <label class="label" for="counterDesc">
        <span class="label-text-alt text-xs text-base-content/60">
          A descriptive name for this counter
        </span>
      </label>
    </div>

    <!-- Value Fields -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
      <!-- Current Value -->
      <div class="form-control">
        <label class="label" for="counterValue">
          <span class="label-text text-sm font-medium">Current Value</span>
          <span class="label-text-alt text-xs text-error">*</span>
          <HelpTooltip 
            text="The next number that will be assigned. This increments automatically each time an ID is generated." 
            title="Current Value"
            position="top"
            class="ml-1"
          />
        </label>
        <input
          id="counterValue"
          type="number"
          class="input input-sm input-bordered w-full"
          class:input-error={formErrors.CounterValue}
          bind:value={formData.CounterValue}
          placeholder="e.g., 1000"
          min="0"
          required
        />
        {#if formErrors.CounterValue}
          <label class="label" for="counterValue">
            <span class="label-text-alt text-xs text-error">{formErrors.CounterValue}</span>
          </label>
        {/if}
      </div>

      <!-- Start Value -->
      <div class="form-control">
        <label class="label" for="counterStart">
          <span class="label-text text-sm font-medium">Start Value</span>
          <span class="label-text-alt text-xs text-error">*</span>
          <HelpTooltip 
            text="The minimum value this counter can have. When reset, the counter returns to this value." 
            title="Start Value"
            position="top"
            class="ml-1"
          />
        </label>
        <input
          id="counterStart"
          type="number"
          class="input input-sm input-bordered w-full"
          class:input-error={formErrors.CounterStart}
          bind:value={formData.CounterStart}
          placeholder="e.g., 1"
          min="0"
          required
        />
        {#if formErrors.CounterStart}
          <label class="label" for="counterStart">
            <span class="label-text-alt text-xs text-error">{formErrors.CounterStart}</span>
          </label>
        {/if}
      </div>

      <!-- End Value -->
      <div class="form-control">
        <label class="label" for="counterEnd">
          <span class="label-text text-sm font-medium">End Value</span>
          <HelpTooltip 
            text="Optional maximum value. When reached, the counter will reset to the start value. Leave empty for no limit." 
            title="End Value"
            position="top"
            class="ml-1"
          />
        </label>
        <input
          id="counterEnd"
          type="number"
          class="input input-sm input-bordered w-full"
          class:input-error={formErrors.CounterEnd}
          bind:value={formData.CounterEnd}
          placeholder="e.g., 9999"
          min="0"
        />
        {#if formErrors.CounterEnd}
          <label class="label" for="counterEnd">
            <span class="label-text-alt text-xs text-error">{formErrors.CounterEnd}</span>
          </label>
        {/if}
      </div>
    </div>

    <!-- Reset Pattern -->
    <div class="form-control">
      <label class="label" for="counterReset">
        <span class="label-text text-sm font-medium">Reset Pattern</span>
        <HelpTooltip 
          text="Determines when the counter automatically resets to the start value. Daily resets at midnight, monthly on the 1st, yearly on Jan 1st." 
          title="Reset Pattern"
          position="top"
          class="ml-1"
        />
      </label>
      <select
        id="counterReset"
        name="counterReset"
        class="select select-sm select-bordered w-full"
        bind:value={formData.CounterReset}
      >
        {#each resetOptions as option (option.value)}
          <option value={option.value}>{option.label}</option>
        {/each}
      </select>
      <label class="label" for="counterReset">
        <span class="label-text-alt text-xs text-base-content/60">
          Choose when the counter automatically resets to the start value
        </span>
      </label>
    </div>
  </form>
  {#snippet footer()}
    <button class="btn btn-ghost" onclick={() => (modalOpen = false)} type="button">Cancel</button>
    <button class="btn btn-primary" onclick={handleSave} disabled={saving} type="button">
      {#if saving}
        <Loader2 class="w-4 h-4 mr-2 animate-spin" />
      {/if}
      {saving ? 'Saving...' : 'Save'}
    </button>
  {/snippet}
</Modal>

<!-- Delete Confirmation Modal -->
<Modal bind:open={deleteConfirmOpen} title="Confirm Delete" size="sm">
  <div class="py-2">
    <div class="alert alert-warning mb-4">
      <AlertCircle class="w-5 h-5 shrink-0" />
      <span>This action cannot be undone.</span>
    </div>
    <p class="text-base-content/80 mb-2">
      Are you sure you want to delete this counter?
    </p>
    <div class="bg-base-200 rounded-lg p-3 mt-3">
      <p class="font-semibold text-base-content">{deleteItem?.CounterDesc}</p>
      <p class="text-sm text-base-content/60 mt-1">
        Current Value: {deleteItem?.CounterValue} | 
        Pattern: {resetLabels[deleteItem?.CounterReset] || 'Manual'}
      </p>
    </div>
    <p class="text-sm text-error mt-4">
      <strong>Warning:</strong> Deleting this counter may cause issues with ID generation if it's currently in use.
    </p>
  </div>
  {#snippet footer()}
    <button class="btn btn-ghost" onclick={() => (deleteConfirmOpen = false)} disabled={deleting} type="button">
      Cancel
    </button>
    <button class="btn btn-error" onclick={handleDelete} disabled={deleting} type="button">
      {#if deleting}
        <Loader2 class="w-4 h-4 mr-2 animate-spin" />
      {:else}
        <Trash2 class="w-4 h-4 mr-2" />
      {/if}
      {deleting ? 'Deleting...' : 'Delete Counter'}
    </button>
  {/snippet}
</Modal>
