<script>
  import { onMount } from 'svelte';
  import { fetchOccupations, createOccupation, updateOccupation } from '$lib/api/occupations.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 HelpTooltip from '$lib/components/HelpTooltip.svelte';
  import { Plus, Edit2, ArrowLeft, Search, Briefcase, Users } from 'lucide-svelte';

  let loading = $state(false);
  let occupations = $state([]);
  let modalOpen = $state(false);
  let modalMode = $state('create');
  let saving = $state(false);
  let formData = $state({ OccupationID: null, OccCode: '', OccText: '', Description: '' });
  let formErrors = $state({});

  // Search state
  let searchQuery = $state('');

  const columns = [
    { key: 'OccCode', label: 'Code', class: 'font-medium w-32' },
    { key: 'OccText', label: 'Occupation Name', class: 'font-medium' },
    { key: 'Description', label: 'Description' },
    { key: 'actions', label: 'Actions', class: 'w-32 text-center' },
  ];

  // Derived filtered occupations based on search query
  let filteredOccupations = $derived(
    searchQuery.trim()
      ? occupations.filter(occupation => {
          const query = searchQuery.toLowerCase().trim();
          return (
            (occupation.OccCode && occupation.OccCode.toLowerCase().includes(query)) ||
            (occupation.OccText && occupation.OccText.toLowerCase().includes(query))
          );
        })
      : occupations
  );

  // Check for duplicate occupation code
  function isDuplicateCode(code, excludeId = null) {
    const normalizedCode = code.trim().toUpperCase();
    return occupations.some(
      occ =>
        occ.OccCode.trim().toUpperCase() === normalizedCode &&
        occ.OccupationID !== excludeId
    );
  }

  // Validate form before submission
  function validateForm() {
    formErrors = {};
    let isValid = true;

    if (!formData.OccCode || formData.OccCode.trim() === '') {
      formErrors.OccCode = 'Occupation code is required';
      isValid = false;
    } else if (formData.OccCode.trim().length > 10) {
      formErrors.OccCode = 'Code must be 10 characters or less';
      isValid = false;
    } else if (isDuplicateCode(formData.OccCode, formData.OccupationID)) {
      formErrors.OccCode = `Code "${formData.OccCode.trim()}" already exists. Please use a unique code.`;
      isValid = false;
    }

    if (!formData.OccText || formData.OccText.trim() === '') {
      formErrors.OccText = 'Occupation name is required';
      isValid = false;
    } else if (formData.OccText.trim().length > 100) {
      formErrors.OccText = 'Name must be 100 characters or less';
      isValid = false;
    }

    if (formData.Description && formData.Description.length > 255) {
      formErrors.Description = 'Description must be 255 characters or less';
      isValid = false;
    }

    return isValid;
  }

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

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

  function handleSearchKeydown(event) {
    if (event.key === 'Enter') {
      // Search is reactive via $derived, but this allows for future server-side search
      event.preventDefault();
    }
  }

  function openCreateModal() {
    modalMode = 'create';
    formData = { OccupationID: null, OccCode: '', OccText: '', Description: '' };
    formErrors = {};
    modalOpen = true;
  }

  function openEditModal(row) {
    modalMode = 'edit';
    formData = {
      OccupationID: row.OccupationID,
      OccCode: row.OccCode || '',
      OccText: row.OccText || '',
      Description: row.Description || '',
    };
    formErrors = {};
    modalOpen = true;
  }

  async function handleSave() {
    if (!validateForm()) {
      return;
    }

    saving = true;
    try {
      if (modalMode === 'create') {
        await createOccupation(formData);
        toastSuccess('Occupation created successfully');
      } else {
        await updateOccupation(formData.OccupationID, formData);
        toastSuccess('Occupation updated successfully');
      }
      modalOpen = false;
      await loadOccupations();
    } catch (err) {
      toastError(err.message || 'Failed to save occupation');
    } finally {
      saving = false;
    }
  }

  function handleModalClose() {
    if (!saving) {
      modalOpen = false;
      formErrors = {};
    }
  }
</script>

