<script>
  import { onMount } from 'svelte';
  import {
    fetchAccounts,
    createAccount,
    updateAccount,
    deleteAccount,
  } 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, User } 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({
    AccountID: null,
    AccountName: '',
    Initial: '',
    Parent: null,
  });
  let deleteConfirmOpen = $state(false);
  let deleteItem = $state(null);
  let deleting = $state(false);
  let searchQuery = $state('');

  const columns = [
    { key: 'Initial', label: 'Initial', class: 'font-medium w-24' },
    { key: 'AccountName', label: 'Name' },
    { key: 'ParentName', label: 'Parent', 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 fetchAccounts();
      items = Array.isArray(response.data) ? response.data : [];
    } catch (err) {
      toastError(err.message || 'Failed to load accounts');
      items = [];
    } finally {
      loading = false;
    }
  }

  const itemsWithParentName = $derived(
    items.map((item) => ({
      ...item,
      ParentName: item.ParentName || (item.Parent ? 'Parent ' + item.Parent : '-'),
    }))
  );

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

  function openCreateModal() {
    modalMode = 'create';
    formData = { AccountID: null, AccountName: '', Initial: '', Parent: null };
    modalOpen = true;
  }

  function openEditModal(row) {
    modalMode = 'edit';
    formData = {
      AccountID: row.id || row.AccountID,
      AccountName: row.AccountName,
      Initial: row.Initial || '',
      Parent: row.Parent || null,
    };
    modalOpen = true;
  }

  async function handleSave() {
    if (!formData.AccountName.trim()) {
      toastError('Account name is required');
      return;
    }

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

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

  async function handleDelete() {
    deleting = true;
    try {
      const accountId = deleteItem.id || deleteItem.AccountID;
      await deleteAccount(accountId);
      toastSuccess('Account deleted successfully');
      deleteConfirmOpen = false;
      deleteItem = null;
      await loadItems();
    } catch (err) {
      toastError(err.message || 'Failed to delete account');
    } 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">Accounts</h1>
      <p class="text-sm text-gray-600">Manage organization accounts</p>
    </div>
    <button class="btn btn-primary" onclick={openCreateModal}>
      <Plus class="w-4 h-4 mr-2" />
      Add Account
    </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-5 h-5 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">
          <User class="w-8 h-8 text-gray-400" />
        </div>
        <h3 class="text-base font-semibold text-base-content mb-1">
          {searchQuery ? 'No accounts found' : 'No accounts yet'}
        </h3>
        <p class="text-sm text-base-content/60 text-center max-w-sm mb-4">
          {searchQuery
            ? `No accounts match your search "${searchQuery}". Try a different search term.`
            : 'Get started by adding your first account.'}
        </p>
        {#if !searchQuery}
          <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
            <Plus class="w-4 h-4 mr-2" />
            Add Your First Account
          </button>
        {/if}
      </div>
    {:else}
      <DataTable
        {columns}
        data={filteredItems}
        {loading}
        emptyMessage="No accounts 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.AccountName}">
                <Edit2 class="w-4 h-4" />
              </button>
              <button class="btn btn-sm btn-ghost text-error" onclick={() => confirmDelete(row)} aria-label="Delete {row.AccountName}">
                <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 Account' : 'Edit Account'} 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="accountName">
          <span class="label-text text-sm font-medium">Account Name</span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="accountName"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.AccountName}
          placeholder="e.g., Main Account"
          required
        />
        <span class="label-text-alt text-xs text-gray-500">Display name for this account</span>
      </div>
      <div class="form-control">
        <label class="label" for="initial">
          <span class="label-text text-sm font-medium">Initial</span>
        </label>
        <input
          id="initial"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.Initial}
          placeholder="e.g., QAC"
        />
        <span class="label-text-alt text-xs text-gray-500">Account initial/code</span>
      </div>
    </div>
    <div class="form-control">
      <label class="label" for="parentAccount">
        <span class="label-text text-sm font-medium">Parent Account</span>
      </label>
      <select
        id="parentAccount"
        class="select select-sm select-bordered w-full"
        bind:value={formData.Parent}
      >
        <option value={null}>None (Top-level account)</option>
        {#each items.filter((a) => (a.id || a.AccountID) !== formData.AccountID) as account}
          <option value={account.id || account.AccountID}>{account.AccountName}</option>
        {/each}
      </select>
      <span class="label-text-alt text-xs text-gray-500">Optional parent for hierarchical structure</span>
    </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 account?
    </p>
      <div class="bg-base-200 rounded-lg p-3 mt-3">
        <p class="font-semibold text-base-content">{deleteItem?.AccountName}</p>
        <p class="text-sm text-base-content/60">Initial: {deleteItem?.Initial || '-'}</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>
