<script>
  import { onMount } from 'svelte';
  import { fetchValueSets, fetchValueSetByKey, refreshValueSets } from '$lib/api/valuesets.js';
  import { success as toastSuccess, error as toastError } from '$lib/utils/toast.js';
  import DataTable from '$lib/components/DataTable.svelte';
  import HelpTooltip from '$lib/components/HelpTooltip.svelte';
  import { Search, RefreshCw, ArrowLeft, Copy, ListX, Hash } from 'lucide-svelte';

  let loading = $state(false);
  let refreshing = $state(false);
  let valueSets = $state([]);
  let searchQuery = $state('');
  let selectedValueSet = $state(null);
  let detailLoading = $state(false);
  let copiedKey = $state('');

  const columns = [
    { key: 'ValueSetKey', label: 'Key', class: 'font-medium' },
    { key: 'Name', label: 'Name' },
    { key: 'ItemCount', label: 'Items', class: 'w-24 text-center' },
  ];

  const itemColumns = [
    { key: 'value', label: 'Value', class: 'font-medium w-32' },
    { key: 'label', label: 'Label' },
  ];

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

  async function loadValueSets() {
    loading = true;
    try {
      const params = searchQuery ? { key: searchQuery } : {};
      const response = await fetchValueSets(params);

      let dataArray = [];

      if (response.status === 'success' && response.data) {
        if (Array.isArray(response.data)) {
          // New API format: { value, label, count }
          dataArray = response.data.map((item) => ({
            ValueSetKey: item.value,
            Name: item.label,
            ItemCount: item.count,
          }));
        } else if (typeof response.data === 'object') {
          // Fallback for old format: { key: count }
          dataArray = Object.entries(response.data).map(([key, count]) => ({
            ValueSetKey: key,
            Name: key.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase()),
            ItemCount: count,
          }));
        }
      }

      valueSets = dataArray;
    } catch (err) {
      console.error('Load error:', err);
      toastError(err.message || 'Failed to load ValueSets');
      valueSets = [];
    } finally {
      loading = false;
    }
  }

  async function handleRefresh() {
    refreshing = true;
    try {
      await refreshValueSets();
      toastSuccess('ValueSets cache refreshed successfully');
      await loadValueSets();
    } catch (err) {
      toastError(err.message || 'Failed to refresh ValueSets');
    } finally {
      refreshing = false;
    }
  }

  async function handleRowClick(row) {
    detailLoading = true;
    
    try {
      const response = await fetchValueSetByKey(row.ValueSetKey);
      if (response.status === 'success' && response.data) {
        // Transform API response (array of items) to include metadata
        selectedValueSet = {
          ValueSetKey: row.ValueSetKey,
          Name: row.Name,
          Items: Array.isArray(response.data) ? response.data : []
        };
      } else {
        throw new Error('Failed to load ValueSet details');
      }
    } catch (err) {
      toastError(err.message || 'Failed to load ValueSet details');
      selectedValueSet = null;
    } finally {
      detailLoading = false;
    }
  }

  function handleSearch() {
    loadValueSets();
  }

  function handleSearchKeydown(event) {
    if (event.key === 'Enter') {
      loadValueSets();
    }
  }

  async function copyToClipboard(text) {
    try {
      await navigator.clipboard.writeText(text);
      copiedKey = text;
      toastSuccess('ValueSet key copied to clipboard');
      setTimeout(() => {
        copiedKey = '';
      }, 2000);
    } catch (err) {
      toastError('Failed to copy to clipboard');
    }
  }
</script>

