<script lang="ts">
  import { onMount } from "svelte";
  import { supabase } from "$lib/supabaseClient";
  import logo from "$lib/images/logo.webp";

  type POItem = {
    id: string;
    item_name: string;
  };

  type Villa = {
    id: string;
    name: string;
  };

  type Employee = {
    id: string;
    name: string;
  };

  let poItemOptions: POItem[] = [];
  let villas: Villa[] = [];
  let employees: Employee[] = [];

  let addPOForm = {
    po_type: "",
    villa_id: "",
    po_item: "",
    po_quantity: 0,
    po_remark: "",
    requested_by: "",
    requested_date: ""
  };

  onMount(async () => {
    // Fetch villas
    const { data: villaData, error: villaError } = await supabase
      .from("vb_villas")
      .select("id, villa_name, villa_status")
      .eq("villa_status", "Active")
      .order("villa_name", { ascending: true });

    if (villaError) {
      console.error("Failed to fetch villas:", villaError.message);
    } else if (villaData) {
      villas = villaData.map((v) => ({ id: v.id, name: v.villa_name }));
    }

    // Fetch employees
    const { data: empData, error: empError } = await supabase
      .from("vb_employee")
      .select("id, employee_name")
      .eq("employee_status", "Active")
      .order("employee_name", { ascending: true });

    if (empError) {
      console.error("Failed to fetch employees:", empError.message);
    } else if (empData) {
      employees = empData.map((e) => ({ id: e.id, name: e.employee_name }));
    }

    // Fetch PO Items
    const { data: poItemData, error: poItemError } = await supabase
      .from("vb_po_item")
      .select("id, item_name")
      .order("item_name", { ascending: true });

    if (poItemError) {
      console.error("Failed to fetch PO items:", poItemError.message);
    } else if (poItemData) {
      poItemOptions = poItemData;
    }
  });

  async function submitForm() {
    if (!addPOForm.requested_by) {
      alert("Please select an employee.");
      return;
    }
    if (!addPOForm.villa_id) {
      alert("Please select a villa.");
      return;
    }
    if (!addPOForm.po_item) {
      alert("Please select a PO item.");
      return;
    }

    const { error } = await supabase.from("vb_purchase_orders").insert({
      po_type: addPOForm.po_type,
      villa_id: addPOForm.villa_id,
      po_item: addPOForm.po_item,
      po_quantity: addPOForm.po_quantity,
      po_status: "requested",
      po_remark: addPOForm.po_remark,
      requested_by: addPOForm.requested_by,
      requested_date: addPOForm.requested_date,
      created_at: new Date().toISOString()
    });

    if (error) {
      alert("Failed to submit Purchase Order: " + error.message);
    } else {
      alert("Purchase Order submitted successfully!");
      addPOForm = {
        po_type: "",
        villa_id: "",
        po_item: "",
        po_quantity: 0,
        po_remark: "",
        requested_by: "",
        requested_date: ""
      };
    }
  }
</script>

<div class="min-h-screen bg-gray-100 flex items-center justify-center">
  <form
    on:submit|preventDefault={submitForm}
    class="w-full max-w-lg bg-white p-6 rounded-2xl shadow-xl space-y-4"
  >
    <img src={logo} alt="Villa Logo" class="mx-auto mb-6" width="250" />

    <h2 class="text-2xl font-bold text-center mb-6">Purchase Order Entry</h2>

    <div>
        <label>PO Type</label>
        <select bind:value={addPOForm.po_type} class="w-full border p-2">
          <option value="" disabled>Select PO Type</option>
          <option value="purchase">Purchase</option>
          <option value="project">Project</option>
          <option value="repair">Repair</option>
        </select>
    </div>

    <div>
        <label>Villa</label>
        <select bind:value={addPOForm.villa_id} class="w-full border p-2">
          <option value="" disabled>Select Villa</option>
            {#each villas as v}
            <option value={v.id}>{v.name}</option>        
          {/each}
        </select>
    </div>

    <div>
      <label>PO Item</label>
        <select bind:value={addPOForm.po_item} class="w-full border p-2">
          <option value="" disabled>Select Item</option>
          {#each poItemOptions as item}
            <option value={item.item_name}>{item.item_name}</option>
          {/each}
        </select>
    </div>

    <div>
      <label>PO Quantity</label>
        <input type="number" bind:value={addPOForm.po_quantity} class="w-full border p-2"/>
    </div>

    <div>
      <label>PO Remark</label>
        <textarea bind:value={addPOForm.po_remark} class="w-full border p-2"></textarea>
    </div>

    <div>
      <label>Requested By</label>
        <select bind:value={addPOForm.requested_by} class="w-full border p-2">
          <option value="" disabled>Select Employee</option>
          {#each employees as e}
            <option value={e.id}>{e.name}</option>
          {/each}
        </select>
    </div>

    <div>
      <label>Requested Date</label>
        <input type="date" bind:value={addPOForm.requested_date} class="w-full border p-2"/>
    </div>
    <button
      type="submit"
      class="w-full bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition"
    >
      Submit Purchase Order
    </button>
  </form>
</div>
