<script>
  import { onMount } from 'svelte';
  import {
    fetchDisciplines,
    createDiscipline,
    updateDiscipline,
    deleteDiscipline,
  } 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, Building2 } 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({
    DisciplineID: null,
    DisciplineCode: '',
    DisciplineName: '',
    Parent: null,
    SeqScr: 0,
    SeqRpt: 0,
  });
  let deleteConfirmOpen = $state(false);
  let deleteItem = $state(null);
  let deleting = $state(false);
  let searchQuery = $state('');

  const columns = [
    { key: 'DisciplineCode', label: 'Code', class: 'font-medium' },
    { key: 'DisciplineName', label: 'Name' },
    { key: 'SeqScr', label: 'Screen Seq', class: 'w-24 text-center' },
    { key: 'SeqRpt', label: 'Report Seq', class: 'w-24 text-center' },
    { key: 'ParentName', label: 'Parent Discipline', class: 'w-48' },
    { key: 'actions', label: 'Actions', class: 'w-32 text-center' },
  ];

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

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

  const itemsWithParentName = $derived(
    items.map((d) => ({
      ...d,
      ParentName: d.Parent
        ? items.find((p) => p.DisciplineID === d.Parent)?.DisciplineName || '-'
        : '-',
    }))
  );

  const filteredItems = $derived(
    itemsWithParentName.filter((item) => {
      if (!searchQuery.trim()) return true;
      const query = searchQuery.toLowerCase();
      return (
        (item.DisciplineCode && item.DisciplineCode.toLowerCase().includes(query)) ||
        (item.DisciplineName && item.DisciplineName.toLowerCase().includes(query))
      );
    })
  );

  function openCreateModal() {
    modalMode = 'create';
    formData = { DisciplineID: null, DisciplineCode: '', DisciplineName: '', Parent: null, SeqScr: 0, SeqRpt: 0 };
    modalOpen = true;
  }

  function openEditModal(row) {
    modalMode = 'edit';
    formData = {
      DisciplineID: row.id || row.DisciplineID,
      DisciplineCode: row.DisciplineCode,
      DisciplineName: row.DisciplineName,
      Parent: row.Parent || null,
      SeqScr: row.SeqScr ?? 0,
      SeqRpt: row.SeqRpt ?? 0,
    };
    modalOpen = true;
  }

  async function handleSave() {
    if (!formData.DisciplineCode.trim()) {
      toastError('Discipline code is required');
      return;
    }
    if (!formData.DisciplineName.trim()) {
      toastError('Discipline name is required');
      return;
    }
    if (formData.SeqScr === null || formData.SeqScr === undefined || formData.SeqScr === '') {
      toastError('Screen sequence is required');
      return;
    }
    if (formData.SeqRpt === null || formData.SeqRpt === undefined || formData.SeqRpt === '') {
      toastError('Report sequence is required');
      return;
    }

    saving = true;
    try {
      if (modalMode === 'create') {
        await createDiscipline(formData);
        toastSuccess('Discipline created successfully');
      } else {
        await updateDiscipline(formData);
        toastSuccess('Discipline updated successfully');
      }
      modalOpen = false;
      await loadItems();
    } catch (err) {
      toastError(err.message || 'Failed to save discipline');
    } finally {
      saving = false;
    }
  }

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

  async function handleDelete() {
    deleting = true;
    try {
      const disciplineId = deleteItem.id || deleteItem.DisciplineID;
      await deleteDiscipline(disciplineId);
      toastSuccess('Discipline deleted successfully');
      deleteConfirmOpen = false;
      deleteItem = null;
      await loadItems();
    } catch (err) {
      toastError(err.message || 'Failed to delete discipline');
    } 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">Disciplines</h1>
      <p class="text-sm text-gray-600">Manage organization disciplines</p>
    </div>
    <button class="btn btn-primary" onclick={openCreateModal}>
      <Plus class="w-4 h-4 mr-2" />
      Add Discipline
    </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 code or name..."
            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">
          <Building2 class="w-8 h-8 text-gray-400" />
        </div>
        <h3 class="text-base font-semibold text-base-content mb-1">
          {searchQuery ? 'No disciplines found' : 'No disciplines yet'}
        </h3>
        <p class="text-sm text-base-content/60 text-center max-w-sm mb-4">
          {searchQuery
            ? `No disciplines match your search "${searchQuery}". Try a different search term.`
            : 'Get started by adding your first discipline.'}
        </p>
        {#if !searchQuery}
          <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
            <Plus class="w-4 h-4 mr-2" />
            Add Your First Discipline
          </button>
        {/if}
      </div>
    {:else}
      <DataTable
        {columns}
        data={filteredItems}
        {loading}
        emptyMessage="No disciplines 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.DisciplineName}">
                <Edit2 class="w-4 h-4" />
              </button>
              <button class="btn btn-sm btn-ghost text-error" onclick={() => confirmDelete(row)} aria-label="Delete {row.DisciplineName}">
                <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 Discipline' : 'Edit Discipline'} 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="disciplineCode">
          <span class="label-text text-sm font-medium">Discipline Code</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="disciplineCode"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.DisciplineCode}
          placeholder="e.g., HEM, CHEM"
          required
        />
        <span class="label-text-alt text-xs text-gray-500">Unique identifier for this discipline</span>
      </div>
      <div class="form-control">
        <label class="label" for="disciplineName">
          <span class="label-text text-sm font-medium">Discipline Name</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="disciplineName"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.DisciplineName}
          placeholder="e.g., Hematology"
          required
        />
        <span class="label-text-alt text-xs text-gray-500">Display name for this discipline</span>
      </div>
    </div>
    <div class="form-control">
      <label class="label" for="parentDiscipline">
        <span class="label-text text-sm font-medium">Parent Discipline</span>
      </label>
      <select
        id="parentDiscipline"
        class="select select-sm select-bordered w-full"
        bind:value={formData.Parent}
      >
        <option value={null}>None (Top-level discipline)</option>
        {#each items.filter((d) => (d.id || d.DisciplineID) !== formData.DisciplineID) as discipline}
          <option value={discipline.id || discipline.DisciplineID}>{discipline.DisciplineName}</option>
        {/each}
      </select>
      <span class="label-text-alt text-xs text-gray-500">Optional parent for hierarchical structure</span>
    </div>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div class="form-control">
        <label class="label" for="SeqScr">
          <span class="label-text text-sm font-medium">Screen Sequence</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="SeqScr"
          type="number"
          class="input input-sm input-bordered w-full"
          bind:value={formData.SeqScr}
          placeholder="0"
          required
          min="0"
        />
        <span class="label-text-alt text-xs text-gray-500">Order for screen display</span>
      </div>
      <div class="form-control">
        <label class="label" for="SeqRpt">
          <span class="label-text text-sm font-medium">Report Sequence</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="SeqRpt"
          type="number"
          class="input input-sm input-bordered w-full"
          bind:value={formData.SeqRpt}
          placeholder="0"
          required
          min="0"
        />
        <span class="label-text-alt text-xs text-gray-500">Order for report display</span>
      </div>
    </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 discipline?
    </p>
    <div class="bg-base-200 rounded-lg p-3 mt-3">
      <p class="font-semibold text-base-content">{deleteItem?.DisciplineName}</p>
      <p class="text-sm text-base-content/60">Code: {deleteItem?.DisciplineCode}</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>
