<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import { Button, Input, InputNumber, Segmented, Tag } from 'ant-design-vue';

import {
  formatPriceDisplay,
  getPriceDelta,
  isFieldChanged,
  isMarketGtPrice,
  isPriceChanged,
  isUnitChanged,
  type PriceDelta,
  type PricePair,
} from '../../admin/utils/priceCompare';

export type PriceCompareFilterTab =
  | 'all'
  | 'changed'
  | 'unchanged'
  | 'marketGtPrice'
  | 'unitChanged'
  | 'priceLocked'
  | 'new'
  | 'unmatched';

export type PriceCompareRow = {
  id: number;
  drug_id?: number;
  drug_name: string;
  drug_number: string;
  pinyin_simple?: string;
  orig_market_price: number;
  orig_price: number;
  orig_unit_name?: string;
  market_price: number;
  price: number;
  unit_name?: string;
  _changed: boolean;
  _marketGtPrice: boolean;
  _unitChanged?: boolean;
  /** 单位名不在字典中，确认时将自动新建 */
  _unitPendingCreate?: boolean;
  _isNew: boolean;
  _fromExcel?: boolean;
  /** 配送仓锁定，不可改价（门店） */
  _priceLocked?: boolean;
  _marketDelta: PriceDelta;
  _priceDelta: PriceDelta;
  _marketChanged: boolean;
  _priceChanged: boolean;
};

export type UnmatchedRow = {
  drug_name: string;
  drug_number: string;
  market_price: number;
  price: number;
  unit_name?: string;
};

const props = withDefaults(
  defineProps<{
    rows: PriceCompareRow[];
    unmatchedRows?: UnmatchedRow[];
    filterTab?: PriceCompareFilterTab;
    savingRowId?: number | null;
    /** 是否展示单位编辑（平台 true，门店 false） */
    showUnit?: boolean;
    /** 是否展示供货价（门店仅零售价时为 false） */
    showMarketPrice?: boolean;
    /** 售价列文案 */
    priceLabel?: string;
    /** 是否显示单行保存按钮 */
    showRowSave?: boolean;
    /** 是否展示「不可改价」筛选 Tab */
    showPriceLockedTab?: boolean;
  }>(),
  {
    unmatchedRows: () => [],
    filterTab: 'all',
    savingRowId: null,
    showUnit: false,
    showMarketPrice: true,
    priceLabel: '售价',
    showRowSave: true,
    showPriceLockedTab: false,
  },
);

const emit = defineEmits<{
  'update:filterTab': [PriceCompareFilterTab];
  cellChange: [row: PriceCompareRow];
  rowSave: [row: PriceCompareRow];
}>();

const keyword = ref('');
const innerFilterTab = ref<PriceCompareFilterTab>(props.filterTab);

watch(
  () => props.filterTab,
  (v) => {
    innerFilterTab.value = v;
  },
);

watch(innerFilterTab, (v) => {
  emit('update:filterTab', v);
});

const tabCounts = computed(() => {
  const all = props.rows.length;
  const changed = props.rows.filter((r) => r._changed && !r._priceLocked).length;
  const unchanged = props.rows.filter(
    (r) => !r._changed && !r._priceLocked && !r._isNew,
  ).length;
  const marketGtPrice = props.rows.filter((r) => r._marketGtPrice).length;
  const unitChanged = props.rows.filter((r) => r._unitChanged).length;
  const priceLocked = props.rows.filter((r) => r._priceLocked).length;
  const newCount = props.rows.filter((r) => r._isNew).length;
  const unmatched = props.unmatchedRows.length;
  return {
    all,
    changed,
    unchanged,
    marketGtPrice,
    unitChanged,
    priceLocked,
    new: newCount,
    unmatched,
  };
});

const filterOptions = computed(() => {
  const opts: { label: string; value: PriceCompareFilterTab }[] = [
    { label: `全部 ${tabCounts.value.all}`, value: 'all' },
    { label: `有修改 ${tabCounts.value.changed}`, value: 'changed' },
    { label: `无修改 ${tabCounts.value.unchanged}`, value: 'unchanged' },
  ];
  if (props.showMarketPrice) {
    opts.push({
      label: `供价超售价 ${tabCounts.value.marketGtPrice}`,
      value: 'marketGtPrice',
    });
  }
  if (props.showUnit) {
    opts.push({
      label: `单位变更 ${tabCounts.value.unitChanged}`,
      value: 'unitChanged',
    });
  }
  if (props.showPriceLockedTab) {
    opts.push({
      label: `不可改价 ${tabCounts.value.priceLocked}`,
      value: 'priceLocked',
    });
  }
  opts.push(
    { label: `待新增 ${tabCounts.value.new}`, value: 'new' },
    { label: `未匹配 ${tabCounts.value.unmatched}`, value: 'unmatched' },
  );
  return opts;
});

