import { Dropdown } from '@/aesthetics/Dropdown';
import { Text } from '@/aesthetics/Text';
import { TextInput } from '@/aesthetics/TextInput';
import { font, radius, shadows, spacing, useColors, weight } from '@/aesthetics/styles';
import { ChevronRight, LogOut, Mail, User, type LucideIcon } from 'lucide-react-native';
import { ReactNode, useRef, useState } from 'react';
import { Pressable, ScrollView, StyleSheet, Switch, View } from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { getBiologicalSexOptions, useProfileSettings } from './useProfile';

type SectionProps = {
  title: string;
  children: ReactNode;
  c: ReturnType<typeof useColors>;
};

const Section = ({ title, children, c }: SectionProps) => (
  <View style={styles.section}>
    <Text style={[styles.sectionTitle, { color: c.secondaryText }]}>{title}</Text>
    <View
      style={[styles.card, shadows.sm, { backgroundColor: c.surface, borderColor: c.borderSubtle }]}
    >
      {children}
    </View>
  </View>
);

type ActionRowProps = {
  icon?: LucideIcon;
  label: string;
  onPress?: () => void;
  iconBg?: string;
  iconColor?: string;
  labelColor?: string;
  rightContent?: ReactNode;
  showChevron?: boolean;
  border?: boolean;
  c: ReturnType<typeof useColors>;
};

const ActionRow = ({
  icon: Icon,
  label,
  onPress,
  iconBg,
  iconColor,
  labelColor,
  rightContent,
  showChevron = true,
  border = true,
  c,
}: ActionRowProps) => (
  <Pressable
    style={({ pressed }) => [
      styles.actionRow,
      pressed && styles.pressed,
      !border && { borderBottomWidth: 0 },
      border && { borderBottomWidth: 1, borderBottomColor: c.borderSubtle },
    ]}
    onPress={onPress}
  >
    <View style={styles.actionRowLeft}>
      {Icon && (
        <View style={[styles.iconCircle, { backgroundColor: iconBg }]}>
          <Icon size={16} color={iconColor} strokeWidth={1.5} />
        </View>
      )}
      <Text style={[styles.actionLabel, { color: labelColor || c.text }]}>{label}</Text>
    </View>
    <View style={styles.rowRight}>
      {rightContent}
      {showChevron && <ChevronRight size={18} color={c.tertiaryText} />}
    </View>
  </Pressable>
);

const getLanguageOptions = (strings: ReturnType<typeof useProfileSettings>['strings']) => [
  { label: strings.profile.languages.system, value: 'system' },
  { label: strings.profile.languages.english, value: 'en' },
  { label: strings.profile.languages.korean, value: 'ko' },
];

