<script setup lang="ts">
import { parseDate } from '@internationalized/date'
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  getIndustryDisplayName,
  industryTypeList,
} from '@/sql'
import { useKvStore } from '@/pinia/kv'
import { upsertProject } from '@/lib/projectRegistry'
import { readCurrentProjectId } from '@/lib/workspace'
import { waitForHydration } from '@/pinia/Plugin/indexdb'
import { Calendar as CalendarIcon, CircleHelp } from 'lucide-vue-next'
import { TooltipContent, TooltipProvider, TooltipRoot, TooltipTrigger } from '@/components/ui/tooltip'
import {
  DatePickerAnchor,
  DatePickerArrow,
  DatePickerCalendar,
  DatePickerCell,
  DatePickerCellTrigger,
  DatePickerClose,
  DatePickerContent,
  DatePickerField,
  DatePickerGrid,
  DatePickerGridBody,
  DatePickerGridHead,
  DatePickerGridRow,
  DatePickerHeadCell,
  DatePickerHeader,
  DatePickerHeading,
  DatePickerInput,
  DatePickerNext,
  DatePickerPrev,
  DatePickerRoot,
  DatePickerTrigger
} from 'reka-ui'

interface XmInfoState {
  projectIndustry?: string
  projectName?: string
  preparedBy?: string
  reviewedBy?: string
  preparedCompany?: string
  preparedDate?: string
  overview?: string
  desc?: string
}

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