const filteredRows = computed(() => {
  const q = keyword.value.trim().toLowerCase();
  let list = props.rows;

  if (innerFilterTab.value === 'changed') {
    list = list.filter((r) => r._changed && !r._priceLocked);
  } else if (innerFilterTab.value === 'unchanged') {
    list = list.filter((r) => !r._changed && !r._priceLocked && !r._isNew);
  } else if (innerFilterTab.value === 'marketGtPrice') {
    list = list.filter((r) => r._marketGtPrice);
  } else if (innerFilterTab.value === 'unitChanged') {
    list = list.filter((r) => r._unitChanged);
  } else if (innerFilterTab.value === 'priceLocked') {
    list = list.filter((r) => r._priceLocked);
  } else if (innerFilterTab.value === 'new') {
    list = list.filter((r) => r._isNew);
  }

  if (q) {
    list = list.filter((r) => {
      const nameOk = r.drug_name.toLowerCase().includes(q);
      const py = (r.pinyin_simple ?? '').toLowerCase();
      const numOk = r.drug_number.toLowerCase().includes(q);
      return nameOk || py.includes(q) || numOk;
    });
  }

  return list;
});

function deltaClass(delta: PriceDelta): string {
  if (delta === 'up') {
    return 'text-rose-500 bg-rose-50 px-1 rounded dark:text-rose-400 dark:bg-rose-500/10 font-medium';
  }
  if (delta === 'down') {
    return 'text-emerald-500 bg-emerald-50 px-1 rounded dark:text-emerald-400 dark:bg-emerald-500/10 font-medium';
  }
  return 'text-gray-400 dark:text-gray-500';
}

function deltaSymbol(delta: PriceDelta): string {
  if (delta === 'up') return '↑';
  if (delta === 'down') return '↓';
  return '';
}

function cardClass(row: PriceCompareRow): string[] {
  // Enhanced card UI with smooth transitions and hover physics
  const classes = [
    'relative group rounded-xl border p-3 shadow-sm transition-all duration-300 ease-out hover:-translate-y-1 hover:shadow-md dark:bg-gray-800/80',
  ];
  if (row._priceLocked) {
    classes.push(
      'border-orange-200 bg-orange-50/40 dark:border-orange-500/30 dark:bg-orange-900/10',
    );
  } else if (row._isNew) {
    classes.push('border-blue-200 bg-blue-50/30 dark:border-blue-500/30 dark:bg-blue-900/10');
  } else if (row._marketGtPrice) {
    classes.push(
      'border-red-200 bg-red-50/50 ring-1 ring-red-100 dark:border-red-500/40 dark:bg-red-900/10 dark:ring-red-900/30',
    );
  } else if (row._changed) {
    classes.push(
      'border-amber-200 bg-amber-50/50 dark:border-amber-500/30 dark:bg-amber-900/10',
    );
  } else {
    classes.push('border-gray-100 bg-white dark:border-gray-700/60');
  }
  return classes;
}

function refreshRowFlags(row: PriceCompareRow) {
  const snapshot: PricePair = {
    market_price: row.orig_market_price,
    price: row.orig_price,
    unit_name: row.orig_unit_name,
  };
  const current: PricePair = {
    market_price: row.market_price,
    price: row.price,
    unit_name: row.unit_name,
  };
  row._marketDelta = getPriceDelta(snapshot.market_price, current.market_price);
  row._priceDelta = getPriceDelta(snapshot.price, current.price);
  row._marketChanged = isFieldChanged(
    snapshot.market_price,
    current.market_price,
  );
  row._priceChanged = isFieldChanged(snapshot.price, current.price);
  row._unitChanged = isUnitChanged(snapshot.unit_name, current.unit_name);
  row._changed = row._isNew || isPriceChanged(snapshot, current);
  row._marketGtPrice = isMarketGtPrice(current);
}

function onPriceChange(
  row: PriceCompareRow,
  field: 'market_price' | 'price',
  value: number | string | null,
) {
  row[field] = Number(value) || 0;
  refreshRowFlags(row);
  emit('cellChange', { ...row });
}

function onUnitChange(row: PriceCompareRow, value: string) {
  row.unit_name = value;
  refreshRowFlags(row);
  emit('cellChange', { ...row });
}

function handleRowSave(row: PriceCompareRow) {
  emit('rowSave', row);
}
</script>

