/**
 * Alta de incidencia (modal). Crea en local + encola issue.create.
 */
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import React, { useCallback, useState } from 'react';
import { ScrollView, StyleSheet } from 'react-native';
import { IssuePriority, IssueType } from '../api/types';
import { createIssue } from '../sync/mutations';
import { RootStackParamList } from '../navigation/types';
import { ChipSelect, Field, PrimaryButton } from '../ui/components';

type Props = NativeStackScreenProps<RootStackParamList, 'IssueCreate'>;

const PRIORITIES: readonly IssuePriority[] = ['low', 'medium', 'high', 'critical'];
const TYPES: readonly IssueType[] = ['defect', 'safety', 'quality', 'documentation', 'other'];

export function IssueCreateScreen({ route, navigation }: Props) {
  const { projectId, featureId } = route.params;
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [priority, setPriority] = useState<IssuePriority>('medium');
  const [type, setType] = useState<IssueType>('defect');
  const [saving, setSaving] = useState(false);

  const onSubmit = useCallback(async () => {
    if (!title.trim()) return;
    setSaving(true);
    try {
      await createIssue({
        project_id: projectId,
        feature_id: featureId,
        title: title.trim(),
        description: description.trim() || undefined,
        priority,
        type,
        status: 'open',
      });
      navigation.goBack();
    } finally {
      setSaving(false);
    }
  }, [title, description, priority, type, projectId, featureId, navigation]);

  return (
    <ScrollView contentContainerStyle={styles.body}>
      <Field label="Título" value={title} onChangeText={setTitle} placeholder="Resumen de la incidencia" />
      <Field
        label="Descripción"
        value={description}
        onChangeText={setDescription}
        placeholder="Detalle…"
        multiline
      />
      <ChipSelect label="Prioridad" value={priority} options={PRIORITIES} onChange={setPriority} />
      <ChipSelect label="Tipo" value={type} options={TYPES} onChange={setType} />
      <PrimaryButton
        title="Crear incidencia"
        onPress={() => void onSubmit()}
        loading={saving}
        disabled={!title.trim()}
      />
      <PrimaryButton title="Cancelar" variant="ghost" onPress={() => navigation.goBack()} />
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  body: { padding: 16, gap: 4 },
});
