import { useState } from 'react';
import { Linking, Modal, ScrollView, StyleSheet, View } from 'react-native';
import { Appbar, Button, HelperText, SegmentedButtons, Text, TextInput } from 'react-native-paper';
import * as MailComposer from 'expo-mail-composer';
import { SafeAreaView } from 'react-native-safe-area-context';
import { theme } from './theme';

const SUBMIT_TO = 'stowarzyszenie@mage.pl';
const DATE = /^\d{4}-\d{2}-\d{2}$/;

type Mode = 'stacjonarnie' | 'online' | 'hybrydowo';

// Builds the e-mail body. Keep the labels in sync with the website's form.
export function buildBody(f: Record<string, string>): string {
  return [
    `Nazwa konferencji: ${f.title}`,
    `Termin: ${f.start}${f.end && f.end !== f.start ? ` - ${f.end}` : ''}`,
    `Sposób udziału: ${f.mode}`,
    `Miejsce: ${f.place || '-'}`,
    `Organizator: ${f.organizer || '-'}`,
    `Strona konferencji: ${f.url || '-'}`,
    '',
    'Opis:',
    f.description || '-',
  ].join('\n');
}

export function SubmitForm({ visible, onClose }: { visible: boolean; onClose: () => void }) {
  const [f, setF] = useState<Record<string, string>>({ mode: 'stacjonarnie' });
  const [tried, setTried] = useState(false);
  const set = (k: string) => (v: string) => setF((p) => ({ ...p, [k]: v }));

  const errors = {
    title: !f.title?.trim(),
    start: !DATE.test(f.start ?? ''),
    end: !!f.end && !DATE.test(f.end),
    place: f.mode !== 'online' && !f.place?.trim(),
  };
  const invalid = Object.values(errors).some(Boolean);

  async function send() {
    setTried(true);
    if (invalid) return;
    const subject = `Zgłoszenie konferencji: ${f.title.trim()}`;
    const body = buildBody(f);
    try {
      if (!(await MailComposer.isAvailableAsync())) throw new Error('no mail');
      const r = await MailComposer.composeAsync({ recipients: [SUBMIT_TO], subject, body });
      if (r.status === 'sent' || r.status === 'saved') onClose();
    } catch {
      // No mail account configured (or web preview): fall back to a mailto: link.
      await Linking.openURL(`mailto:${SUBMIT_TO}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`);
    }
  }

  return (
    <Modal visible={visible} animationType="slide" onRequestClose={onClose}>
      <SafeAreaView style={s.root} edges={['top', 'bottom']}>
        <Appbar.Header style={s.header}>
          <Appbar.Action icon="close" color="#FFFFFF" onPress={onClose} accessibilityLabel="Zamknij formularz" />
          <Appbar.Content title="Zgłoś konferencję" titleStyle={s.title} />
        </Appbar.Header>
        <ScrollView contentContainerStyle={s.body} keyboardShouldPersistTaps="handled">
          <Text variant="bodyMedium" style={s.intro}>
            Wypełnij dane. Otworzymy gotowy e-mail do redakcji, a Ty go tylko wyślesz.
            Niczego nie zapisujemy w aplikacji ani na serwerze.
          </Text>
          <TextInput mode="outlined" label="Nazwa konferencji *" value={f.title ?? ''} onChangeText={set('title')} error={tried && errors.title} />
          <HelperText type="error" visible={tried && errors.title}>Podaj nazwę konferencji.</HelperText>
          <View style={s.row}>
            <View style={s.half}>
              <TextInput mode="outlined" label="Od *" placeholder="RRRR-MM-DD" value={f.start ?? ''} onChangeText={set('start')} error={tried && errors.start} />
              <HelperText type="error" visible={tried && errors.start}>Format RRRR-MM-DD.</HelperText>
            </View>
            <View style={s.half}>
              <TextInput mode="outlined" label="Do" placeholder="RRRR-MM-DD" value={f.end ?? ''} onChangeText={set('end')} error={tried && errors.end} />
              <HelperText type="error" visible={tried && errors.end}>Format RRRR-MM-DD.</HelperText>
            </View>
          </View>
          <SegmentedButtons
            value={f.mode}
            onValueChange={set('mode')}
            buttons={[
              { value: 'stacjonarnie', label: 'Stacjonarnie', showSelectedCheck: false },
              { value: 'online', label: 'Online', showSelectedCheck: false },
              { value: 'hybrydowo', label: 'Hybrydowo', showSelectedCheck: false },
            ] satisfies { value: Mode; label: string; showSelectedCheck: boolean }[]}
          />
          <TextInput mode="outlined" style={s.gap} label={f.mode === 'online' ? 'Miejsce (opcjonalnie)' : 'Miejsce *'} value={f.place ?? ''} onChangeText={set('place')} error={tried && errors.place} />
          <HelperText type="error" visible={tried && errors.place}>Podaj miejsce konferencji.</HelperText>
          <TextInput mode="outlined" label="Organizator" value={f.organizer ?? ''} onChangeText={set('organizer')} />
          <TextInput mode="outlined" style={s.gap} label="Strona konferencji (adres www)" autoCapitalize="none" keyboardType="url" value={f.url ?? ''} onChangeText={set('url')} />
          <TextInput mode="outlined" style={s.gap} label="Krótki opis" multiline numberOfLines={4} value={f.description ?? ''} onChangeText={set('description')} />
          <Button mode="contained" icon="email-fast-outline" style={s.send} contentStyle={s.sendContent} onPress={send}>
            Przygotuj e-mail
          </Button>
          <Text variant="bodySmall" style={s.note}>Wiadomość trafi na adres {SUBMIT_TO}.</Text>
        </ScrollView>
      </SafeAreaView>
    </Modal>
  );
}

const s = StyleSheet.create({
  root: { flex: 1, backgroundColor: theme.colors.primary },
  header: { backgroundColor: theme.colors.primary },
  title: { color: '#FFFFFF', fontWeight: '700' },
  body: { padding: 16, backgroundColor: theme.colors.background, flexGrow: 1 },
  intro: { marginBottom: 12 },
  row: { flexDirection: 'row', gap: 12 },
  half: { flex: 1 },
  gap: { marginTop: 12 },
  send: { marginTop: 20 },
  sendContent: { paddingVertical: 6 },
  note: { marginTop: 8, textAlign: 'center', color: theme.colors.onSurfaceVariant },
});
