import React, { useState } from 'react';
import { ScrollView, StyleSheet, View, type ViewStyle } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import type { ComponentProps } from 'react';
import { EmptyState } from '../ui/EmptyState';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { ScreenHeader } from './ScreenHeader';
import { FormModal, type FormField } from '../form/FormModal';
import { ConfirmDialog } from '../ui/ConfirmDialog';
import { Touchable } from '../ui/Touchable';

/**
 * 管理页模板（P2）：统一「列表 + ＋新增 + 点按编辑 + 长按删除 + FormModal」模式。
 * 各管理页只声明字段配置与数据读写，不再复制 header/Alert/Modal 样板。
 */
interface ManagementScreenProps<T> {
  title: string;
  items: T[];
  keyExtractor: (item: T) => string;
  /** 渲染单个条目；handlers.openEdit 打开编辑弹窗，handlers.confirmDelete 弹删除确认。 */
  renderItem: (item: T, handlers: { openEdit: () => void; confirmDelete: () => void }) => React.ReactNode;
  addLabel: string;
  emptyText?: string;
  /** 空状态图标（Ionicons 名），默认 file-tray-outline。 */
  emptyIcon?: ComponentProps<typeof Ionicons>['name'];
  formTitle: (editing: T | null) => string;
  formFields: (editing: T | null) => FormField[];
  /** 返回 true 关闭弹窗（校验失败 Alert 后返回 false 保持打开）。 */
  onSubmit: (values: Record<string, string>, editing: T | null) => boolean;
  onDelete: (item: T) => void;
  deleteConfirmText: (item: T) => string;
  /** 删除确认弹窗标题（默认通用「删除」）。 */
  deleteConfirmTitle?: string;
  /** 字段值变更时的联动回调，返回新值覆盖。 */
  onValuesChange?: (changedKey: string, newValue: string, prevValues: Record<string, string>) => Record<string, string> | void;
  /** FormModal 附加内容（如颜色选择器），渲染在字段与按钮之间。 */
  formExtra?: (editing: T | null) => React.ReactNode;
  /** 打开表单时的回调（用于重置附加状态，如颜色选择）。 */
  onOpenForm?: (editing: T | null) => void;
  /** 列表上方的额外内容（分组 Tab 等）。 */
  headerContent?: React.ReactNode;
  footer?: React.ReactNode;
  /** 条目容器的额外样式（如标签页的 flexDirection row + flexWrap）。 */
  listStyle?: ViewStyle;
}

export function ManagementScreen<T>(props: ManagementScreenProps<T>) {
  const { theme } = useTheme();
  const t = useT();
  const [editing, setEditing] = useState<T | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [deleting, setDeleting] = useState<T | null>(null);

  const openForm = (item: T | null) => {
    setEditing(item);
    props.onOpenForm?.(item);
    setModalOpen(true);
  };

  const confirmDelete = (item: T) => setDeleting(item);

  const closeModal = () => {
    setModalOpen(false);
    setEditing(null);
  };

  const handleSubmit = (values: Record<string, string>) => {
    if (props.onSubmit(values, editing)) closeModal();
  };

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]} edges={['top']}>
      <ScreenHeader
        title={props.title}
        right={
          <Touchable onPress={() => openForm(null)} hitSlop={8} accessibilityRole="button" accessibilityLabel={props.addLabel}>
            <Ionicons name="add" size={26} color={theme.colors.accent} />
          </Touchable>
        }
      />
      <ScrollView contentContainerStyle={styles.content}>
        {props.headerContent}
        {props.items.length === 0 && props.emptyText ? (
          <EmptyState icon={props.emptyIcon ?? 'file-tray-outline'} title={props.emptyText} />
        ) : null}
        <View style={props.listStyle}>
          {props.items.map(item => (
            <View key={props.keyExtractor(item)}>
              {props.renderItem(item, {
                openEdit: () => openForm(item),
                confirmDelete: () => confirmDelete(item),
              })}
            </View>
          ))}
        </View>
        {props.footer}
      </ScrollView>
      <FormModal
        visible={modalOpen}
        title={props.formTitle(editing)}
        fields={props.formFields(editing)}
        onValuesChange={props.onValuesChange}
        onConfirm={handleSubmit}
        onCancel={closeModal}
      >
        {props.formExtra?.(editing)}
      </FormModal>
      <ConfirmDialog
        visible={deleting !== null}
        title={props.deleteConfirmTitle ?? t('common.delete')}
        message={deleting ? props.deleteConfirmText(deleting) : ''}
        confirmLabel={t('common.delete')}
        destructive
        onConfirm={() => {
          if (deleting) props.onDelete(deleting);
          setDeleting(null);
        }}
        onCancel={() => setDeleting(null)}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  page: { flex: 1 },
  content: { padding: 16, gap: 12 },
});