export function ProfileContent() {
  const c = useColors();
  const insets = useSafeAreaInsets();
  const languageRowRef = useRef<View>(null);
  const [languageDropdownOpen, setLanguageDropdownOpen] = useState(false);
  const {
    isDarkMode,
    hapticFeedback,
    user,
    profile,
    isDemo,
    languagePreference,
    strings,
    editingField,
    tempValue,
    setTheme,
    setHapticFeedback,
    setTempValue,
    handleSignOut,
    startEditing,
    saveField,
    updateSex,
    setLanguage,
    handleOpenPrivacy,
    handleOpenTerms,
    handleContactSupport,
    handleNavigateToBoard,
    handleNavigateToCastle,
    handleNavigateToSignIn,
  } = useProfileSettings();

  const renderRow = (
    label: string,
    value: string | null,
    field?: string,
    keyboardType: 'default' | 'numeric' = 'default',
    suffix?: string
  ) => {
    const isEditing = editingField === field;
    return (
      <View style={[styles.row, { borderBottomColor: c.borderSubtle }]}>
        <Text style={[styles.rowLabel, { color: c.text }]}>{label}</Text>
        {field && isEditing ? (
          <TextInput
            style={[styles.input, { color: c.text, backgroundColor: c.tagBg }]}
            value={tempValue}
            onChangeText={setTempValue}
            keyboardType={keyboardType}
            autoFocus
            onBlur={() => saveField(field)}
            onSubmitEditing={() => saveField(field)}
          />
        ) : (
          <Pressable onPress={field ? () => startEditing(field, value) : undefined}>
            <Text style={[styles.rowValue, { color: value ? c.secondaryText : c.tertiaryText }]}>
              {value ? `${value}${suffix || ''}` : strings.common.notSet}
            </Text>
          </Pressable>
        )}
      </View>
    );
  };

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: c.background }]} edges={['top']}>
      <ScrollView
        style={styles.scroll}
        contentContainerStyle={[styles.content, { paddingBottom: 120 + insets.bottom }]}
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.header}>
          <Text style={[styles.title, { color: c.text, fontWeight: weight.semibold }]}>
            {strings.profile.title}
          </Text>
          <Text style={[styles.subtitle, { color: c.tertiaryText }]}>
            {strings.profile.subtitle}
          </Text>
        </View>

        <View style={styles.sections}>
          <Section title={strings.profile.account} c={c}>
            {isDemo ? (
              <ActionRow
                icon={User}
                label={strings.auth.signIn}
                onPress={handleNavigateToSignIn}
                iconBg={c.accentSubtle}
                iconColor={c.accent}
                border={false}
                c={c}
              />
            ) : (
              <>
                <View style={[styles.row, { borderBottomColor: c.borderSubtle }]}>
                  <View style={styles.actionRowLeft}>
                    <View style={[styles.iconCircle, { backgroundColor: c.sageSubtle }]}>
                      <Mail size={16} color={c.sage} strokeWidth={1.5} />
                    </View>
                    <Text style={[styles.rowLabel, { color: c.text }]}>{user?.email}</Text>
                  </View>
                </View>
                <ActionRow
                  icon={LogOut}
                  label={strings.auth.signOut}
                  onPress={handleSignOut}
                  iconBg={c.roseSubtle}
                  iconColor={c.danger}
                  labelColor={c.danger}
                  showChevron={false}
                  border={false}
                  c={c}
                />
              </>
            )}
          </Section>

          {!isDemo && (
            <Section title={strings.profile.personalInfo} c={c}>
              {renderRow(
                strings.profile.birthYear,
                profile?.birth_year?.toString() || null,
                'birth_year',
                'numeric'
              )}
              <View style={[styles.row, { borderBottomColor: c.borderSubtle }]}>
                <Text style={[styles.rowLabel, { color: c.text }]}>
                  {strings.profile.biologicalSex}
                </Text>
                <View style={[styles.segmentedControl, { backgroundColor: c.tagBg }]}>
                  {getBiologicalSexOptions(strings).map(option => (
                    <Pressable
                      key={option.label}
                      style={[
                        styles.segment,
                        profile?.biological_sex === option.value && {
                          backgroundColor: c.accent,
                        },
                      ]}
                      onPress={() => updateSex(option.value)}
                    >
                      <Text
                        style={[
                          styles.segmentText,
                          {
                            color:
                              profile?.biological_sex === option.value
                                ? c.buttonText
                                : c.secondaryText,
                          },
                        ]}
                      >
                        {option.label}
                      </Text>
                    </Pressable>
                  ))}
                </View>
              </View>
              {renderRow(
                strings.profile.height,
                profile?.body_height_cm?.toString() || null,
                'body_height_cm',
                'numeric',
                ` ${strings.profile.cm}`
              )}
              {renderRow(
                strings.profile.weight,
                profile?.body_weight_kg?.toString() || null,
                'body_weight_kg',
                'numeric',
                ` ${strings.profile.kg}`
              )}
            </Section>
          )}

          <Section title={strings.profile.settings} c={c}>
            <View style={[styles.row, { borderBottomColor: c.borderSubtle }]}>
              <Text style={[styles.rowLabel, { color: c.text }]}>{strings.profile.darkMode}</Text>
              <Switch
                value={isDarkMode}
                onValueChange={v => setTheme(v ? 'dark' : 'light')}
                trackColor={{ false: c.progressBg, true: c.accent }}
                thumbColor="#FFFFFF"
              />
            </View>
            <View style={[styles.row, { borderBottomColor: c.borderSubtle }]}>
              <Text style={[styles.rowLabel, { color: c.text }]}>
                {strings.profile.hapticFeedback}
              </Text>
              <Switch
                value={hapticFeedback}
                onValueChange={setHapticFeedback}
                trackColor={{ false: c.progressBg, true: c.accent }}
                thumbColor="#FFFFFF"
              />
            </View>
            <View ref={languageRowRef}>
              <ActionRow
                label={strings.profile.language}
                onPress={() => setLanguageDropdownOpen(true)}
                border={false}
                rightContent={
                  <Text style={[styles.rowValue, { color: c.accent, marginRight: spacing.xs }]}>
                    {languagePreference === 'system'
                      ? strings.profile.languages.systemDisplay
                      : languagePreference === 'en'
                        ? strings.profile.languages.englishDisplay
                        : strings.profile.languages.koreanDisplay}
                  </Text>
                }
                c={c}
              />
            </View>
            <Dropdown
              triggerRef={languageRowRef}
              visible={languageDropdownOpen}
              onClose={() => setLanguageDropdownOpen(false)}
              options={getLanguageOptions(strings)}
              selected={languagePreference}
              onSelect={v => setLanguage(v as 'system' | 'en' | 'ko')}
            />
          </Section>

          <Section title={strings.profile.support} c={c}>
            <ActionRow label={strings.profile.castleMode} onPress={handleNavigateToCastle} c={c} />
            <ActionRow label={strings.profile.privacyPolicy} onPress={handleOpenPrivacy} c={c} />
            <ActionRow label={strings.profile.termsOfService} onPress={handleOpenTerms} c={c} />
            {!isDemo && (
              <ActionRow
                label={strings.profile.theBoardRoom}
                onPress={handleNavigateToBoard}
                c={c}
              />
            )}
            <ActionRow
              label={strings.profile.contactSupport}
              onPress={handleContactSupport}
              border={false}
              c={c}
            />
          </Section>
        </View>

        <View style={styles.footer}>
          <Text
            style={[styles.footerBrand, { color: c.tertiaryText, fontWeight: weight.semibold }]}
          >
            {strings.common.appName}
          </Text>
          <Text style={[styles.footerTagline, { color: c.tertiaryText }]}>
            {strings.common.tagline}
          </Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scroll: {
    flex: 1,
  },
  content: {
    paddingHorizontal: spacing.xl,
    paddingTop: spacing.lg,
  },
  header: {
    marginBottom: spacing.xxl,
  },
  title: {
    fontSize: font.xxl,
    letterSpacing: 0.5,
  },
  subtitle: {
    fontSize: font.sm,
    marginTop: spacing.xs,
  },
  sections: {
    gap: spacing.xl,
  },
  section: {
    gap: spacing.sm,
  },
  sectionTitle: {
    fontSize: font.xs,
    fontWeight: weight.medium,
    textTransform: 'uppercase',
    letterSpacing: 1,
    marginLeft: spacing.xs,
  },
  card: {
    borderRadius: radius.lg,
    borderWidth: 1,
    overflow: 'hidden',
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.lg,
    borderBottomWidth: 1,
  },
  rowRight: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 0,
  },
  rowLabel: {
    fontSize: font.md,
    fontWeight: weight.medium,
  },
  rowValue: {
    fontSize: font.md,
  },
  actionRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.lg,
  },
  actionRowLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
  },
  actionLabel: {
    fontSize: font.md,
    fontWeight: weight.medium,
  },
  iconCircle: {
    width: 32,
    height: 32,
    borderRadius: radius.sm,
    alignItems: 'center',
    justifyContent: 'center',
  },
  input: {
    fontSize: font.md,
    borderRadius: radius.sm,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    minWidth: 80,
    textAlign: 'right',
  },
  segmentedControl: {
    flexDirection: 'row',
    padding: 3,
    borderRadius: radius.sm,
  },
  segment: {
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderRadius: radius.sm - 2,
  },
  segmentText: {
    fontSize: font.sm,
    fontWeight: weight.medium,
  },
  pressed: {
    opacity: 0.7,
  },
  footer: {
    marginTop: spacing.xxxl,
    alignItems: 'center',
    paddingBottom: spacing.xl,
  },
  footerBrand: {
    fontSize: font.lg,
    letterSpacing: 1,
  },
  footerTagline: {
    fontSize: font.xs,
    letterSpacing: 2,
    textTransform: 'uppercase',
    marginTop: spacing.xs,
  },
});
