<script>
  import { onMount } from 'svelte';
  import { fetchSpecialties, createSpecialty, updateSpecialty, deleteSpecialty } from '$lib/api/specialties.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 SelectDropdown from '$lib/components/SelectDropdown.svelte';
  import { Plus, Edit2, Trash2, ArrowLeft } from 'lucide-svelte';

  let loading = $state(false);
  let specialties = $state([]);
  let modalOpen = $state(false);
  let modalMode = $state('create');
  let saving = $state(false);
  let formData = $state({ SpecialtyID: null, SpecialtyText: '', Title: '', Parent: '' });
  let deleteConfirmOpen = $state(false);
  let deleteItem = $state(null);

  const columns = [
    { key: 'SpecialtyText', label: 'Specialty Name', class: 'font-medium' },
    { key: 'Title', label: 'Title' },
    { key: 'ParentLabel', label: 'Parent' },
    { key: 'actions', label: 'Actions', class: 'w-32 text-center' },
  ];

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

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

  function openCreateModal() {
    modalMode = 'create';
    formData = { SpecialtyID: null, SpecialtyText: '', Title: '', Parent: '' };
    modalOpen = true;
  }

  function openEditModal(row) {
    modalMode = 'edit';
    formData = {
      SpecialtyID: row.SpecialtyID,
      SpecialtyText: row.SpecialtyText || '',
      Title: row.Title || '',
      Parent: row.Parent || '',
    };
    modalOpen = true;
  }

  async function handleSave() {
    saving = true;
    try {
      if (modalMode === 'create') {
        await createSpecialty(formData);
        toastSuccess('Specialty created successfully');
      } else {
        await updateSpecialty(formData);
        toastSuccess('Specialty updated successfully');
      }
      modalOpen = false;
      await loadSpecialties();
    } catch (err) {
      toastError(err.message || 'Failed to save specialty');
    } finally {
      saving = false;
    }
  }

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

  async function handleDelete() {
    try {
      await deleteSpecialty(deleteItem.SpecialtyID);
      toastSuccess('Specialty deleted successfully');
      deleteConfirmOpen = false;
      await loadSpecialties();
    } catch (err) {
      toastError(err.message || 'Failed to delete specialty');
    }
  }

  const parentOptions = $derived(
    specialties
      .filter((s) => s.SpecialtyID !== formData.SpecialtyID)
      .map((s) => ({ value: s.SpecialtyID, label: s.SpecialtyText }))
  );

  const specialtyMap = $derived(
    Object.fromEntries(specialties.map((s) => [s.SpecialtyID, s.SpecialtyText]))
  );
</script>

<div class="p-6">
  <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-3xl font-bold text-gray-800">Medical Specialties</h1>
      <p class="text-gray-600">Manage medical specialty codes</p>
    </div>
    <button class="btn btn-primary" onclick={openCreateModal}>
      <Plus class="w-4 h-4 mr-2" />
      Add Specialty
    </button>
  </div>

  <div class="bg-base-100 rounded-lg shadow border border-base-200">
    <DataTable
      {columns}
      data={specialties.map((s) => ({
        ...s,
        ParentLabel: s.Parent === '0' || !s.Parent ? '-' : specialtyMap[s.Parent] || '-',
      }))}
      {loading}
      emptyMessage="No specialties 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)}>
              <Edit2 class="w-4 h-4" />
            </button>
            <button class="btn btn-sm btn-ghost text-error" onclick={() => confirmDelete(row)}>
              <Trash2 class="w-4 h-4" />
            </button>
          </div>
        {:else}
          {value}
        {/if}
      {/snippet}
    </DataTable>
  </div>
</div>

<Modal bind:open={modalOpen} title={modalMode === 'create' ? 'Add Specialty' : 'Edit Specialty'} size="md">
  <form class="space-y-5" 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="specialtyText">
          <span class="label-text font-medium">Specialty Name</span>
          <span class="label-text-alt text-error">*</span>
        </label>
        <input
          id="specialtyText"
          type="text"
          class="input input-bordered w-full"
          bind:value={formData.SpecialtyText}
          placeholder="Enter specialty name"
          required
        />
      </div>
      <div class="form-control">
        <label class="label" for="title">
          <span class="label-text font-medium">Title</span>
        </label>
        <input
          id="title"
          type="text"
          class="input input-bordered w-full"
          bind:value={formData.Title}
          placeholder="e.g., Sp. A, Sp. And"
        />
      </div>
    </div>
    <SelectDropdown
      label="Parent Specialty"
      name="parent"
      bind:value={formData.Parent}
      options={parentOptions}
      placeholder="None"
    />
  </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 <strong class="text-base-content">{deleteItem?.SpecialtyText}</strong>?
    </p>
    <p class="text-sm text-error mt-2">This action cannot be undone.</p>
  </div>
  {#snippet footer()}
    <button class="btn btn-ghost" onclick={() => (deleteConfirmOpen = false)} type="button">Cancel</button>
    <button class="btn btn-error" onclick={handleDelete} type="button">Delete</button>
  {/snippet}
</Modal>