const DB_KEY = 'xm-base-info-v1'
const { t, locale } = useI18n()
const DEFAULT_PROJECT_NAME = t('xmInfo.defaultProjectName')
const DEFAULT_DESC = t('xmInfo.defaultDesc')
const INDUSTRY_HINT_TEXT = computed(() => t('xmInfo.industryHint'))
const getTodayDateString = () => {
  const now = new Date()
  const year = String(now.getFullYear())
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const isProjectInitialized = ref(false)
const isBootstrapping = ref(true)

const projectName = ref('')
const projectIndustry = ref('')
const preparedBy = ref('')
const reviewedBy = ref('')
const preparedCompany = ref('')
const preparedDate = ref(getTodayDateString())
const preparedDatePickerValue = ref<any>(undefined)
const overview = ref('')
const desc = ref(DEFAULT_DESC)

const normalizeDateString = (value: unknown): string => {
  if (typeof value !== 'string') return ''
  const trimmed = value.trim()
  if (!trimmed) return ''
  try {
    const parsed = parseDate(trimmed)
    return parsed.toString() === trimmed ? trimmed : ''
  } catch {
    return ''
  }
}

const syncPreparedDatePickerFromString = () => {
  if (!preparedDate.value) {
    preparedDatePickerValue.value = undefined
    return
  }
  try {
    preparedDatePickerValue.value = parseDate(preparedDate.value)
  } catch {
    preparedDatePickerValue.value = undefined
    preparedDate.value = ''
  }
}

const handlePreparedDateSelect = (date: any) => {
  preparedDatePickerValue.value = date
  preparedDate.value = date?.toString() ?? ''
}

const majorParentNodes = computed<MajorParentNode[]>(() =>
  industryTypeList.map(item => ({
    id: item.id,
    name: getIndustryDisplayName(item.id, locale.value) || String(item.name || '')
  }))
)
const majorParentCodeSet = new Set<string>(industryTypeList.map(item => String(item.id)))
const DEFAULT_PROJECT_INDUSTRY = String(industryTypeList[0]?.id || '')
const kvStore = useKvStore()

const saveToIndexedDB = async () => {
  try {
    const normalizedProjectName = projectName.value.trim() || DEFAULT_PROJECT_NAME
    projectName.value = normalizedProjectName
    const payload: XmInfoState = {
      projectIndustry: projectIndustry.value,
      projectName: normalizedProjectName,
      preparedBy: preparedBy.value,
      reviewedBy: reviewedBy.value,
      preparedCompany: preparedCompany.value,
      preparedDate: preparedDate.value,
      overview: overview.value,
      desc: desc.value
    }
    await kvStore.setItem(DB_KEY, payload)
    upsertProject(readCurrentProjectId(), normalizedProjectName)
  } catch (error) {
    console.error('saveToIndexedDB failed:', error)
  }
}

const loadFromIndexedDB = async () => {
  try {
    const data = await kvStore.getItem<XmInfoState>(DB_KEY)
    if (data) {
      isProjectInitialized.value = true
      projectIndustry.value =
        typeof data.projectIndustry === 'string' && majorParentCodeSet.has(data.projectIndustry)
          ? data.projectIndustry
          : DEFAULT_PROJECT_INDUSTRY
      projectName.value =
        typeof data.projectName === 'string' && data.projectName.trim() ? data.projectName : DEFAULT_PROJECT_NAME
      preparedBy.value = typeof data.preparedBy === 'string' ? data.preparedBy : ''
      reviewedBy.value = typeof data.reviewedBy === 'string' ? data.reviewedBy : ''
      preparedCompany.value = typeof data.preparedCompany === 'string' ? data.preparedCompany : ''
      preparedDate.value = normalizeDateString(data.preparedDate) || getTodayDateString()
      overview.value = typeof data.overview === 'string' ? data.overview : ''
      desc.value = typeof data.desc === 'string' && data.desc.trim() ? data.desc : DEFAULT_DESC
      syncPreparedDatePickerFromString()
      return
    }

    isProjectInitialized.value = false
    projectIndustry.value = DEFAULT_PROJECT_INDUSTRY
    projectName.value = DEFAULT_PROJECT_NAME
    preparedBy.value = ''
    reviewedBy.value = ''
    preparedCompany.value = ''
    preparedDate.value = getTodayDateString()
    overview.value = ''
    desc.value = DEFAULT_DESC
    syncPreparedDatePickerFromString()
  } catch (error) {
    console.error('loadFromIndexedDB failed:', error)
    isProjectInitialized.value = false
    projectIndustry.value = DEFAULT_PROJECT_INDUSTRY
    projectName.value = DEFAULT_PROJECT_NAME
    preparedBy.value = ''
    reviewedBy.value = ''
    preparedCompany.value = ''
    preparedDate.value = getTodayDateString()
    overview.value = ''
    desc.value = DEFAULT_DESC
    syncPreparedDatePickerFromString()
  }
}

let persistTimer: ReturnType<typeof setTimeout> | null = null
const schedulePersist = () => {
  if (!isProjectInitialized.value) return
  if (persistTimer) clearTimeout(persistTimer)
  persistTimer = setTimeout(() => {
    void saveToIndexedDB()
  }, 250)
}

const handleProjectNameBlur = () => {
  if (!projectName.value.trim()) {
    projectName.value = DEFAULT_PROJECT_NAME
  }
}

watch(
  [projectIndustry, projectName, preparedBy, reviewedBy, preparedCompany, preparedDate, overview, desc],
  schedulePersist
)

onMounted(async () => {
  try {
    await waitForHydration('kv')
    await loadFromIndexedDB()
  } finally {
    isBootstrapping.value = false
  }
})
</script>

<template>
  <TooltipProvider>
  <div class="space-y-6 h-full">
    <div
      v-if="isBootstrapping"
      class="rounded-xl border bg-card p-10 h-full flex items-center justify-center text-sm text-muted-foreground"
    >
      {{ t('common.loading') }}
    </div>

    <div
      v-else-if="!isProjectInitialized"
      class="rounded-xl border bg-card p-10 h-full flex items-center justify-center text-sm text-muted-foreground"
    >
      {{ t('xmInfo.createFromHomeFirst') }}
    </div>

    <div v-else class="rounded-xl border bg-card p-4 shadow-sm shrink-0 md:p-5">
      <div class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
        <div class="md:col-span-2 xl:col-span-4">
          <label class="block text-sm font-medium text-foreground">{{ t('xmInfo.fields.projectName') }}</label>
          <input
            v-model="projectName"
            type="text"
            required
            :placeholder="t('xmInfo.defaultProjectName')"
            class="mt-2 h-10 w-full rounded-lg border bg-background px-4 text-sm outline-none ring-offset-background shadow-sm transition placeholder:text-muted-foreground/70 focus-visible:border-primary/60 focus-visible:ring-2 focus-visible:ring-ring"
            @blur="handleProjectNameBlur"
          />
        </div>

        <div class="md:col-span-2 xl:col-span-4">
          <div class="flex items-center gap-1.5">
            <label class="block text-sm font-medium text-foreground">{{ t('xmInfo.fields.projectIndustry') }}</label>
            <TooltipRoot>
              <TooltipTrigger as-child>
                <button
                  type="button"
                  :aria-label="t('xmInfo.industryHintAria')"
                  class="inline-flex h-5 w-5  items-center justify-center text-muted-foreground/90 transition hover:text-foreground"
                >
                  <CircleHelp class="h-5 w-5" />
                </button>
              </TooltipTrigger>
              <TooltipContent side="top">{{ INDUSTRY_HINT_TEXT }}</TooltipContent>
            </TooltipRoot>
          </div>
          <div class="mt-2 flex flex-wrap gap-3 rounded-lg border bg-background px-3 py-2">
            <label
              v-for="item in majorParentNodes"
              :key="item.id"
              class="inline-flex items-center gap-2 text-sm text-foreground/80"
            >
              <input
                v-model="projectIndustry"
                type="radio"
                :value="item.id"
                disabled
                class="h-4 w-4 cursor-not-allowed accent-primary"
              />
              <span>{{ item.name }}</span>
            </label>
          </div>
        </div>
    <div class="md:col-span-2 xl:col-span-4">
          <label class="block text-sm font-medium text-foreground">{{ t('xmInfo.fields.overview') }}</label>
          <textarea
            v-model="overview"
            rows="3"
            :placeholder="t('xmInfo.placeholders.overview')"
            class="mt-2 w-full rounded-lg border bg-background px-4 py-2 text-sm outline-none ring-offset-background shadow-sm transition placeholder:text-muted-foreground/70 focus-visible:border-primary/60 focus-visible:ring-2 focus-visible:ring-ring resize-none"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-foreground">{{ t('xmInfo.fields.preparedBy') }}</label>
          <input
            v-model="preparedBy"
            type="text"
            :placeholder="t('xmInfo.placeholders.preparedBy')"
            class="mt-2 h-10 w-full rounded-lg border bg-background px-4 text-sm outline-none ring-offset-background shadow-sm transition placeholder:text-muted-foreground/70 focus-visible:border-primary/60 focus-visible:ring-2 focus-visible:ring-ring"
          />
        </div>

        <div>
          <label class="block text-sm font-medium text-foreground">{{ t('xmInfo.fields.reviewedBy') }}</label>
          <input
            v-model="reviewedBy"
            type="text"
            :placeholder="t('xmInfo.placeholders.reviewedBy')"
            class="mt-2 h-10 w-full rounded-lg border bg-background px-4 text-sm outline-none ring-offset-background shadow-sm transition placeholder:text-muted-foreground/70 focus-visible:border-primary/60 focus-visible:ring-2 focus-visible:ring-ring"
          />
        </div>

        <div>
          <label class="block text-sm font-medium text-foreground">{{ t('xmInfo.fields.preparedCompany') }}</label>
          <input
            v-model="preparedCompany"
            type="text"
            :placeholder="t('xmInfo.placeholders.preparedCompany')"
            class="mt-2 h-10 w-full rounded-lg border bg-background px-4 text-sm outline-none ring-offset-background shadow-sm transition placeholder:text-muted-foreground/70 focus-visible:border-primary/60 focus-visible:ring-2 focus-visible:ring-ring"
          />
        </div>

        <div>
          <label class="block text-sm font-medium text-foreground">{{ t('xmInfo.fields.preparedDate') }}</label>
          <DatePickerRoot
            locale="en-CA"
            :model-value="preparedDatePickerValue"
            @update:model-value="handlePreparedDateSelect"
          >
            <DatePickerAnchor class="mt-2 block w-full">
              <DatePickerField
                v-slot="{ segments }"
                class="flex h-10 w-full items-center justify-between rounded-lg border bg-background px-4 text-sm outline-none ring-offset-background shadow-sm transition focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-ring"
              >
                <div class="flex items-center">
                  <template
                    v-for="(segment, index) in segments"
                    :key="`${segment.part}-${index}`"
                  >
                    <DatePickerInput
                      :part="segment.part"
                      :class="segment.part === 'literal' ? 'text-muted-foreground/70' : 'text-foreground'"
                    >
                      {{ segment.part === 'literal' ? '-' : segment.value }}
                    </DatePickerInput>
                  </template>
                </div>
                <DatePickerTrigger as-child>
                  <button type="button" class="cursor-pointer inline-flex h-6 w-6 items-center justify-center text-muted-foreground">
                    <CalendarIcon class="h-4 w-4" />
                  </button>
                </DatePickerTrigger>
              </DatePickerField>
            </DatePickerAnchor>
            <DatePickerContent class="z-50 w-[22rem] rounded-lg border bg-card p-4 shadow-lg">
              <DatePickerArrow class="fill-border" />
              <DatePickerCalendar v-slot="{ weekDays, grid }" locale="zh-CN">
                <DatePickerHeader class="mb-2 flex items-center justify-between">
                  <DatePickerPrev as-child>
                    <button
                      type="button"
                      class=" cursor-potiner inline-flex h-9 w-9 items-center justify-center rounded-md border text-sm transition hover:bg-muted"
                    >
                      ‹
                    </button>
                  </DatePickerPrev>
                  <DatePickerHeading class="text-base font-medium text-foreground" />
                  <DatePickerNext as-child>
                    <button
                      type="button"
                      class="cursor-potiner inline-flex h-9 w-9 items-center justify-center rounded-md border text-sm transition hover:bg-muted"
                    >
                      ›
                    </button>
                  </DatePickerNext>
                </DatePickerHeader>
                <div class="space-y-2">
                  <DatePickerGrid
                    v-for="month in grid"
                    :key="month.value.toString()"
                    class="w-full border-collapse select-none"
                  >
                    <DatePickerGridHead>
                      <DatePickerGridRow class="grid grid-cols-7">
                        <DatePickerHeadCell
                          v-for="day in weekDays"
                          :key="day"
                          class="flex h-9 items-center justify-center text-sm text-muted-foreground"
                        >
                          {{ day }}
                        </DatePickerHeadCell>
                      </DatePickerGridRow>
                    </DatePickerGridHead>
                    <DatePickerGridBody>
                      <DatePickerGridRow
                        v-for="(weekDates, index) in month.rows"
                        :key="`${month.value.toString()}-${index}`"
                        class="grid grid-cols-7"
                      >
                        <DatePickerCell
                          v-for="dateValue in weekDates"
                          :key="dateValue.toString()"
                          :date="dateValue"
                          class="h-10 w-full p-0.5"
                        >
                        <DatePickerCellTrigger
                          :day="dateValue"
                          :month="month.value"
                          class="cursor-pointer h-full w-full rounded-md border border-transparent bg-transparent text-base outline-none transition hover:bg-muted data-[outside-view]:text-muted-foreground/40 data-[selected]:border-primary data-[selected]:bg-transparent data-[selected]:text-foreground data-[disabled]:opacity-40 data-[unavailable]:text-muted-foreground/40"
                        >
                            {{ dateValue.day }}
                          </DatePickerCellTrigger>
                        </DatePickerCell>
                      </DatePickerGridRow>
                    </DatePickerGridBody>
                  </DatePickerGrid>
                </div>
              </DatePickerCalendar>
              <div class="mt-2 flex justify-end">
                  <DatePickerClose as-child>
                    <button
                    type="button"
                    class="cursor-pointer h-8 rounded-md border px-3 text-xs text-foreground transition hover:bg-muted mr-2"
                  >
                    {{ t('common.confirm') }}
                  </button>
                 
                </DatePickerClose>
              </div>
            </DatePickerContent>
          </DatePickerRoot>
        </div>
    

        <div class="md:col-span-2 xl:col-span-4">
          <label class="block text-sm font-medium text-foreground">{{ t('xmInfo.fields.desc') }}</label>
          <textarea
            v-model="desc"
            rows="4"
            class="mt-2 w-full rounded-lg border bg-background px-4 py-2 text-sm outline-none ring-offset-background shadow-sm transition placeholder:text-muted-foreground/70 focus-visible:border-primary/60 focus-visible:ring-2 focus-visible:ring-ring resize-none"
          />
        </div>
      </div>
    </div>
  </div>
  </TooltipProvider>
</template>