<div class="p-6 h-[calc(100vh-4rem)] flex flex-col">
  <!-- 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">
      <div class="flex items-center gap-3">
        <h1 class="text-xl font-bold text-gray-800">ValueSets</h1>
        <HelpTooltip
          text="ValueSets are reusable lookup tables used throughout the system for dropdown menus, form fields, and standardized values. They ensure consistency in data entry and reporting."
          title="About ValueSets"
          position="right"
        />
      </div>
      <p class="text-sm text-gray-600">System lookup values and dropdown options</p>
    </div>
  </div>

  <!-- Two Column Layout -->
  <div class="flex-1 grid grid-cols-1 lg:grid-cols-2 gap-6 min-h-0">
    <!-- Left Column: ValueSet List -->
    <div class="flex flex-col min-h-0">
      <!-- Actions -->
      <div class="flex flex-col sm:flex-row gap-4 mb-4">
        <label class="input input-sm input-bordered flex-1 flex items-center gap-2">
          <Search class="w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="Search ValueSets by key (e.g., priority_status, test_category)..."
            class="grow"
            bind:value={searchQuery}
            onkeydown={handleSearchKeydown}
          />
        </label>
        
        <button 
          class="btn btn-primary"
          onclick={handleSearch}
          disabled={loading}
        >
          {#if loading}
            <span class="loading loading-spinner loading-sm"></span>
          {:else}
            <Search class="w-4 h-4" />
          {/if}
          Search
        </button>
        
        <button 
          class="btn btn-outline"
          onclick={handleRefresh}
          disabled={refreshing}
        >
          {#if refreshing}
            <span class="loading loading-spinner loading-sm"></span>
          {:else}
            <RefreshCw class="w-4 h-4" />
          {/if}
          Refresh
        </button>
      </div>

      <!-- Table -->
      <div class="flex-1 bg-base-100 rounded-lg shadow border border-base-200 overflow-auto">
        <DataTable
          {columns}
          data={valueSets}
          {loading}
          emptyMessage="No ValueSets found matching your search"
          hover={true}
          bordered={false}
          onRowClick={handleRowClick}
        />
      </div>
    </div>

    <!-- Right Column: ValueSet Detail -->
    <div class="bg-base-100 rounded-lg shadow border border-base-200 p-6 overflow-auto">
      {#if detailLoading}
        <div class="flex flex-col items-center justify-center h-full min-h-[300px]">
          <span class="loading loading-spinner loading-lg text-primary"></span>
          <p class="text-gray-500 mt-4">Loading ValueSet details...</p>
        </div>
      {:else if selectedValueSet}
        <div class="space-y-3">
          <!-- Header -->
          <div class="border-b border-base-300 pb-4">
            <h2 class="text-2xl font-bold text-gray-800">{selectedValueSet.Name}</h2>
            <div class="flex items-center gap-2 mt-2">
              <code class="px-2 py-1 bg-base-200 rounded text-sm font-mono text-gray-600">
                {selectedValueSet.ValueSetKey}
              </code>
              <button
                class="btn btn-xs btn-ghost btn-circle"
                onclick={() => copyToClipboard(selectedValueSet.ValueSetKey)}
                title="Copy ValueSet key"
              >
                {#if copiedKey === selectedValueSet.ValueSetKey}
                  <svg class="w-4 h-4 text-success" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                  </svg>
                {:else}
                  <Copy class="w-4 h-4 opacity-60" />
                {/if}
              </button>
            </div>
          </div>

          <!-- Items Table -->
          <div>
            <h3 class="font-semibold mb-3 flex items-center gap-2">
              <Hash class="w-4 h-4 opacity-60" />
              <span>Items</span>
              <span class="badge badge-primary badge-sm">
                {selectedValueSet.Items?.length || 0} items
              </span>
            </h3>
            
            {#if selectedValueSet.Items && selectedValueSet.Items.length > 0}
              <div class="bg-base-100 rounded-lg border border-base-200 overflow-hidden">
                <DataTable
                  columns={itemColumns}
                  data={selectedValueSet.Items}
                  loading={false}
                  emptyMessage="No items in this ValueSet"
                  hover={true}
                  bordered={false}
                  compact={true}
                />
              </div>
            {:else}
              <div class="flex flex-col items-center justify-center py-8 text-gray-400 bg-base-50 rounded-lg border border-dashed border-base-300">
                <ListX class="w-8 h-8 mb-2 opacity-50" />
                <p class="text-sm">No items in this ValueSet</p>
              </div>
            {/if}
          </div>
        </div>
      {:else}
        <div class="flex flex-col items-center justify-center h-full min-h-[300px] text-gray-400">
          <ListX class="w-16 h-16 mb-4 opacity-50" />
          <p class="text-lg font-medium">No ValueSet Selected</p>
          <p class="text-sm mt-1">Click on a ValueSet from the list to view its details</p>
        </div>
      {/if}
    </div>
  </div>
</div>
