<script>
  import { onMount } from 'svelte';
  import { fetchContacts, createContact, updateContact, deleteContact } from '$lib/api/contacts.js';
  import { fetchSpecialties } 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 HelpTooltip from '$lib/components/HelpTooltip.svelte';
  import { Plus, Edit2, Trash2, ArrowLeft, Search, Users, Loader2 } from 'lucide-svelte';

  let loading = $state(false);
  let saving = $state(false);
  let deleting = $state(false);
  let contacts = $state([]);
  let specialties = $state([]);
  let searchQuery = $state('');
  let modalOpen = $state(false);
  let modalMode = $state('create');
  let formData = $state({ ContactID: null, NameFirst: '', NameLast: '', Title: '', Initial: '', Specialty: '' });
  let deleteConfirmOpen = $state(false);
  let deleteItem = $state(null);

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

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

  const filteredContacts = $derived.by(() => {
    if (!searchQuery.trim()) return contacts;
    const query = searchQuery.toLowerCase().trim();
    return contacts.filter(contact => {
      const fullName = `${contact.NameFirst || ''} ${contact.NameLast || ''}`.trim().toLowerCase();
      const initial = (contact.Initial || '').toLowerCase();
      return fullName.includes(query) || initial.includes(query);
    });
  });

  const columns = [
    { key: 'Initial', label: 'Initial', class: 'font-medium w-24' },
    { key: 'FullName', label: 'Full Name' },
    { key: 'Title', label: 'Title', class: 'w-32' },
    { key: 'SpecialtyLabel', label: 'Specialty' },
    { key: 'actions', label: 'Actions', class: 'w-32 text-center' },
  ];

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

  async function loadSpecialties() {
    try {
      const response = await fetchSpecialties();
      specialties = Array.isArray(response.data) ? response.data : [];
    } catch (err) {
      console.error('Failed to load specialties:', err);
      specialties = [];
    }
  }

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

  function openCreateModal() {
    modalMode = 'create';
    formData = { ContactID: null, NameFirst: '', NameLast: '', Title: '', Initial: '', Specialty: '' };
    modalOpen = true;
  }

  function openEditModal(row) {
    modalMode = 'edit';
    formData = {
      ContactID: row.ContactID,
      NameFirst: row.NameFirst || '',
      NameLast: row.NameLast || '',
      Title: row.Title || '',
      Initial: row.Initial || '',
      Specialty: row.Specialty || '',
    };
    modalOpen = true;
  }

  function validateForm() {
    const initial = (formData.Initial || '').trim().toUpperCase();
    
    // Check for duplicate initials (excluding current contact when editing)
    const duplicate = contacts.find(c => 
      c.Initial?.toUpperCase() === initial && 
      c.ContactID !== formData.ContactID
    );
    
    if (duplicate) {
      toastError(`Initial "${initial}" is already used by "${duplicate.NameFirst} ${duplicate.NameLast}". Please choose a different initial.`);
      return false;
    }
    
    return true;
  }

  async function handleSave() {
    if (!validateForm()) return;
    
    saving = true;
    try {
      // Normalize the initial to uppercase before saving
      const dataToSave = {
        ...formData,
        Initial: (formData.Initial || '').trim().toUpperCase()
      };
      
      if (modalMode === 'create') {
        await createContact(dataToSave);
        toastSuccess('Contact created successfully');
      } else {
        await updateContact(dataToSave.ContactID, dataToSave);
        toastSuccess('Contact updated successfully');
      }
      modalOpen = false;
      await loadContacts();
    } catch (err) {
      toastError(err.message || 'Failed to save contact');
    } finally {
      saving = false;
    }
  }

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

  async function handleDelete() {
    deleting = true;
    try {
      await deleteContact(deleteItem.ContactID);
      toastSuccess('Contact deleted successfully');
      deleteConfirmOpen = false;
      await loadContacts();
    } catch (err) {
      toastError(err.message || 'Failed to delete contact');
    } finally {
      deleting = false;
    }
  }

  function getDisplayName(contact) {
    const firstName = contact.NameFirst?.trim();
    const lastName = contact.NameLast?.trim();
    if (firstName && lastName) {
      return `${firstName} ${lastName}`;
    }
    return firstName || lastName || 'Unnamed Contact';
  }
