<script>
  import { onMount } from 'svelte';
  import { success as toastSuccess, error as toastError } from '$lib/utils/toast.js';
  import {
    fetchEquipmentList,
    createEquipment,
    updateEquipment,
    deleteEquipment,
  } from '$lib/api/equipment.js';
  import { fetchDepartments } from '$lib/api/organization.js';
  import DataTable from '$lib/components/DataTable.svelte';
  import EquipmentModal from './EquipmentModal.svelte';
  import DeleteConfirmModal from './DeleteConfirmModal.svelte';
  import { Plus, Edit2, Trash2, ArrowLeft, Search, Activity } from 'lucide-svelte';

  let loading = $state(false);
  let items = $state([]);
  let departments = $state([]);
  let modalOpen = $state(false);
  let modalMode = $state('create');
  let saving = $state(false);
  let formData = $state({
    EID: null,
    IEID: '',
    InstrumentID: '',
    InstrumentName: '',
    DepartmentID: null,
    WorkstationID: null,
    Enable: 1,
    EquipmentRole: '',
  });
  let deleteConfirmOpen = $state(false);
  let deleteItem = $state(null);
  let deleting = $state(false);
  let searchQuery = $state('');

  const columns = [
    { key: 'IEID', label: 'IEID', class: 'font-medium' },
    { key: 'InstrumentName', label: 'Name' },
    { key: 'DepartmentName', label: 'Department' },
    { key: 'Enable', label: 'Status', class: 'w-24 text-center' },
    { key: 'actions', label: 'Actions', class: 'w-32 text-center' },
  ];

  onMount(async () => {
    await Promise.all([loadItems(), loadDepartments()]);
  });

  async function loadItems() {
    loading = true;
    try {
      const response = await fetchEquipmentList();
      items = response.data || [];
    } catch (err) {
      toastError(err.message || 'Failed to load equipment');
      items = [];
    } finally {
      loading = false;
    }
  }

  async function loadDepartments() {
    try {
      const response = await fetchDepartments();
      departments = response.data || [];
    } catch (err) {
      console.error('Failed to load departments:', err);
      departments = [];
    }
  }

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

  function openCreateModal() {
    modalMode = 'create';
    formData = {
      EID: null,
      IEID: '',
      InstrumentID: '',
      InstrumentName: '',
      DepartmentID: departments.length > 0 ? departments[0].DepartmentID : null,
      WorkstationID: null,
      Enable: 1,
      EquipmentRole: '',
    };
    modalOpen = true;
  }

  function openEditModal(row) {
    modalMode = 'edit';
    formData = {
      EID: row.EID,
      IEID: row.IEID || '',
      InstrumentID: row.InstrumentID || '',
      InstrumentName: row.InstrumentName || '',
      DepartmentID: row.DepartmentID,
      WorkstationID: row.WorkstationID,
      Enable: row.Enable ?? 1,
      EquipmentRole: row.EquipmentRole || '',
    };
    modalOpen = true;
  }

  function validateForm() {
    if (!formData.IEID.trim()) {
      toastError('IEID is required');
      return false;
    }
    if (!formData.DepartmentID) {
      toastError('Department is required');
      return false;
    }
    if (!formData.EquipmentRole.trim()) {
      toastError('Equipment Role is required');
      return false;
    }
    return true;
  }

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

    saving = true;
    try {
      if (modalMode === 'create') {
        await createEquipment(formData);
        toastSuccess('Equipment created successfully');
      } else {
        await updateEquipment(formData.EID, formData);
        toastSuccess('Equipment updated successfully');
      }
      modalOpen = false;
      await loadItems();
    } catch (err) {
      toastError(err.message || 'Failed to save equipment');
    } finally {
      saving = false;
    }
  }

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

  async function handleDelete() {
    if (!deleteItem?.EID) return;
    
    deleting = true;
    try {
      await deleteEquipment(deleteItem.EID);
      toastSuccess('Equipment deleted successfully');
      deleteConfirmOpen = false;
      deleteItem = null;
      await loadItems();
    } catch (err) {
      toastError(err.message || 'Failed to delete equipment');
    } finally {
      deleting = false;
    }
  }

  function getStatusBadge(enable) {
    return enable === 1
      ? '<span class="badge badge-success badge-sm">Active</span>'
      : '<span class="badge badge-error badge-sm">Inactive</span>';
  }
</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">Equipment</h1>
      <p class="text-sm text-gray-600">Manage laboratory equipment</p>
    </div>
    <button class="btn btn-primary" onclick={openCreateModal}>
      <Plus class="w-4 h-4 mr-2" />
      Add Equipment
    </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 IEID 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">
          <Activity class="w-8 h-8 text-gray-400" />
        </div>
        <h3 class="text-base font-semibold text-base-content mb-1">
          {searchQuery ? 'No equipment found' : 'No equipment yet'}
        </h3>
        <p class="text-sm text-base-content/60 text-center max-w-sm mb-4">
          {searchQuery
            ? `No equipment match your search "${searchQuery}". Try a different search term.`
            : 'Get started by adding your first equipment.'}
        </p>
        {#if !searchQuery}
          <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
            <Plus class="w-4 h-4 mr-2" />
            Add Your First Equipment
          </button>
        {/if}
      </div>
    {:else}
      <DataTable
        {columns}
        data={filteredItems}
        {loading}
        emptyMessage="No equipment 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.InstrumentName}">
                <Edit2 class="w-4 h-4" />
              </button>
              <button class="btn btn-sm btn-ghost text-error" onclick={() => confirmDelete(row)} aria-label="Delete {row.InstrumentName}">
                <Trash2 class="w-4 h-4" />
              </button>
            </div>
          {:else if column.key === 'Enable'}
            {@html getStatusBadge(row.Enable)}
          {:else}
            {row[column.key] || '-'}
          {/if}
        {/snippet}
      </DataTable>
    {/if}
  </div>
</div>

<EquipmentModal
  bind:open={modalOpen}
  mode={modalMode}
  bind:formData
  {departments}
  {saving}
  onSave={handleSave}
  onCancel={() => (modalOpen = false)}
/>

<DeleteConfirmModal
  bind:open={deleteConfirmOpen}
  item={deleteItem}
  {deleting}
  onConfirm={handleDelete}
  onCancel={() => (deleteConfirmOpen = false)}
/>
