<script>
  import Header from '$lib/layout/Header.svelte';
  import Tabs from '$lib/components/Tabs.svelte';
  import RegisterCpr from '$lib/components/commodities/cpr/RegisterCpr.svelte';
  import Tables from '$lib/components/Tables.svelte';
  import ContractCpr from '$lib/components/commodities/cpr/ContractCpr.svelte';
  import EmissionCpr from '$lib/components/commodities/cpr/EmissionCpr.svelte';
  import CprEditModal from '$lib/components/commodities/cpr/CprEditModal.svelte';
  import ConfirmModal from '$lib/components/ui/PopUpDelete.svelte';

  // EditModal
  let showCprEdit = false;
  let selectedRow = null;
  let editValue = {};

  // Delete confirmation
  let showDeleteConfirm = false;
  let rowToDelete = null;

  const breadcrumb = [{ label: 'Início' }, { label: 'CPR', active: true }];
  let activeTab = 4;
  const tabs = ["Contrato", "Registro", "Emissão"];

  let columns = [
    { key: "nome", label: "Nome" },
    { key: "status", label: "Status" }
  ];

  let data = [
    { nome: "CPR A", status: "Disponível" },
    { nome: "CPR B", status: "Indisponível" }
  ];

  function handleAddTop() {
    // ao clicar em "+", mudar para a aba de Registro (index 1) e exibir Tabs + Form
    activeTab = 0;
  }

  function handleDeleteRow(e) {
    const { row } = e.detail;
    rowToDelete = row;
    showDeleteConfirm = true;
  }

  function handleEditRow(e) {
    const { row } = e.detail;
    selectedRow = row;
    editValue = { ...row }; 
    showCprEdit = true;
  }

  function handleCprSave(e) {
    const { value } = e.detail;
    if (selectedRow) {
      // Atualiza a linha com os dados editados
      data = data.map((r) => (r === selectedRow ? { ...r, ...value } : r));
    }
    handleCprCancel();
  }

  function handleCprCancel() {
    showCprEdit = false;
    selectedRow = null;
    editValue = {};
  }

  function handleFinalize() {
    // Aqui você pode adicionar validação dos campos obrigatórios
    // Por enquanto, apenas volta para a tabela principal
    alert('CPR finalizado com sucesso!');
    activeTab = 4;
  }

  function handleCancel() {
    // Volta para a tabela principal cancelando o processo
    activeTab = 4;
  }

  function confirmDelete() {
    // Remove pelo objeto (referência) para manter simples no exemplo
    data = data.filter((r) => r !== rowToDelete);
    showDeleteConfirm = false;
    rowToDelete = null;
  }

  function cancelDelete() {
    showDeleteConfirm = false;
    rowToDelete = null;
  }
</script>

<div>
  <Header title="CPR - Cédula de Produto Rural" subtitle="Gestão de contratos, emissão e registro de CPRs" breadcrumb={breadcrumb} />
  <div class="p-4">
    <div class="max-w-6xl mx-auto mt-4">
    
      {#if activeTab === 4}
        <Tables
          title="CPRs"
          columns={columns}
          data={data}
          on:addTop={handleAddTop}
          on:editRow={handleEditRow}
          on:deleteRow={handleDeleteRow}
          
        />
        <CprEditModal
        visible={showCprEdit}
        title="Editar CPR"
        value={editValue}
        on:save={handleCprSave}
        on:cancel={handleCprCancel}
      />
      {:else if activeTab === 0}
      <Tabs {tabs} bind:active={activeTab} showCloseIcon={true} on:close={handleCancel} />
      <div class="mt-4">
        <ContractCpr />
      </div>
      <!-- Navigation Controls -->
      <div class="flex justify-between mt-6">
        <button 
          class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg cursor-not-allowed" 
          disabled
        >
          Anterior
        </button>
        <button 
          class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          on:click={() => activeTab = 1}
        >
          Próximo
        </button>
      </div>
      {:else if activeTab === 1}
      <Tabs {tabs} bind:active={activeTab} showCloseIcon={true} on:close={handleCancel} />
      <div class="mt-4">
        <RegisterCpr />
      </div>
      <!-- Navigation Controls -->
      <div class="flex justify-between mt-6">
        <button 
          class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600"
          on:click={() => activeTab = 0}
        >
          Anterior
        </button>
        <button 
          class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          on:click={() => activeTab = 2}
        >
          Próximo
        </button>
      </div>
      {:else if activeTab === 2}
      <Tabs {tabs} bind:active={activeTab} showCloseIcon={true} on:close={handleCancel} />
      <div class="mt-4">
        <EmissionCpr />
      </div>
      <!-- Navigation Controls -->
      <div class="flex justify-between mt-6">
        <button 
          class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600"
          on:click={() => activeTab = 1}
        >
          Anterior
        </button>
        <button 
          class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold"
          on:click={handleFinalize}
        >
          Finalizar CPR
        </button>
      </div>

      {/if}
    </div>
  </div>
</div>

<ConfirmModal
  visible={showDeleteConfirm}
  title="Confirmar exclusão"
  confirmText="Excluir"
  cancelText="Cancelar"
  on:confirm={confirmDelete}
  on:cancel={cancelDelete}
>
  <p>Tem certeza que deseja excluir a CPR "{rowToDelete?.nome}"?</p>
</ConfirmModal>
