/**
 * Sección Incidencias: maestro-detalle + alta de incidencia.
 */
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import React, { useCallback, useState } from 'react';
import { FlatList, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { Issue } from '../../api/types';
import { hasPermission, useSession } from '../../auth/session';
import { getIssues } from '../../db/repositories';
import { RootStackParamList } from '../../navigation/types';
import {
  Badge,
  COLORS,
  EmptyState,
  ISSUE_PRIORITY_COLOR,
  ISSUE_STATUS_COLOR,
  PrimaryButton,
} from '../../ui/components';
import { MasterDetail } from '../../ui/MasterDetail';
import { IssueDetailContent } from '../detail/IssueDetailContent';

type Nav = NativeStackNavigationProp<RootStackParamList>;

export function IssuesSection({ projectId }: { projectId: number }) {
  const navigation = useNavigation<Nav>();
  const { user } = useSession();
  const canCreate = hasPermission(user, 'create issues');
  const [issues, setIssues] = useState<Issue[]>([]);

  const load = useCallback(() => {
    void getIssues(projectId).then(setIssues);
  }, [projectId]);

  useFocusEffect(load);

  return (
    <View style={{ flex: 1 }}>
      {canCreate && (
        <View style={styles.toolbar}>
          <PrimaryButton
            title="+ Nueva incidencia"
            variant="ghost"
            onPress={() => navigation.navigate('IssueCreate', { projectId })}
          />
        </View>
      )}
      <MasterDetail
        onSelectPhone={(id) => {
          const i = issues.find((x) => x.id === id);
          navigation.navigate('IssueDetail', { issueId: id, title: i?.title ?? 'Incidencia' });
        }}
        renderDetail={(id) => <IssueDetailContent issueId={id} />}
        renderMaster={({ selectedId, onSelect }) =>
          issues.length === 0 ? (
            <EmptyState text="Sin incidencias." />
          ) : (
            <FlatList
              data={issues}
              keyExtractor={(i) => String(i.id)}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={[styles.row, item.id === selectedId && styles.rowActive]}
                  onPress={() => onSelect(item.id)}
                >
                  <View style={{ flex: 1 }}>
                    <Text style={styles.title} numberOfLines={1}>
                      {item.title}
                    </Text>
                    <View style={styles.badges}>
                      {item.priority && (
                        <Badge
                          label={item.priority}
                          color={ISSUE_PRIORITY_COLOR[item.priority] ?? COLORS.muted}
                        />
                      )}
                      {item.status && (
                        <Badge
                          label={item.status}
                          color={ISSUE_STATUS_COLOR[item.status] ?? COLORS.muted}
                        />
                      )}
                      {item.id < 0 && <Badge label="local" color={COLORS.warn} />}
                    </View>
                  </View>
                </TouchableOpacity>
              )}
            />
          )
        }
      />
    </View>
  );
}

const styles = StyleSheet.create({
  toolbar: { padding: 12, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: COLORS.border },
  row: {
    paddingHorizontal: 16,
    paddingVertical: 14,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderColor: COLORS.border,
  },
  rowActive: { backgroundColor: '#eef5f0' },
  title: { fontSize: 15, fontWeight: '600' },
  badges: { flexDirection: 'row', gap: 6, marginTop: 6 },
});
