<script>
  import { onMount } from 'svelte';
  import {
    fetchCodingSystems,
    createCodingSystem,
    updateCodingSystem,
    deleteCodingSystem,
  } from '$lib/api/organization.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 { Plus, Edit2, Trash2, ArrowLeft, Search, FileCode } from 'lucide-svelte';

  let loading = $state(false);
  let items = $state([]);
  let modalOpen = $state(false);
  let modalMode = $state('create');
  let saving = $state(false);
  let formData = $state({
    CodingSysID: null,
    CodingSysAbb: '',
    FullText: '',
    Description: '',
  });
  let deleteConfirmOpen = $state(false);
  let deleteItem = $state(null);
  let deleting = $state(false);
  let searchQuery = $state('');

  const columns = [
    { key: 'CodingSysAbb', label: 'Abbreviation', class: 'font-medium w-32' },
    { key: 'FullText', label: 'Full Text' },
    { key: 'Description', label: 'Description', class: 'text-gray-600' },
    { key: 'actions', label: 'Actions', class: 'w-32 text-center' },
  ];

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

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

  const filteredItems = $derived(
    items.filter((item) => {
      if (!searchQuery.trim()) return true;
      const query = searchQuery.toLowerCase();
      return (
        (item.CodingSysAbb && item.CodingSysAbb.toLowerCase().includes(query)) ||
        (item.FullText && item.FullText.toLowerCase().includes(query)) ||
        (item.Description && item.Description.toLowerCase().includes(query))
      );
    })
  );

  function openCreateModal() {
    modalMode = 'create';
    formData = { CodingSysID: null, CodingSysAbb: '', FullText: '', Description: '' };
    modalOpen = true;
  }

  function openEditModal(row) {
    modalMode = 'edit';
    formData = {
      CodingSysID: row.CodingSysID,
      CodingSysAbb: row.CodingSysAbb,
      FullText: row.FullText,
      Description: row.Description || '',
    };
    modalOpen = true;
  }

  async function handleSave() {
    if (!formData.CodingSysAbb.trim()) {
      toastError('Abbreviation is required');
      return;
    }
    if (!formData.FullText.trim()) {
      toastError('Full text is required');
      return;
    }

    saving = true;
    try {
      if (modalMode === 'create') {
        await createCodingSystem(formData);
        toastSuccess('Coding system created successfully');
      } else {
        await updateCodingSystem(formData);
        toastSuccess('Coding system updated successfully');
      }
      modalOpen = false;
      await loadItems();
    } catch (err) {
      toastError(err.message || 'Failed to save coding system');
    } finally {
      saving = false;
    }
  }

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

  async function handleDelete() {
    deleting = true;
    try {
      await deleteCodingSystem(deleteItem.CodingSysID);
      toastSuccess('Coding system deleted successfully');
      deleteConfirmOpen = false;
      deleteItem = null;
      await loadItems();
    } catch (err) {
      toastError(err.message || 'Failed to delete coding system');
    } finally {
      deleting = false;
    }
  }
</script>

