<template>
  <section class="mt-8">
    <div class="overflow-hidden bg-white">
      <div class="grid grid-cols-4 border border-black bg-tertiary-500 px-6 py-3 text-[20px] font-semibold text-black rounded-t-md">
        <p>Contrat</p>
        <p>Heures</p>
        <p>Date de début</p>
        <p>Date de fin</p>
      </div>
      <div v-if="contractHistory.length === 0" class="px-6 py-4 text-md text-neutral-600">
        Aucun historique de contrat.
      </div>
      <div v-else class="border-x border-b border-primary-500 rounded-b-md">
        <div
          v-for="item in contractHistory"
          :key="`${item.startDate}-${item.endDate ?? 'open'}-${item.contractId ?? item.contractName}`"
          class="grid grid-cols-4 border-b border-primary-500 px-6 py-3 text-md font-bold text-primary-500 last:border-b-0 hover:bg-tertiary-500"
        >
          <p>{{ item.interimAgencyName ? `${contractNatureLabel(item.contractNature)} (${item.interimAgencyName})` : contractNatureLabel(item.contractNature) }}</p>
          <p>{{ contractHistoryLabel(item) }}</p>
          <p>{{ formatDate(item.startDate) }}</p>
          <p>{{ formatDate(item.endDate) }}</p>
        </div>
      </div>
    </div>

    <div class="mt-8 flex justify-center gap-12">
      <button
        type="button"
        class="w-[200px] rounded-md bg-blue-500 py-2 text-white disabled:cursor-not-allowed disabled:opacity-50"
        :disabled="isContractSubmitting || !canCloseCurrentContract"
        @click="onOpenCloseContractDrawer"
      >
        Modifier
      </button>
      <button
        type="button"
        class="flex w-[200px] items-center justify-center gap-2 rounded-md bg-primary-500 px-4 py-2 text-md text-white disabled:cursor-not-allowed disabled:opacity-50"
        :disabled="isCreateContractSubmitting || contracts.length === 0 || !canCreateContract"
        @click="onOpenCreateContractDrawer"
      >
        + Ajouter
      </button>
    </div>

    <MalioDrawer :model-value="isContractDrawerOpen" @update:model-value="onUpdateContractDrawerOpen">
      <template #header>
          <h2 class="text-[32px] font-semibold text-primary-500">Modifier le contrat</h2>
      </template>
      <div class="mb-4 flex border-b border-neutral-200">
          <button
              type="button"
              class="pb-2 px-4 border-b-2 font-semibold"
              :class="drawerTab === 'close'
                  ? 'border-primary-500 text-primary-500'
                  : 'border-transparent text-primary-500/50 hover:text-primary-500'"
              @click="drawerTab = 'close'"
          >
              Clôturer
          </button>
          <button
              type="button"
              class="pb-2 px-4 border-b-2 font-semibold"
              :class="drawerTab === 'suspend'
                  ? 'border-primary-500 text-primary-500'
                  : 'border-transparent text-primary-500/50 hover:text-primary-500'"
              @click="drawerTab = 'suspend'"
          >
              Suspendre
          </button>
      </div>
      <div v-if="drawerTab === 'close'">
      <form class="space-y-4" @submit.prevent="onSubmitCloseContract">
        <div>
          <label class="text-md font-semibold text-neutral-700" for="contract-nature">
            Type de contrat
          </label>
          <input id="contract-nature" :value="contractNatureLabel(contractForm.contractNature)" type="text" :class="readonlyFieldClass" readonly />
        </div>

        <div>
          <label class="text-md font-semibold text-neutral-700" for="contract">
            Temps de travail
          </label>
          <input id="contract" :value="closeContractWorkedHoursLabel" type="text" :class="readonlyFieldClass" readonly />
        </div>

        <div>
          <label class="text-md font-semibold text-neutral-700" for="contract-start-date">
            Début contrat
          </label>
          <input
            id="contract-start-date"
            :value="contractForm.startDate"
            type="date"
            :class="readonlyFieldClass"
            readonly
          />
        </div>

        <div>
          <label class="text-md font-semibold text-neutral-700" for="contract-end-date">
            Fin contrat <span class="text-red-600">*</span>
          </label>
          <input
            id="contract-end-date"
            v-model="contractForm.endDate"
            type="date"
            :class="contractEndDateFieldClass"
          />
          <p v-if="showContractEndDateError" class="mt-1 text-sm text-red-600">La date de fin est obligatoire.</p>
        </div>

        <WorkDaysHoursInput
          v-if="contractForm.workDaysHours"
          :model-value="contractForm.workDaysHours"
          :contract-weekly-hours="contractForm.weeklyHours ?? null"
          disabled
        />

        <div>
          <label class="text-md font-semibold text-neutral-700" for="contract-comment">
            Commentaire
          </label>
          <textarea
            id="contract-comment"
            v-model="contractForm.comment"
            rows="3"
            class="mt-2 w-full rounded-md border border-neutral-300 px-3 py-2 text-base text-neutral-900 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-secondary-500/20"
            placeholder="Motif de la clôture..."
          />
        </div>

        <div class="rounded-md border border-neutral-200 bg-neutral-50 p-3">
          <label class="inline-flex items-center gap-2 text-md font-semibold text-neutral-700" for="contract-paid-leave-settled">
            <input
              id="contract-paid-leave-settled"
              v-model="contractForm.paidLeaveSettled"
              type="checkbox"
              class="h-4 w-4 rounded border-neutral-300 text-primary-500 focus:ring-primary-500"
            />
            Soldé dans le solde de tout compte
          </label>
        </div>

        <div class="flex justify-center pt-2">
          <MalioButton
            label="Modifier"
            button-class="w-[200px]"
            :disabled="isContractSubmitting || !isContractEndDateValid"
            @click="onSubmitCloseContract"
          />
        </div>
      </form>
      </div>

      <div v-if="drawerTab === 'suspend'" class="space-y-6">
          <div
              v-for="(form, index) in suspensionForms"
              :key="form.id ?? `new-${index}`"
              class="space-y-4 rounded-lg border border-neutral-200 p-4"
          >
              <div>
                  <label class="text-md font-semibold text-neutral-700">
                      Date de début <span class="text-red-600">*</span>
                  </label>
                  <input
                      v-model="form.startDate"
                      type="date"
                      class="mt-2 w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-base text-neutral-900 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-secondary-500/20"
                  />
              </div>
              <div>
                  <label class="text-md font-semibold text-neutral-700">
                      Date de fin
                  </label>
                  <input
                      v-model="form.endDate"
                      type="date"
                      class="mt-2 w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-base text-neutral-900 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-secondary-500/20"
                  />
              </div>
              <div>
                  <label class="text-md font-semibold text-neutral-700">
                      Commentaire
                  </label>
                  <textarea
                      v-model="form.comment"
                      rows="3"
                      class="mt-2 w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-base text-neutral-900 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-secondary-500/20"
                  />
              </div>
              <MalioButton
                  :label="form.id ? 'Modifier' : 'Ajouter'"
                  button-class="w-full"
                  :disabled="!form.startDate || isSuspensionSubmitting"
                  @click="onSubmitSuspension(index)"
              />
          </div>

          <MalioButton
              label="Ajouter une suspension"
              icon-name="mdi:plus"
              icon-position="left"
              variant="tertiary"
              button-class="w-full"
              @click="onAddSuspensionForm"
          />
      </div>
    </MalioDrawer>

    <MalioDrawer :model-value="isCreateContractDrawerOpen" @update:model-value="onUpdateCreateContractDrawerOpen">
      <template #header>
          <h2 class="text-[32px] font-semibold text-primary-500">Ajouter un contrat</h2>
      </template>
      <form class="space-y-4" @submit.prevent="onSubmitCreateContract">
        <div>
          <label class="text-md font-semibold text-neutral-700" for="create-contract-nature">
            Type de contrat <span class="text-red-600">*</span>
          </label>
          <select id="create-contract-nature" v-model="createContractForm.contractNature" :class="createContractNatureFieldClass">
            <option value="CDI">CDI</option>
            <option value="CDD">CDD</option>
            <option value="INTERIM">Intérim</option>
          </select>
        </div>

        <div v-if="createContractForm.contractNature === 'INTERIM'">
          <label class="text-md font-semibold text-neutral-700" for="create-interim-agency">
            Agence d'intérim
          </label>
          <select
            id="create-interim-agency"
            v-model="createContractForm.interimAgencyId"
            class="mt-2 w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-md text-neutral-900"
          >
            <option value="">Aucune</option>
            <option v-for="agency in interimAgencies" :key="agency.id" :value="agency.id">
              {{ agency.name }}
            </option>
          </select>
        </div>

        <div>
          <label class="text-md font-semibold text-neutral-700" for="create-contract-id">
            Temps de travail <span class="text-red-600">*</span>
          </label>
          <select id="create-contract-id" v-model="createContractForm.contractId" :class="createContractFieldClass">
            <option value="">Sélectionner un contrat</option>
            <option v-for="contract in contracts" :key="contract.id" :value="contract.id">
              {{ contract.name }}
            </option>
          </select>
        </div>

        <div>
          <label class="text-md font-semibold text-neutral-700" for="create-contract-start-date">
            Début contrat <span class="text-red-600">*</span>
          </label>
          <input id="create-contract-start-date" v-model="createContractForm.startDate" type="date" :class="createContractStartDateFieldClass" />
        </div>

        <div v-if="showsCreateContractEndDate">
          <label class="text-md font-semibold text-neutral-700" for="create-contract-end-date">
            Fin contrat <span v-if="requiresCreateContractEndDate" class="text-red-600">*</span>
          </label>
          <input id="create-contract-end-date" v-model="createContractForm.endDate" type="date" :class="createContractEndDateFieldClass" />
        </div>

        <div class="rounded-md border border-neutral-200 bg-neutral-50 p-3">
          <label class="inline-flex items-center gap-2 text-md font-semibold text-neutral-700" for="create-contract-is-driver">
            <input
              id="create-contract-is-driver"
              v-model="createContractForm.isDriver"
              type="checkbox"
              class="h-4 w-4 rounded border-neutral-300 text-primary-500 focus:ring-primary-500"
            />
            Chauffeur
          </label>
        </div>

        <WorkDaysHoursInput
          v-if="requiresCreateWorkDaysHours"
          v-model="createContractForm.workDaysHours"
          :contract-weekly-hours="selectedCreateContract?.weeklyHours ?? null"
        />

        <div class="sticky bottom-0 -mx-[20px] bg-white px-[20px] py-3 flex justify-center">
          <MalioButton
            label="Ajouter"
            icon-name="mdi:plus"
            icon-position="left"
            button-class="w-[200px]"
            :disabled="isCreateContractSubmitting || !isCreateContractFormValid"
            @click="onSubmitCreateContract"
          />
        </div>
      </form>
    </MalioDrawer>
  </section>