<div class="p-4">
  <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-xl font-bold text-gray-800">Occupations</h1>
      <p class="text-sm text-gray-600">Manage occupation codes for patient demographics</p>
    </div>
    <button class="btn btn-primary" onclick={openCreateModal}>
      <Plus class="w-4 h-4 mr-2" />
      Add Occupation
    </button>
  </div>

  <!-- Search Section -->
  <div class="bg-base-100 rounded-lg shadow border border-base-200 p-4 mb-4">
    <div class="flex flex-col sm:flex-row gap-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 by code or occupation name..."
          class="grow"
          bind:value={searchQuery}
          onkeydown={handleSearchKeydown}
        />
      </label>
    </div>
  </div>

  <div class="bg-base-100 rounded-lg shadow border border-base-200">
    {#if !loading && filteredOccupations.length === 0}
      <!-- Empty State -->
      <div class="flex flex-col items-center justify-center py-16 px-4">
        <div class="bg-base-200 rounded-full p-6 mb-4">
          {#if searchQuery.trim()}
            <Search class="w-12 h-12 text-gray-400" />
          {:else}
            <Briefcase class="w-12 h-12 text-gray-400" />
          {/if}
        </div>
        <h3 class="text-base font-semibold text-gray-700 mb-2">
          {searchQuery.trim() ? 'No occupations match your search' : 'No occupations found'}
        </h3>
        <p class="text-xs text-gray-500 text-center max-w-md mb-6">
          {searchQuery.trim()
            ? `No occupations found matching "${searchQuery}". Try a different search term or clear the filter.`
            : 'Get started by adding your first occupation code. These codes are used when registering patients to identify their profession.'}
        </p>
        {#if searchQuery.trim()}
          <button class="btn btn-outline" onclick={() => searchQuery = ''}>
            Clear Search
          </button>
        {:else}
          <button class="btn btn-primary" onclick={openCreateModal}>
            <Plus class="w-4 h-4 mr-2" />
            Add Occupation
          </button>
        {/if}
      </div>
    {:else}
      <DataTable
        {columns}
        data={filteredOccupations}
        {loading}
        emptyMessage="No occupations 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)} title="Edit occupation">
                <Edit2 class="w-4 h-4" />
              </button>
            </div>
          {:else if column.key === 'OccCode'}
            <span class="badge badge-outline badge-primary font-mono text-xs">{value}</span>
          {:else if column.key === 'Description'}
            <span class="text-gray-500 text-sm">{value || '-'}</span>
          {:else}
            {value}
          {/if}
        {/snippet}
      </DataTable>
    {/if}
  </div>

  <!-- Info Card -->
  {#if !loading && filteredOccupations.length > 0}
    <div class="mt-4 bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3">
      <Users class="w-5 h-5 text-blue-500 mt-0.5 flex-shrink-0" />
      <div>
        <h4 class="text-sm font-medium text-blue-900">About Occupation Codes</h4>
        <p class="text-sm text-blue-700 mt-1">
          Occupation codes are used during patient registration to record the patient's profession.
          These codes help with demographic tracking and may be used for reporting purposes.
          Keep codes short and memorable (e.g., DR for Doctor, ENG for Engineer).
        </p>
      </div>
    </div>
  {/if}
</div>

<Modal bind:open={modalOpen} title={modalMode === 'create' ? 'Add Occupation' : 'Edit Occupation'} size="md">
  <form class="space-y-3" 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="occCode">
          <span class="label-text text-sm font-medium flex items-center gap-2">
            Occupation Code
            <HelpTooltip
              text="A short, unique code used to identify this occupation. This code will be displayed in patient demographics. Examples: DR (Doctor), NUR (Nurse), ENG (Engineer), TCH (Teacher). Keep it short (2-5 characters) for easy reference."
              title="Occupation Code Help"
              position="top"
            />
          </span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="occCode"
          type="text"
          class="input input-bordered w-full {formErrors.OccCode ? 'input-error' : ''}"
          bind:value={formData.OccCode}
          placeholder="e.g., DR, ENG, TCH"
          required
          maxlength="10"
          disabled={saving}
        />
        {#if formErrors.OccCode}
          <span class="label-text-alt text-xs text-error mt-1">{formErrors.OccCode}</span>
        {:else}
          <span class="label-text-alt text-xs text-gray-500">Short unique code (max 10 characters)</span>
        {/if}
      </div>
      <div class="form-control">
        <label class="label" for="occText">
          <span class="label-text text-sm font-medium">Occupation Name</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="occText"
          type="text"
          class="input input-bordered w-full {formErrors.OccText ? 'input-error' : ''}"
          bind:value={formData.OccText}
          placeholder="e.g., Doctor, Engineer, Teacher"
          required
          maxlength="100"
          disabled={saving}
        />
        {#if formErrors.OccText}
          <span class="label-text-alt text-xs text-error mt-1">{formErrors.OccText}</span>
        {:else}
          <span class="label-text-alt text-xs text-gray-500">Full name of the occupation</span>
        {/if}
      </div>
    </div>
    <div class="form-control">
      <label class="label" for="description">
        <span class="label-text text-sm font-medium">Description</span>
      </label>
      <input
        id="description"
        type="text"
        class="input input-bordered w-full {formErrors.Description ? 'input-error' : ''}"
        bind:value={formData.Description}
        placeholder="e.g., Medical practitioner, licensed physician"
        maxlength="255"
        disabled={saving}
      />
      {#if formErrors.Description}
        <span class="label-text-alt text-xs text-error mt-1">{formErrors.Description}</span>
      {:else}
        <span class="label-text-alt text-xs text-gray-500">Optional additional details about this occupation</span>
      {/if}
    </div>
  </form>
  {#snippet footer()}
    <button class="btn btn-ghost" onclick={handleModalClose} type="button" disabled={saving}>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>