<div class="p-4">
  <div class="flex items-center gap-4 mb-6">
    <a href="/master-data/organization" 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">Coding Systems</h1>
      <p class="text-sm text-gray-600">Manage coding systems and terminologies</p>
    </div>
    <button class="btn btn-primary" onclick={openCreateModal}>
      <Plus class="w-4 h-4 mr-2" />
      Add Coding System
    </button>
  </div>

  <div class="bg-base-100 rounded-lg shadow border border-base-200">
    <div class="p-4 border-b border-base-200">
      <div class="flex items-center gap-3 max-w-md">
        <label class="input input-sm input-bordered w-full flex items-center gap-2">
          <Search class="w-4 h-4 text-gray-400" />
          <input
            type="text"
            class="grow"
            placeholder="Search by abbreviation, text or description..."
            bind:value={searchQuery}
          />
        </label>
        {#if searchQuery}
          <button class="btn btn-ghost btn-sm" onclick={() => (searchQuery = '')}>
            Clear
          </button>
        {/if}
      </div>
    </div>

    {#if !loading && filteredItems.length === 0}
      <div class="flex flex-col items-center justify-center py-16 px-4">
        <div class="w-16 h-16 rounded-full bg-base-200 flex items-center justify-center mb-4">
          <FileCode class="w-8 h-8 text-gray-400" />
        </div>
        <h3 class="text-base font-semibold text-base-content mb-1">
          {searchQuery ? 'No coding systems found' : 'No coding systems yet'}
        </h3>
        <p class="text-sm text-base-content/60 text-center max-w-sm mb-4">
          {searchQuery
            ? `No coding systems match your search "${searchQuery}". Try a different search term.`
            : 'Get started by adding your first coding system.'}
        </p>
        {#if !searchQuery}
          <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
            <Plus class="w-4 h-4 mr-2" />
            Add Your First Coding System
          </button>
        {/if}
      </div>
    {:else}
      <DataTable
        {columns}
        data={filteredItems}
        {loading}
        emptyMessage="No coding systems found"
        hover={true}
        bordered={false}
      >
        {#snippet cell({ column, row })}
          {#if column.key === 'actions'}
            <div class="flex justify-center gap-2">
              <button class="btn btn-sm btn-ghost" onclick={() => openEditModal(row)} aria-label="Edit {row.CodingSysAbb}">
                <Edit2 class="w-4 h-4" />
              </button>
              <button class="btn btn-sm btn-ghost text-error" onclick={() => confirmDelete(row)} aria-label="Delete {row.CodingSysAbb}">
                <Trash2 class="w-4 h-4" />
              </button>
            </div>
          {:else}
            {row[column.key]}
          {/if}
        {/snippet}
      </DataTable>
    {/if}
  </div>
</div>

<Modal bind:open={modalOpen} title={modalMode === 'create' ? 'Add Coding System' : 'Edit Coding System'} size="md">
  <form class="space-y-4" onsubmit={(e) => { e.preventDefault(); handleSave(); }}>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div class="form-control">
        <label class="label" for="codingSysAbb">
          <span class="label-text text-sm font-medium">Abbreviation</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="codingSysAbb"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.CodingSysAbb}
          placeholder="e.g., LOINC"
          required
        />
        <span class="label-text-alt text-xs text-gray-500">Short code for this coding system</span>
      </div>
      <div class="form-control">
        <label class="label" for="fullText">
          <span class="label-text text-sm font-medium">Full Text</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="fullText"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.FullText}
          placeholder="e.g., Logical Observation Identifiers Names and Codes"
          required
        />
        <span class="label-text-alt text-xs text-gray-500">Complete name of the coding system</span>
      </div>
    </div>
    <div class="form-control">
      <label class="label" for="description">
        <span class="label-text text-sm font-medium">Description</span>
      </label>
      <textarea
        id="description"
        class="textarea textarea-bordered w-full"
        bind:value={formData.Description}
        placeholder="Enter description..."
        rows="3"
      ></textarea>
      <span class="label-text-alt text-xs text-gray-500">Additional information about this coding system</span>
    </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}
        <span class="loading loading-spinner loading-sm mr-2"></span>
      {/if}
      {saving ? 'Saving...' : 'Save'}
    </button>
  {/snippet}
</Modal>

<Modal bind:open={deleteConfirmOpen} title="Confirm Delete" size="sm">
  <div class="py-2">
    <p class="text-base-content/80">
      Are you sure you want to delete the following coding system?
    </p>
    <div class="bg-base-200 rounded-lg p-3 mt-3">
      <p class="font-semibold text-base-content">{deleteItem?.CodingSysAbb}</p>
      <p class="text-sm text-base-content/60">{deleteItem?.FullText}</p>
    </div>
    <p class="text-sm text-error mt-4">This action cannot be undone.</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}
        <span class="loading loading-spinner loading-sm mr-2"></span>
      {/if}
      {deleting ? 'Deleting...' : 'Delete'}
    </button>
  {/snippet}
</Modal>
