<script>
  import { onMount } from 'svelte';
  import {
    fetchWorkstations,
    createWorkstation,
    updateWorkstation,
    deleteWorkstation,
    fetchSites,
    fetchDepartments,
  } 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, Monitor } from 'lucide-svelte';

  let loading = $state(false);
  let items = $state([]);
  let sites = $state([]);
  let departments = $state([]);
  let modalOpen = $state(false);
  let modalMode = $state('create');
  let saving = $state(false);
  let formData = $state({
    WorkstationID: null,
    WorkstationCode: '',
    WorkstationName: '',
    SiteID: null,
    DepartmentID: null,
  });
  let deleteConfirmOpen = $state(false);
  let deleteItem = $state(null);
  let deleting = $state(false);
  let searchQuery = $state('');

  const columns = [
    { key: 'WorkstationCode', label: 'Code', class: 'font-medium' },
    { key: 'WorkstationName', label: 'Name' },
    { key: 'SiteName', label: 'Site', class: 'w-40' },
    { key: 'DepartmentName', label: 'Department', class: 'w-40' },
    { key: 'actions', label: 'Actions', class: 'w-32 text-center' },
  ];

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

  async function loadSites() {
    try {
      const response = await fetchSites();
      sites = Array.isArray(response.data) ? response.data : [];
    } catch (err) {
      sites = [];
    }
  }

  async function loadDepartments() {
    try {
      const response = await fetchDepartments();
      departments = Array.isArray(response.data) ? response.data : [];
    } catch (err) {
      departments = [];
    }
  }

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

  const itemsWithNames = $derived(
    items.map((item) => ({
      ...item,
      SiteName: sites.find((s) => s.id === item.SiteID || s.SiteID === item.SiteID)?.SiteName || '-',
      DepartmentName: departments.find((d) => d.id === item.DepartmentID || d.DepartmentID === item.DepartmentID)?.DeptName || departments.find((d) => d.id === item.DepartmentID || d.DepartmentID === item.DepartmentID)?.DepartmentName || '-',
    }))
  );

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

  function openCreateModal() {
    modalMode = 'create';
    formData = { WorkstationID: null, WorkstationCode: '', WorkstationName: '', SiteID: null, DepartmentID: null };
    modalOpen = true;
  }

  function openEditModal(row) {
    modalMode = 'edit';
    formData = {
      WorkstationID: row.id || row.WorkstationID,
      WorkstationCode: row.WorkstationCode,
      WorkstationName: row.WorkstationName,
      SiteID: row.SiteID,
      DepartmentID: row.DepartmentID,
    };
    modalOpen = true;
  }

  async function handleSave() {
    if (!formData.WorkstationCode.trim()) {
      toastError('Workstation code is required');
      return;
    }
    if (!formData.WorkstationName.trim()) {
      toastError('Workstation name is required');
      return;
    }

    saving = true;
    try {
      if (modalMode === 'create') {
        await createWorkstation(formData);
        toastSuccess('Workstation created successfully');
      } else {
        await updateWorkstation(formData.WorkstationID, formData);
        toastSuccess('Workstation updated successfully');
      }
      modalOpen = false;
      await loadItems();
    } catch (err) {
      toastError(err.message || 'Failed to save workstation');
    } finally {
      saving = false;
    }
  }

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

  async function handleDelete() {
    deleting = true;
    try {
      const wsId = deleteItem.id || deleteItem.WorkstationID;
      await deleteWorkstation(wsId);
      toastSuccess('Workstation deleted successfully');
      deleteConfirmOpen = false;
      deleteItem = null;
      await loadItems();
    } catch (err) {
      toastError(err.message || 'Failed to delete workstation');
    } 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">Workstations</h1>
      <p class="text-sm text-gray-600">Manage organization workstations</p>
    </div>
    <button class="btn btn-primary" onclick={openCreateModal}>
      <Plus class="w-4 h-4 mr-2" />
      Add Workstation
    </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">
          <Monitor class="w-8 h-8 text-gray-400" />
        </div>
        <h3 class="text-base font-semibold text-base-content mb-1">
          {searchQuery ? 'No workstations found' : 'No workstations yet'}
        </h3>
        <p class="text-sm text-base-content/60 text-center max-w-sm mb-4">
          {searchQuery
            ? `No workstations match your search "${searchQuery}". Try a different search term.`
            : 'Get started by adding your first workstation.'}
        </p>
        {#if !searchQuery}
          <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
            <Plus class="w-4 h-4 mr-2" />
            Add Your First Workstation
          </button>
        {/if}
      </div>
    {:else}
      <DataTable
        {columns}
        data={filteredItems}
        {loading}
        emptyMessage="No workstations 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.WorkstationName}">
                <Edit2 class="w-4 h-4" />
              </button>
              <button class="btn btn-sm btn-ghost text-error" onclick={() => confirmDelete(row)} aria-label="Delete {row.WorkstationName}">
                <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 Workstation' : 'Edit Workstation'} 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="workstationCode">
          <span class="label-text text-sm font-medium">Workstation Code</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="workstationCode"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.WorkstationCode}
          placeholder="e.g., WS001"
          required
        />
        <span class="label-text-alt text-xs text-gray-500">Unique identifier for this workstation</span>
      </div>
      <div class="form-control">
        <label class="label" for="workstationName">
          <span class="label-text text-sm font-medium">Workstation Name</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="workstationName"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.WorkstationName}
          placeholder="e.g., Lab Workstation 1"
          required
        />
        <span class="label-text-alt text-xs text-gray-500">Display name for this workstation</span>
      </div>
    </div>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div class="form-control">
        <label class="label" for="site">
          <span class="label-text text-sm font-medium">Site</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <select
          id="site"
          class="select select-sm select-bordered w-full"
          bind:value={formData.SiteID}
          required
        >
          <option value={null}>Select site...</option>
          {#each sites as site}
            <option value={site.id || site.SiteID}>{site.SiteName}</option>
          {/each}
        </select>
        <span class="label-text-alt text-xs text-gray-500">The site this workstation belongs to</span>
      </div>
      <div class="form-control">
        <label class="label" for="department">
          <span class="label-text text-sm font-medium">Department</span>
        </label>
        <select
          id="department"
          class="select select-sm select-bordered w-full"
          bind:value={formData.DepartmentID}
        >
          <option value={null}>Select department...</option>
          {#each departments.filter((d) => !formData.SiteID || d.SiteID === formData.SiteID) as dept}
            <option value={dept.id || dept.DepartmentID}>{dept.DeptName || dept.DepartmentName}</option>
          {/each}
        </select>
        <span class="label-text-alt text-xs text-gray-500">The department this workstation belongs to</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 workstation?
    </p>
    <div class="bg-base-200 rounded-lg p-3 mt-3">
      <p class="font-semibold text-base-content">{deleteItem?.WorkstationName}</p>
      <p class="text-sm text-base-content/60">Code: {deleteItem?.WorkstationCode}</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>