</template>

<script setup lang="ts">
import type { Contract } from '~/services/dto/contract'
import type { ContractHistoryItem } from '~/services/dto/employee'
import type { InterimAgency } from '~/services/interim-agencies'
import WorkDaysHoursInput from '~/components/employees/WorkDaysHoursInput.vue'

type SuspensionForm = {
  id: number | null
  startDate: string
  endDate: string
  comment: string
}

type ContractForm = {
  contractId: number | ''
  contractName: string
  weeklyHours: number | null
  contractNature: 'CDI' | 'CDD' | 'INTERIM'
  startDate: string
  endDate: string
  paidLeaveSettled: boolean
  comment: string
  workDaysHours: Record<number, number> | null
}

type CreateContractForm = {
  contractId: number | ''
  contractNature: 'CDI' | 'CDD' | 'INTERIM'
  startDate: string
  endDate: string
  isDriver: boolean
  workDaysHours: Record<number, number> | null
  interimAgencyId: number | ''
}

const props = defineProps<{
  contractHistory: ContractHistoryItem[]
  contractNatureLabel: (value?: 'CDI' | 'CDD' | 'INTERIM') => string
  contractHistoryLabel: (item: ContractHistoryItem) => string
  formatDate: (value?: string | null) => string
  isContractSubmitting: boolean
  canCloseCurrentContract: boolean
  isCreateContractSubmitting: boolean
  contracts: Contract[]
  canCreateContract: boolean
  isContractDrawerOpen: boolean
  contractForm: ContractForm
  readonlyFieldClass: string
  closeContractWorkedHoursLabel: string
  contractEndDateFieldClass: string
  showContractEndDateError: boolean
  isContractEndDateValid: boolean
  isCreateContractDrawerOpen: boolean
  createContractForm: CreateContractForm
  createContractNatureFieldClass: string
  createContractFieldClass: string
  createContractStartDateFieldClass: string
  showsCreateContractEndDate: boolean
  requiresCreateContractEndDate: boolean
  createContractEndDateFieldClass: string
  isCreateContractFormValid: boolean
  requiresCreateWorkDaysHours: boolean
  selectedCreateContract: Contract | null
  onOpenCloseContractDrawer: () => void
  onOpenCreateContractDrawer: () => void
  onUpdateContractDrawerOpen: (open: boolean) => void
  onUpdateCreateContractDrawerOpen: (open: boolean) => void
  onSubmitCloseContract: () => void
  onSubmitCreateContract: () => void
  suspensionForms: SuspensionForm[]
  isSuspensionSubmitting: boolean
  onSubmitSuspension: (index: number) => void
  onAddSuspensionForm: () => void
  currentContractPeriodId?: number | null
  interimAgencies: InterimAgency[]
}>()

const drawerTab = ref<'close' | 'suspend'>('close')

watch(() => props.isContractDrawerOpen, (open) => {
  if (open) drawerTab.value = 'close'
})
</script>
