<template>
  <div class="max-w-4xl mx-auto space-y-6">
    <!-- Section Header with Export Controls -->
    <div class="flex items-center justify-between mb-8">
      <div>
        <h3 class="text-2xl font-black text-black mb-2">Who's on your team?</h3>
        <p class="text-neutral-600">
          Add everyone who'll be working in the co-op, even if they're not ready
          to be paid yet.
        </p>
      </div>
      <div class="flex items-center gap-3">
        <UButton
          variant="outline"
          color="gray"
          size="sm"
          @click="exportMembers">
          <UIcon name="i-heroicons-arrow-down-tray" class="mr-1" />
          Export
        </UButton>
        <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">
          Get started by adding your first team member.
        </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">
        <!-- Header row with name and coverage chip -->
        <div class="flex items-center justify-between mb-4">
          <div class="flex items-center gap-3">
            <UInput
              v-model="member.displayName"
              placeholder="Member name"
              size="lg"
              class="text-lg font-bold w-48"
              @update:model-value="saveMember(member)"
              @blur="saveMember(member)" />
            <CoverageChip
              :coverage-min-pct="memberCoverage(member).minPct"
              :coverage-target-pct="memberCoverage(member).targetPct"
              :member-name="member.displayName || 'This member'"
            />
          </div>
          <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>
        
        <!-- Compact grid for pay and hours -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-3 mb-3">
          <UFormField label="Pay relationship" required>
            <USelect
              v-model="member.payRelationship"
              :items="payRelationshipOptions"
              size="md"
              class="text-sm 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="md"
              class="text-sm font-medium w-full"
              @update:model-value="validateAndSaveHours($event, member)"
              @blur="saveMember(member)" />
          </UFormField>
          
          <UFormField label="Role (optional)">
            <UInput
              v-model="member.role"
              placeholder="Developer"
              size="md"
              class="text-sm font-medium w-full"
              @update:model-value="saveMember(member)"
              @blur="saveMember(member)" />
          </UFormField>
        </div>

        <!-- Compact needs section -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-3 p-3 bg-gray-50 rounded-lg">
          <div>
            <label class="text-xs font-medium text-gray-600 mb-1 block">Minimum needs (€/mo)</label>
            <UInput
              v-model="member.minMonthlyNeeds"
              type="text"
              placeholder="2000"
              size="sm"
              class="text-sm font-medium w-full"
              @update:model-value="validateAndSaveAmount($event, member, 'minMonthlyNeeds')"
              @blur="saveMember(member)" />
          </div>

          <div>
            <label class="text-xs font-medium text-gray-600 mb-1 block">Target pay (€/mo)</label>
            <UInput
              v-model="member.targetMonthlyPay"
              type="text"
              placeholder="3500"
              size="sm"
              class="text-sm font-medium w-full"
              @update:model-value="validateAndSaveAmount($event, member, 'targetMonthlyPay')"
              @blur="saveMember(member)" />
          </div>

          <div>
            <label class="text-xs font-medium text-gray-600 mb-1 block">External income (€/mo)</label>
            <UInput
              v-model="member.externalMonthlyIncome"
              type="text"
              placeholder="1500"
              size="sm"
              class="text-sm font-medium w-full"
              @update:model-value="validateAndSaveAmount($event, member, 'externalMonthlyIncome')"
              @blur="saveMember(member)" />
          </div>
        </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 { coverage } from "~/types/members";

const emit = defineEmits<{
  "save-status": [status: "saving" | "saved" | "error"];
}>();

// Store
const coop = useCoopBuilder();
const members = computed(() => 
  coop.members.value.map(m => ({
    // Map store fields to component expectations
    id: m.id,
    displayName: m.name,
    role: m.role || '',
    capacity: {
      targetHours: m.hoursPerMonth || 0
    },
    payRelationship: 'FullyPaid', // Default since not in store yet
    minMonthlyNeeds: m.minMonthlyNeeds || 0,
    targetMonthlyPay: m.targetMonthlyPay || 0,
    externalMonthlyIncome: m.externalMonthlyIncome || 0,
    monthlyPayPlanned: m.monthlyPayPlanned || 0
  }))
);

// 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 {
    // Convert component format back to store format
    const memberData = {
      id: member.id,
      name: member.displayName || '',
      role: member.role || '',
      hoursPerMonth: member.capacity?.targetHours || 0,
      minMonthlyNeeds: member.minMonthlyNeeds || 0,
      targetMonthlyPay: member.targetMonthlyPay || 0,
      externalMonthlyIncome: member.externalMonthlyIncome || 0,
      monthlyPayPlanned: member.monthlyPayPlanned || 0,
    };
    
    coop.upsertMember(memberData);
    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 validateAndSaveAmount(value: string, member: any, field: string) {
  const numValue = parseFloat(value.replace(/[^\d.]/g, ""));
  member[field] = isNaN(numValue) ? 0 : Math.max(0, numValue);
  saveMember(member);
}

function memberCoverage(member: any) {
  return coverage(
    member.minMonthlyNeeds || 0,
    member.targetMonthlyPay || 0,
    member.monthlyPayPlanned || 0,
    member.externalMonthlyIncome || 0
  );
}

function addMember() {
  const newMember = {
    id: Date.now().toString(),
    name: "",
    role: "",
    hoursPerMonth: 0,
    minMonthlyNeeds: 0,
    targetMonthlyPay: 0,
    externalMonthlyIncome: 0,
    monthlyPayPlanned: 0,
  };

  coop.upsertMember(newMember);
}

function removeMember(id: string) {
  coop.removeMember(id);
}

function exportMembers() {
  const exportData = {
    members: members.value,
    exportedAt: new Date().toISOString(),
    section: "members",
  };

  const blob = new Blob([JSON.stringify(exportData, null, 2)], {
    type: "application/json",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `coop-members-${new Date().toISOString().split("T")[0]}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}
</script>
