<template>
  <div class="space-y-4">
    <div>
      <div class="flex items-center justify-between mb-6">
        <h3 class="text-2xl font-black text-black">Who's on your team?</h3>
        <UButton
          v-if="members.length > 0"
          @click="addMember"
          size="sm"
          variant="solid"
          color="success"
          :ui="{
            base: 'cursor-pointer hover:scale-105 transition-transform',
            leadingIcon: 'hover:rotate-90 transition-transform',
          }">
          <UIcon name="i-heroicons-plus" class="mr-1" />
          Add member
        </UButton>
      </div>
    </div>

    <!-- Members List -->
    <div class="space-y-3">
      <div
        v-if="members.length === 0"
        class="text-center py-12 border-4 border-dashed border-black rounded-xl bg-white shadow-lg">
        <h4 class="font-medium text-neutral-900 mb-2">No team members yet</h4>
        <p class="text-sm text-neutral-500 mb-4">
          Add everyone who'll be working in the co-op, even if they're not ready
          to be paid yet.
        </p>
        <UButton @click="addMember" size="lg" variant="solid" color="primary">
          <UIcon name="i-heroicons-plus" class="mr-2" />
          Add your first member
        </UButton>
      </div>

      <div
        v-for="(member, index) in members"
        :key="member.id"
        class="p-6 border-3 border-black rounded-xl bg-white shadow-md">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <UFormField label="Name" required class="md:col-span-2">
            <UInput
              v-model="member.displayName"
              placeholder="Alex Chen"
              size="xl"
              class="text-lg font-medium w-full"
              @update:model-value="saveMember(member)"
              @blur="saveMember(member)" />
          </UFormField>

          <UFormField label="Pay relationship" required>
            <USelect
              v-model="member.payRelationship"
              :items="payRelationshipOptions"
              size="xl"
              class="text-lg font-medium w-full"
              @update:model-value="saveMember(member)" />
          </UFormField>

          <UFormField label="Hours/month" required>
            <UInput
              v-model="member.capacity.targetHours"
              type="text"
              placeholder="120"
              size="xl"
              class="text-xl font-bold w-full"
              @update:model-value="validateAndSaveHours($event, member)"
              @blur="saveMember(member)" />
          </UFormField>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-3">
          <UFormField label="External income coverage %" class="md:col-span-1">
            <UInput
              v-model="member.externalCoveragePct"
              type="text"
              placeholder="50"
              size="xl"
              class="text-lg font-medium w-full"
              @update:model-value="validateAndSavePercentage($event, member)"
              @blur="saveMember(member)" />
            <template #help>
              <span class="text-xs text-neutral-500"
                >% of needs covered by other income</span
              >
            </template>
          </UFormField>
        </div>

        <!-- Actions -->
        <div class="flex justify-end mt-6 pt-6 border-t-3 border-black">
          <UButton
            size="xs"
            variant="solid"
            color="error"
            @click="removeMember(member.id)"
            :ui="{
              base: 'cursor-pointer hover:opacity-90 transition-opacity',
            }">
            <UIcon name="i-heroicons-trash" class="w-4 h-4" />
          </UButton>
        </div>
      </div>

      <!-- Add Member -->
      <div v-if="members.length > 0" class="flex justify-center">
        <UButton
          @click="addMember"
          size="lg"
          variant="solid"
          color="success"
          :ui="{
            base: 'cursor-pointer hover:scale-105 transition-transform',
            leadingIcon: 'hover:rotate-90 transition-transform',
          }">
          <UIcon name="i-heroicons-plus" class="mr-2" />
          Add another member
        </UButton>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useDebounceFn } from "@vueuse/core";
import { storeToRefs } from "pinia";
const emit = defineEmits<{
  "save-status": [status: "saving" | "saved" | "error"];
}>();

// Store
const membersStore = useMembersStore();
const { members } = storeToRefs(membersStore);

// Options
const payRelationshipOptions = [
  { label: "Fully Paid", value: "FullyPaid" },
  { label: "Hybrid", value: "Hybrid" },
  { label: "Supplemental", value: "Supplemental" },
  { label: "Volunteer/Deferred", value: "VolunteerOrDeferred" },
];

const riskBandOptions = [
  { label: "Low Risk", value: "Low" },
  { label: "Medium Risk", value: "Medium" },
  { label: "High Risk", value: "High" },
];

// Computeds
const totalTargetHours = computed(() =>
  members.value.reduce((sum, m) => sum + (m.capacity?.targetHours || 0), 0)
);

const avgExternalCoverage = computed(() => {
  if (members.value.length === 0) return 0;
  const total = members.value.reduce(
    (sum, m) => sum + (m.externalCoveragePct || 0),
    0
  );
  return Math.round(total / members.value.length);
});

// Live-write with debounce
const debouncedSave = useDebounceFn((member: any) => {
  emit("save-status", "saving");

  try {
    membersStore.upsertMember(member);
    emit("save-status", "saved");
  } catch (error) {
    console.error("Failed to save member:", error);
    emit("save-status", "error");
  }
}, 300);

function saveMember(member: any) {
  debouncedSave(member);
}

// Validation functions
function validateAndSaveHours(value: string, member: any) {
  const numValue = parseFloat(value.replace(/[^\d.]/g, ""));
  member.capacity.targetHours = isNaN(numValue) ? 0 : Math.max(0, numValue);
  saveMember(member);
}

function validateAndSavePercentage(value: string, member: any) {
  const numValue = parseFloat(value.replace(/[^\d.]/g, ""));
  member.externalCoveragePct = isNaN(numValue)
    ? 0
    : Math.min(100, Math.max(0, numValue));
  saveMember(member);
}

function addMember() {
  const newMember = {
    id: Date.now().toString(),
    displayName: "",
    roleFocus: "", // Hidden but kept for compatibility
    payRelationship: "FullyPaid",
    capacity: {
      minHours: 0,
      targetHours: 0,
      maxHours: 0,
    },
    riskBand: "Medium", // Hidden but kept with default
    externalCoveragePct: 50,
    privacyNeeds: "aggregate_ok",
    deferredHours: 0,
    quarterlyDeferredCap: 240,
  };

  membersStore.upsertMember(newMember);
}

function removeMember(id: string) {
  membersStore.removeMember(id);
}
</script>
