import { ReactNode } from 'react'
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'
import { colors, radii, spacing } from '../../constants/theme'
import type { FormTab } from '../../constants/formTabsConfig'

type Props = {
  tabs: FormTab[]
  activeTab: string
  onChange: (key: string) => void
}

export function FormTabs({ tabs, activeTab, onChange }: Props) {
  return (
    <ScrollView
      horizontal
      showsHorizontalScrollIndicator={false}
      contentContainerStyle={styles.row}
      style={styles.scroll}
    >
      {tabs.map((tab) => {
        const active = tab.key === activeTab
        return (
          <Pressable
            key={tab.key}
            onPress={() => onChange(tab.key)}
            style={[styles.tab, active && styles.tabActive]}
          >
            <Text style={[styles.tabLabel, active && styles.tabLabelActive]}>{tab.label}</Text>
          </Pressable>
        )
      })}
    </ScrollView>
  )
}

type PanelProps = {
  visible: boolean
  tab?: FormTab
  children: ReactNode
}

export function FormTabPanel({ visible, tab, children }: PanelProps) {
  if (!visible) return null

  return (
    <View style={styles.panel}>
      {tab?.description ? (
        <View style={styles.description}>
          <Text style={styles.descriptionTitle}>{tab.label}</Text>
          <Text style={styles.descriptionText}>{tab.description}</Text>
        </View>
      ) : null}
      {children}
    </View>
  )
}

const styles = StyleSheet.create({
  scroll: {
    marginBottom: spacing.sm,
    maxHeight: 44,
  },
  row: {
    gap: spacing.xs,
    paddingBottom: spacing.xs,
  },
  tab: {
    backgroundColor: colors.surface,
    borderColor: colors.border,
    borderRadius: radii.pill,
    borderWidth: 1,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  tabActive: {
    backgroundColor: colors.primaryLight,
    borderColor: colors.primary,
  },
  tabLabel: {
    color: colors.textMuted,
    fontSize: 13,
    fontWeight: '600',
  },
  tabLabelActive: {
    color: colors.primaryDark,
    fontWeight: '700',
  },
  panel: {
    gap: spacing.sm,
  },
  description: {
    backgroundColor: colors.background,
    borderColor: colors.border,
    borderRadius: radii.md,
    borderWidth: 1,
    marginBottom: spacing.sm,
    padding: spacing.md,
  },
  descriptionTitle: {
    color: colors.text,
    fontSize: 15,
    fontWeight: '700',
    marginBottom: 4,
  },
  descriptionText: {
    color: colors.textMuted,
    fontSize: 13,
    lineHeight: 18,
  },
})
