/**
 * 备注模板管理页面。
 * 模板用 ${placeholder} 语法，导入账单时自动填充。
 * P5：套 ManagementScreen 模板，消除手写头部/新增按钮/弹窗样板。
 */
import React from 'react';
import { Pressable, Text } from 'react-native';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { useMetadataStore, generateId } from '../../store/metadataStore';
import { Card } from '../../components/ui/Card';
import { ManagementScreen } from '../../components/layout/ManagementScreen';

interface RemarkTemplate {
  id: string;
  name: string;
  template: string;
}

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

  const templates = useMetadataStore(s => s.remarkTemplates);
  const addTemplate = useMetadataStore(s => s.addRemarkTemplate);
  const updateTemplate = useMetadataStore(s => s.updateRemarkTemplate);
  const removeTemplate = useMetadataStore(s => s.removeRemarkTemplate);

  return (
    <ManagementScreen<RemarkTemplate>
      title={t('remark.title')}
      items={templates}
      keyExtractor={tpl => tpl.id}
      addLabel={t('remark.add')}
      emptyText={t('remark.empty')}
      renderItem={(tpl, { openEdit, confirmDelete }) => (
        <Pressable onPress={openEdit} onLongPress={confirmDelete}>
          <Card title={tpl.name}>
            <Text style={[theme.typography.bodySmall, { color: theme.colors.fgSecondary, fontVariant: ['tabular-nums'] }]}>
              {tpl.template}
            </Text>
          </Card>
        </Pressable>
      )}
      formTitle={editing => (editing ? t('remark.editTitle') : t('remark.add'))}
      formFields={editing => [
        { key: 'name', label: t('remark.fieldName'), placeholder: '日常餐饮', defaultValue: editing?.name },
        { key: 'template', label: t('remark.fieldTemplate'), placeholder: '${counterparty} ${time}', defaultValue: editing?.template },
      ]}
      onSubmit={(values, editing) => {
        const name = values.name?.trim() || t('common.untitled');
        const template = values.template?.trim() || '';
        if (editing) {
          updateTemplate(editing.id, { name, template });
        } else {
          addTemplate({ id: generateId('tpl'), name, template });
        }
        return true;
      }}
      onDelete={tpl => removeTemplate(tpl.id)}
      deleteConfirmText={tpl => t('remark.deleteConfirm', { name: tpl.name })}
      deleteConfirmTitle={t('remark.deleteTitle')}
      footer={
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, textAlign: 'center' }]}>
          {t('common.clickEditLongDelete')}
        </Text>
      }
    />
  );
}
