/**
 * 标签管理页面 —— ManagementScreen 模板试点（P2）。
 *
 * 功能：标签列表(彩色芯片) + 添加/编辑/删除。
 * 标签名写入 .bean 的 #tag 语法,需符合 [\w-]。
 */
import React, { useState } from 'react';
import { Alert, Pressable, StyleSheet, Text, View } from 'react-native';
import { useTheme } from '../../theme';
import { TAG_COLORS } from '../../theme/palette';
import { useMetadataStore, generateId } from '../../store/metadataStore';
import { useT } from '../../i18n';
import { ManagementScreen } from '../../components/layout/ManagementScreen';
import { isValidTagName } from '../../domain/taxonomy/tags';
import type { Tag } from '../../domain/taxonomy/tags';

export default function TagScreen() {
  const { theme } = useTheme();
  const t = useT();

  const tags = useMetadataStore(s => s.tags);
  const addTag = useMetadataStore(s => s.addTag);
  const updateTag = useMetadataStore(s => s.updateTag);
  const removeTag = useMetadataStore(s => s.removeTag);

  const [selectedColor, setSelectedColor] = useState<string>(TAG_COLORS[0]);

  return (
    <ManagementScreen<Tag>
      title={t('tag.title')}
      items={tags}
      keyExtractor={tag => tag.id}
      addLabel={t('tag.add')}
      emptyText={t('tag.empty')}
      listStyle={styles.chipGrid}
      onOpenForm={editing => setSelectedColor(editing?.color ?? TAG_COLORS[0])}
      renderItem={(tag, { openEdit, confirmDelete }) => (
        <Pressable
          onPress={openEdit}
          onLongPress={confirmDelete}
          style={[styles.chip, { backgroundColor: tag.color }]}
        >
          <Text style={{ color: theme.colors.fgInverse, fontWeight: '700' }}>#{tag.name}</Text>
        </Pressable>
      )}
      formTitle={editing => (editing ? t('tag.editTitle') : t('tag.add'))}
      formFields={editing => [
        { key: 'name', label: t('tag.fieldName'), placeholder: 'food', defaultValue: editing?.name },
      ]}
      formExtra={() => (
        <View style={styles.colorRow}>
          {TAG_COLORS.map(c => (
            <Pressable
              key={c}
              onPress={() => setSelectedColor(c)}
              style={[styles.colorDot, {
                backgroundColor: c,
                borderWidth: selectedColor === c ? 3 : 0,
                borderColor: theme.colors.fgPrimary,
              }]}
            />
          ))}
        </View>
      )}
      onSubmit={(values, editing) => {
        const name = values.name?.trim() ?? '';
        if (!isValidTagName(name)) {
          Alert.alert(t('tag.invalidName'), t('tag.invalidDesc'));
          return false;
        }
        if (editing) updateTag(editing.id, { name, color: selectedColor });
        else addTag({ id: generateId('tag'), name, color: selectedColor });
        return true;
      }}
      onDelete={tag => removeTag(tag.id)}
      deleteConfirmText={tag => t('tag.deleteConfirm', { name: tag.name })}
      deleteConfirmTitle={t('tag.deleteTitle')}
      footer={
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, textAlign: 'center' }]}>
          {t('common.clickEditLongDelete')}
        </Text>
      }
    />
  );
}

const styles = StyleSheet.create({
  chipGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
  chip: { paddingVertical: 6, paddingHorizontal: 14, borderRadius: 16 },
  colorRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 12, paddingVertical: 4 },
  colorDot: { width: 36, height: 36, borderRadius: 18 },
});
