import React, { useState } from 'react';
import { Alert, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { Card } from '../components/ui/Card';
import { Input } from '../components/ui/Input';
import { Button } from '../components/ui/Button';
import { createEvent } from '../lib/events';
import { RootStackParamList } from '../navigation/types';
import { colors, radius, shadows } from '../lib/theme';

export default function EventsCreate() {
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [date, setDate] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const submit = async () => {
    setError('');
    if (!title.trim()) return setError('Preenche o título');
    if (!date.trim()) return setError('Escolhe a data e hora');

    const parsed = new Date(date.trim());
    if (Number.isNaN(parsed.getTime())) {
      return setError('Usa uma data válida. Ex: 2026-05-10 18:30');
    }

    try {
      setSaving(true);
      await createEvent({
        title: title.trim(),
        description: description.trim() || undefined,
        date: parsed.toISOString(),
      });
      Alert.alert('Evento criado', 'O evento foi guardado no teu perfil.');
      navigation.navigate('Profile');
    } catch (e: any) {
      setError(e?.message || 'Erro ao criar evento');
    } finally {
      setSaving(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.content}>
        <Card style={styles.card}>
          <View style={styles.iconBox}>
            <Text style={styles.iconText}>+</Text>
          </View>
          <Text style={styles.title}>Criar evento</Text>
          <Text style={styles.subtitle}>Este evento vai aparecer no teu perfil</Text>

          {!!error && <Text style={styles.error}>{error}</Text>}

          <Input
            label="Título"
            value={title}
            onChangeText={(text) => {
              setTitle(text);
              setError('');
            }}
            placeholder="Ex: Corte às 18h"
          />
          <Input
            label="Descrição (opcional)"
            value={description}
            onChangeText={(text) => {
              setDescription(text);
              setError('');
            }}
            placeholder="Notas do evento..."
          />
          <Input
            label="Data e hora"
            value={date}
            onChangeText={(text) => {
              setDate(text);
              setError('');
            }}
            placeholder="2026-05-10 18:30"
          />

          <View style={styles.actions}>
            <Button variant="outline" style={styles.actionButton} onPress={() => navigation.navigate('Profile')}>
              Cancelar
            </Button>
            <Button style={styles.actionButton} onPress={submit} loading={saving}>
              Criar evento
            </Button>
          </View>
        </Card>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  content: {
    padding: 16,
    justifyContent: 'center',
    minHeight: '100%',
  },
  card: {
    padding: 24,
    borderRadius: radius.sm,
  },
  iconBox: {
    width: 56,
    height: 56,
    borderRadius: radius.md,
    backgroundColor: colors.surfaceDark,
    alignItems: 'center',
    justifyContent: 'center',
    alignSelf: 'center',
    marginBottom: 16,
    ...shadows.soft,
  },
  iconText: {
    color: colors.accentSoft,
    fontSize: 32,
    fontWeight: '900',
    lineHeight: 36,
  },
  title: {
    fontSize: 28,
    fontWeight: '900',
    color: colors.text,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: 14,
    color: colors.textMuted,
    textAlign: 'center',
    marginTop: 6,
    marginBottom: 24,
  },
  error: {
    backgroundColor: colors.dangerSoft,
    borderColor: '#fecaca',
    borderWidth: 1,
    borderRadius: radius.md,
    color: '#991b1b',
    padding: 12,
    marginBottom: 16,
    fontWeight: '600',
  },
  actions: {
    flexDirection: 'row',
    gap: 12,
    marginTop: 8,
  },
  actionButton: {
    flex: 1,
  },
});