</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">Contacts</h1>
      <p class="text-sm text-gray-600">Manage physicians and contacts</p>
    </div>
    <button class="btn btn-primary" onclick={openCreateModal}>
      <Plus class="w-4 h-4 mr-2" />
      Add Contact
    </button>
  </div>

  <!-- Search Bar -->
  <div class="mb-4">
    <div class="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 name or initial..."
          bind:value={searchQuery}
        />
        {#if searchQuery}
          <button 
            class="btn btn-ghost btn-xs btn-circle"
            onclick={() => searchQuery = ''}
          >
            ×
          </button>
        {/if}
      </label>
    </div>
  </div>

  <div class="bg-base-100 rounded-lg shadow border border-base-200">
    {#if loading}
      <div class="flex items-center justify-center py-16">
        <Loader2 class="w-8 h-8 animate-spin text-primary mr-3" />
        <span class="text-gray-600">Loading contacts...</span>
      </div>
    {:else if filteredContacts.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">
          <Users class="w-12 h-12 text-gray-400" />
        </div>
        <h3 class="text-base font-semibold text-gray-700 mb-1">
          {searchQuery ? 'No contacts found' : 'No contacts yet'}
        </h3>
        <p class="text-xs text-gray-500 text-center max-w-sm mb-4">
          {searchQuery 
            ? `No contacts matching "${searchQuery}". Try a different search term.` 
            : 'Get started by adding your first physician or contact.'}
        </p>
        {#if !searchQuery}
          <button class="btn btn-primary" onclick={openCreateModal}>
            <Plus class="w-4 h-4 mr-2" />
            Add First Contact
          </button>
        {/if}
      </div>
    {:else}
      <DataTable
        {columns}
        data={filteredContacts.map((c) => ({
          ...c,
          FullName: getDisplayName(c),
          SpecialtyLabel: specialtyMap[c.Specialty] || '-',
        }))}
        loading={false}
        emptyMessage="No contacts 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 contact">
                <Edit2 class="w-4 h-4" />
              </button>
              <button class="btn btn-sm btn-ghost text-error" onclick={() => confirmDelete(row)} title="Delete contact">
                <Trash2 class="w-4 h-4" />
              </button>
            </div>
          {:else}
            {value}
          {/if}
        {/snippet}
      </DataTable>
    {/if}
  </div>
</div>

<Modal bind:open={modalOpen} title={modalMode === 'create' ? 'Add Contact' : 'Edit Contact'} 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="initial">
          <span class="label-text text-sm font-medium flex items-center gap-2">
            Initial
            <HelpTooltip 
              text="A unique short code used to identify this doctor (e.g., 'JS' for John Smith). This will be used in reports and quick reference." 
              title="Doctor's Short Code"
              position="right"
            />
          </span>
          <span class="label-text-alt text-xs text-error">*</span>
        </label>
        <input
          id="initial"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.Initial}
          placeholder="e.g., JS, AB, MK"
          maxlength="10"
          required
        />
        <label class="label" for="initial">
          <span class="label-text-alt text-xs text-gray-500">Unique identifier for this doctor</span>
        </label>
      </div>
      <div class="form-control">
        <label class="label" for="title">
          <span class="label-text text-sm font-medium">Title</span>
        </label>
        <input
          id="title"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.Title}
          placeholder="e.g., Dr., Prof., Mr., Ms."
        />
      </div>
    </div>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div class="form-control">
        <label class="label" for="nameFirst">
          <span class="label-text text-sm font-medium">First Name</span>
        </label>
        <input
          id="nameFirst"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.NameFirst}
          placeholder="Enter first name"
        />
      </div>
      <div class="form-control">
        <label class="label" for="nameLast">
          <span class="label-text text-sm font-medium">Last Name</span>
        </label>
        <input
          id="nameLast"
          type="text"
          class="input input-sm input-bordered w-full"
          bind:value={formData.NameLast}
          placeholder="Enter last name"
        />
      </div>
    </div>
    <SelectDropdown
      label="Specialty"
      name="specialty"
      bind:value={formData.Specialty}
      options={specialtyOptions}
      placeholder="Select a medical specialty..."
    />
  </form>
  {#snippet footer()}
    <button class="btn btn-ghost" onclick={() => (modalOpen = false)} 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>

<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">{getDisplayName(deleteItem || {})}</strong>?
    </p>
    {#if deleteItem?.Initial}
      <p class="text-sm text-gray-500 mt-1">Initial: {deleteItem.Initial}</p>
    {/if}
    <p class="text-sm text-error mt-3">This action cannot be undone.</p>
  </div>
  {#snippet footer()}
    <button class="btn btn-ghost" onclick={() => (deleteConfirmOpen = false)} type="button" disabled={deleting}>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>