<template>
  <div class="flex min-h-0 flex-1 flex-col overflow-hidden">
    <!-- Header Controls -->
    <div class="mb-4 flex flex-shrink-0 flex-wrap items-center gap-3">
      <Input
        v-model:value="keyword"
        allow-clear
        class="max-w-xs !rounded-lg shadow-sm"
        placeholder="按药品名称、编码或拼音筛选"
      />
      <Tag class="!rounded-full !border-gray-200 !bg-white px-3 py-1 shadow-sm dark:!border-gray-700 dark:!bg-gray-800">
        {{ filteredRows.length }} 条
      </Tag>
    </div>

    <!-- Segmented Control -->
    <Segmented
      v-model:value="innerFilterTab"
      class="mb-4 flex-shrink-0 flex-wrap !rounded-lg !p-1 shadow-sm"
      :options="filterOptions"
    />

    <!-- Main Content Area -->
    <div
      v-if="innerFilterTab !== 'unmatched'"
      class="min-h-0 flex-1 overflow-y-auto pr-1 custom-scrollbar"
    >
      <Transition name="fade" mode="out-in">
        <div
          v-if="filteredRows.length === 0"
          class="flex h-32 items-center justify-center text-sm text-gray-400"
        >
          暂无匹配的数据
        </div>

        <!-- Animated Grid -->
        <TransitionGroup
          v-else
          tag="div"
          name="list"
          class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5"
        >
          <div
            v-for="row in filteredRows"
            :key="row.id"
            :class="cardClass(row)"
          >
            <!-- Card Header -->
            <div class="mb-3 flex items-start justify-between gap-2 border-b border-gray-100/50 pb-2 dark:border-gray-700/50">
              <div
                class="min-w-0 flex-1 truncate text-sm font-semibold text-gray-800 dark:text-gray-100"
                :title="row.drug_name"
              >
                {{ row.drug_name || '—' }}
              </div>
              <span
                class="flex-shrink-0 rounded bg-gray-100 px-1.5 py-0.5 text-[11px] text-gray-500 dark:bg-gray-700 dark:text-gray-300"
                :title="row.drug_number"
              >
                {{ row.drug_number || '—' }}
              </span>
            </div>

            <!-- Status Tags -->
            <div v-if="row._isNew || row._priceLocked" class="mb-2 flex flex-wrap gap-1">
              <Tag
                v-if="row._isNew"
                color="blue"
                class="!mr-0 !border-blue-200 !text-[11px] shadow-sm"
              >
                待新增
              </Tag>
              <Tag
                v-if="row._priceLocked"
                color="orange"
                class="!mr-0 !text-[11px] shadow-sm"
              >
                不可改价
              </Tag>
            </div>

            <!-- Price Inputs Area -->
            <div class="space-y-2.5 text-xs">
              <!-- Market Price Row -->
              <div
                v-if="showMarketPrice"
                class="flex items-center justify-between group/row"
              >
                <span class="w-12 flex-shrink-0 font-medium text-gray-500 dark:text-gray-400">
                  供货价
                </span>
                <div class="flex flex-1 items-center justify-end gap-2">
                  <template v-if="!row._isNew">
                    <span class="text-gray-400 line-through decoration-gray-300 dark:text-gray-500 dark:decoration-gray-600">
                      {{ formatPriceDisplay(row.orig_market_price) }}
                    </span>
                    <span class="text-gray-300 dark:text-gray-600">→</span>
                  </template>
                  <InputNumber
                    class="!w-[85px] !rounded-md shadow-sm transition-all focus-within:ring-2 focus-within:ring-blue-100"
                    :min="0"
                    :precision="4"
                    :step="0.0001"
                    size="small"
                    :disabled="!!row._priceLocked"
                    :value="row.market_price"
                    @update:value="
                      (v) => onPriceChange(row, 'market_price', v as number)
                    "
                  />
                  <span
                    v-if="!row._isNew && row._marketChanged"
                    class="w-4 text-center transition-opacity"
                    :class="deltaClass(row._marketDelta)"
                  >
                    {{ deltaSymbol(row._marketDelta) }}
                  </span>
                  <span v-else class="w-4"></span>
                </div>
              </div>

              <!-- Sell Price Row -->
              <div class="flex items-center justify-between group/row">
                <span class="w-12 flex-shrink-0 font-medium text-gray-500 dark:text-gray-400">
                  {{ priceLabel }}
                </span>
                <div class="flex flex-1 items-center justify-end gap-2">
                  <template v-if="!row._isNew">
                    <span class="text-gray-400 line-through decoration-gray-300 dark:text-gray-500 dark:decoration-gray-600">
                      {{ formatPriceDisplay(row.orig_price) }}
                    </span>
                    <span class="text-gray-300 dark:text-gray-600">→</span>
                  </template>
                  <InputNumber
                    class="!w-[85px] !rounded-md shadow-sm transition-all focus-within:ring-2 focus-within:ring-blue-100"
                    :min="0"
                    :precision="4"
                    :step="0.0001"
                    size="small"
                    :disabled="!!row._priceLocked"
                    :value="row.price"
                    @update:value="
                      (v) => onPriceChange(row, 'price', v as number)
                    "
                  />
                  <span
                    v-if="!row._isNew && row._priceChanged"
                    class="w-4 text-center transition-opacity"
                    :class="deltaClass(row._priceDelta)"
                  >
                    {{ deltaSymbol(row._priceDelta) }}
                  </span>
                  <span v-else class="w-4"></span>
                </div>
              </div>

              <!-- Unit Row（平台） -->
              <div
                v-if="showUnit"
                class="flex items-center justify-between group/row"
              >
                <span class="w-12 flex-shrink-0 font-medium text-gray-500 dark:text-gray-400">
                  单位
                </span>
                <div class="flex flex-1 items-center justify-end gap-2">
                  <template v-if="!row._isNew">
                    <span class="text-gray-400 line-through decoration-gray-300 dark:text-gray-500">
                      {{ row.orig_unit_name || '—' }}
                    </span>
                    <span class="text-gray-300 dark:text-gray-600">→</span>
                  </template>
                  <Input
                    class="!w-[85px] !rounded-md shadow-sm"
                    size="small"
                    :value="row.unit_name"
                    placeholder="单位"
                    @update:value="(v) => onUnitChange(row, String(v ?? ''))"
                  />
                  <Tag
                    v-if="row._unitPendingCreate"
                    color="orange"
                    class="!mr-0 !text-[10px]"
                  >
                    待建
                  </Tag>
                  <span v-else class="w-4"></span>
                </div>
              </div>
              <!-- 门店只读单位对照 -->
              <div
                v-else-if="row.unit_name || row.orig_unit_name"
                class="flex items-center justify-between text-gray-400"
              >
                <span class="w-12 flex-shrink-0">单位</span>
                <span>{{ row.unit_name || row.orig_unit_name || '—' }}</span>
              </div>
            </div>

            <!-- Action Area -->
            <div
              class="mt-3 flex h-7 items-end justify-end overflow-hidden"
            >
              <Transition name="slide-up">
                <Button
                  v-if="showRowSave && row._changed && !row._priceLocked"
                  :loading="savingRowId === row.id"
                  size="small"
                  type="primary"
                  class="!rounded-md !px-4 shadow-sm hover:shadow-md"
                  @click="handleRowSave(row)"
                >
                  保存更新
                </Button>
              </Transition>
            </div>
          </div>
        </TransitionGroup>
      </Transition>
    </div>

    <!-- Unmatched Rows View -->
    <Transition name="fade" mode="out-in">
      <div
        v-if="innerFilterTab === 'unmatched'"
        class="min-h-0 flex-1 overflow-y-auto rounded-xl border border-orange-100 bg-gradient-to-b from-orange-50/50 to-orange-50/10 p-4 shadow-inner custom-scrollbar dark:border-orange-900/40 dark:from-orange-950/20 dark:to-transparent"
      >
        <div
          v-if="unmatchedRows.length === 0"
          class="flex h-full items-center justify-center text-sm text-gray-400"
        >
          暂无未匹配行
        </div>
        <div
          v-for="(row, index) in unmatchedRows"
          :key="`${row.drug_name}-${index}`"
          class="group mb-2 flex items-center justify-between rounded-lg bg-white p-3 shadow-sm transition-all hover:shadow-md dark:bg-gray-800"
        >
          <div class="flex items-center gap-3">
            <span class="font-medium text-gray-800 dark:text-gray-200">{{ row.drug_name || '—' }}</span>
            <span class="rounded bg-gray-100 px-2 py-0.5 text-xs text-gray-500 dark:bg-gray-700">{{ row.drug_number || '—' }}</span>
          </div>
          <div class="flex gap-4 text-sm text-gray-600 dark:text-gray-400">
            <span>供货价 <strong class="font-semibold text-gray-800 dark:text-gray-200">{{ formatPriceDisplay(row.market_price) }}</strong></span>
            <span class="text-gray-300">|</span>
            <span>售价 <strong class="font-semibold text-gray-800 dark:text-gray-200">{{ formatPriceDisplay(row.price) }}</strong></span>
          </div>
        </div>
      </div>
    </Transition>
  </div>
</template>

<style scoped>
/* List Transitions for Grid Cards */
.list-move,
.list-enter-active,
.list-leave-active {
  transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateY(15px) scale(0.98);
}

/* Ensure leaving items are taken out of flow so moving items animate smoothly */
.list-leave-active {
  position: absolute;
}

/* Fade Transitions */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* Slide Up Transition for Button */
.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}

.slide-up-enter-from,
.slide-up-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

/* Scrollbar styling for modern look */
.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}
.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.3);
  border-radius: 20px;
}
.custom-scrollbar:hover::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.5);
}
</style>
