<script>
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
import { fetchRules } from '$lib/api/rule.js';
  import { error as toastError } from '$lib/utils/toast.js';
  import DataTable from '$lib/components/DataTable.svelte';
  import { Plus, Search, Edit2, ArrowLeft, Loader2, Filter, FileText } from 'lucide-svelte';

  let loading = $state(false);
  let rules = $state([]);
  let searchName = $state('');
  let searchDebounceTimer = $state(null);

  let filterEventCode = $state('ORDER_CREATED');
  let filterActive = $state('ALL');

  const columns = [
    { key: 'RuleCode', label: 'Code', class: 'font-medium w-36' },
    { key: 'RuleName', label: 'Name', class: 'font-medium min-w-[200px]' },
    { key: 'EventCode', label: 'Event', class: 'w-32' },
    { key: 'Priority', label: 'Priority', class: 'w-20 text-center' },
    { key: 'Active', label: 'Active', class: 'w-20 text-center' },
    { key: 'actions', label: 'Actions', class: 'w-20 text-center' },
  ];

  function normalizeRulesListResponse(response) {
    if (Array.isArray(response?.data?.data)) return response.data.data;
    if (Array.isArray(response?.data)) return response.data;
    if (Array.isArray(response?.data?.rules)) return response.data.rules;
    return [];
  }

  function getParams() {
    const params = {};

    if (filterEventCode) params.EventCode = filterEventCode;
    if (filterActive !== 'ALL') params.Active = filterActive;

    const s = searchName.trim();
    if (s) params.search = s;

    return params;
  }

  async function loadRules() {
    loading = true;
    try {
      const response = await fetchRules(getParams());
      rules = normalizeRulesListResponse(response);
    } catch (err) {
      toastError(err?.message || 'Failed to load rules');
      rules = [];
    } finally {
      loading = false;
    }
  }

  function handleSearch() {
    if (searchDebounceTimer) {
      clearTimeout(searchDebounceTimer);
    }
    searchDebounceTimer = setTimeout(() => {
      loadRules();
    }, 300);
  }

  onMount(loadRules);

  function openCreatePage() {
    goto('/rules/new');
  }

  function openEditPage(row) {
    goto(`/rules/${row.RuleID}`);
  }

  function isActive(v) {
    return v === 1 || v === '1' || v === true;
  }
</script>

<div class="p-4">
  <div class="flex items-center gap-4 mb-6">
    <a href="/dashboard" 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 flex items-center gap-2">
        <FileText class="w-5 h-5 text-gray-500" />
        Rules
      </h1>
      <p class="text-sm text-gray-600">Manage global rules with DSL compilation</p>
    </div>
    <button class="btn btn-primary" onclick={openCreatePage}>
      <Plus class="w-4 h-4 mr-2" />
      New Rule
    </button>
  </div>

  <div class="bg-base-100 rounded-lg shadow border border-base-200 p-4 mb-4">
    <div class="flex items-center gap-2 mb-3 text-sm font-semibold text-gray-700">
      <Filter class="w-4 h-4" />
      Filters
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-3">
      <div>
        <div class="text-xs font-semibold text-gray-600">EventCode</div>
        <select class="select select-sm select-bordered w-full" bind:value={filterEventCode} disabled={true}>
          <option value="ORDER_CREATED">ORDER_CREATED</option>
        </select>
      </div>
      <div>
        <div class="text-xs font-semibold text-gray-600">Active</div>
        <select class="select select-sm select-bordered w-full" bind:value={filterActive} onchange={loadRules}>
          <option value="ALL">All</option>
          <option value="1">Active</option>
          <option value="0">Inactive</option>
        </select>
      </div>
      <div>
        <div class="text-xs font-semibold text-gray-600">Search Rule</div>
        <div class="flex gap-2">
          <label class="input input-sm input-bordered flex items-center gap-2 w-full focus-within:input-primary">
            <Search class="w-4 h-4 text-gray-400" />
            <input
              type="text"
              class="grow bg-transparent outline-none"
              placeholder="Search..."
              bind:value={searchName}
              oninput={handleSearch}
              onkeydown={(e) => e.key === 'Enter' && loadRules()}
            />
          </label>
          <button class="btn btn-sm btn-primary" onclick={loadRules} disabled={loading} type="button">
            {#if loading}
              <Loader2 class="w-4 h-4 animate-spin" />
            {:else}
              <Search class="w-4 h-4" />
            {/if}
          </button>
        </div>
      </div>
    </div>
  </div>

  <div class="bg-base-100 rounded-lg shadow border border-base-200">
    <DataTable
      {columns}
      data={rules}
      loading={loading}
      emptyMessage="No rules found"
      hover={true}
      bordered={false}
    >
      {#snippet cell({ column, row, value })}
        {#if column.key === 'Active'}
          <div class="flex justify-center">
            <span class="badge badge-sm {isActive(row.Active) ? 'badge-success' : 'badge-ghost'}">
              {isActive(row.Active) ? 'Yes' : 'No'}
            </span>
          </div>
        {:else if column.key === 'Priority'}
          <div class="text-center">{value ?? 0}</div>
        {:else if column.key === 'actions'}
          <div class="flex justify-center gap-2">
            <button
              class="btn btn-sm btn-ghost"
              onclick={() => openEditPage(row)}
              title="Edit rule"
              type="button"
            >
              <Edit2 class="w-4 h-4" />
            </button>
          </div>
        {:else}
          {value || '-'}
        {/if}
      {/snippet}
    </DataTable>
  </div>
</div>
