import React, { useState, useCallback } from 'react';
import { View, FlatList, StyleSheet, RefreshControl, TextInput, TouchableOpacity, Text, KeyboardAvoidingView, Platform } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { useResponsive } from '../../hooks/useResponsive';
import { Header } from '../../components/common/Header';
import { AnimatedCard } from '../../components/ui/AnimatedCard';
import { EmptyState } from '../../components/ui/EmptyState';
import { StatusBadge } from '../../components/common/StatusBadge';
import { jobService } from '../../services/jobService';
import { useAuth } from '../../hooks/useAuth';
import { Job } from '../../types';
import { colors, spacing, radii } from '../../theme';

export default function JobListScreen() {
  const navigation = useNavigation<any>();
  const insets = useSafeAreaInsets();
  const { hasPermission } = useAuth();
  const { contentPadding, fontSize, isPhone } = useResponsive();
  const [jobs, setJobs] = useState<Job[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [search, setSearch] = useState('');

  const loadJobs = async () => {
    try {
      const data = await jobService.list();
      setJobs(data);
    } catch (error) {
      console.error('Failed to load jobs:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(useCallback(() => { loadJobs(); }, []));

  const filteredJobs = jobs.filter(
    j => j.title.toLowerCase().includes(search.toLowerCase()) ||
         j.job_number.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <View style={styles.container}>
      <Header title="Jobs" subtitle={`${filteredJobs.length} jobs`} />

      <View style={[styles.toolbar, { paddingHorizontal: contentPadding, paddingTop: spacing.md }]}>
        <View style={styles.searchContainer}>
          <Ionicons name="search-outline" size={16} color={colors.gray[400]} />
          <TextInput
            style={[styles.searchInput, { fontSize: fontSize.body }]}
            placeholder="Search jobs..."
            placeholderTextColor={colors.gray[400]}
            value={search}
            onChangeText={setSearch}
          />
          {search.length > 0 && (
            <TouchableOpacity onPress={() => setSearch('')}>
              <Ionicons name="close-circle" size={16} color={colors.gray[400]} />
            </TouchableOpacity>
          )}
        </View>
        {hasPermission('job.create') && (
          <TouchableOpacity
            style={styles.addButton}
            onPress={() => navigation.navigate('JobCreate')}
            activeOpacity={0.7}
          >
            <Ionicons name="add" size={18} color={colors.white} />
            <Text style={[styles.addButtonText, { fontSize: fontSize.body }]}>New Job</Text>
          </TouchableOpacity>
        )}
      </View>

      <FlatList
        data={filteredJobs}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item, index }) => (
          <AnimatedCard
            onPress={() => navigation.navigate('JobDetail', { jobId: item.id })}
            delay={index * 60}
            style={{ marginBottom: spacing.md }}
          >
            <View style={styles.cardHeader}>
              <Text style={[styles.jobNumber, { fontSize: fontSize.caption }]}>{item.job_number}</Text>
              <StatusBadge status={item.status} />
            </View>
            <Text style={[styles.title, { fontSize: fontSize.h3 }]} numberOfLines={1}>{item.title}</Text>
            {item.description && (
              <Text style={[styles.description, { fontSize: fontSize.bodySmall }]} numberOfLines={2}>{item.description}</Text>
            )}
            <View style={styles.progressContainer}>
              <View style={styles.progressBar}>
                <View style={[styles.progressFill, { width: `${item.completion_percentage}%` }]} />
              </View>
              <Text style={[styles.percentage, { fontSize: fontSize.caption }]}>{item.completion_percentage}%</Text>
            </View>
          </AnimatedCard>
        )}
        contentContainerStyle={{ padding: contentPadding, paddingTop: spacing.md, paddingBottom: 100 }}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => { setRefreshing(true); loadJobs(); }} tintColor={colors.primary[500]} />}
        ListEmptyComponent={
          <EmptyState
            icon="briefcase-outline"
            title="No jobs found"
            description={search ? 'Try a different search term' : 'Create your first job to get started'}
            action={
              hasPermission('job.create') && !search ? (
                <TouchableOpacity style={styles.emptyAction} onPress={() => navigation.navigate('JobCreate')}>
                  <Text style={styles.emptyActionText}>Create Job</Text>
                </TouchableOpacity>
              ) : undefined
            }
          />
        }
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: colors.background },
  toolbar: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
    paddingBottom: spacing.md,
  },
  searchContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.white,
    borderRadius: radii.md,
    borderWidth: 1,
    borderColor: colors.border,
    paddingHorizontal: spacing.md,
    gap: spacing.sm,
  },
  searchInput: {
    flex: 1,
    paddingVertical: 10,
    color: colors.gray[900],
  },
  addButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.primary[600],
    paddingHorizontal: spacing.lg,
    paddingVertical: 10,
    borderRadius: radii.md,
    gap: spacing.xs,
  },
  addButtonText: { color: colors.white, fontWeight: '600' },
  cardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.sm,
  },
  jobNumber: {
    fontWeight: '600',
    color: colors.primary[600],
  },
  title: {
    fontWeight: '600',
    color: colors.gray[900],
    marginBottom: 4,
  },
  description: {
    color: colors.gray[500],
    marginBottom: spacing.md,
    lineHeight: 18,
  },
  progressContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
  },
  progressBar: {
    flex: 1,
    height: 5,
    backgroundColor: colors.gray[100],
    borderRadius: 3,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    backgroundColor: colors.primary[500],
    borderRadius: 3,
  },
  percentage: {
    fontWeight: '600',
    color: colors.gray[600],
    width: 36,
    textAlign: 'right',
  },
  emptyAction: {
    backgroundColor: colors.primary[600],
    borderRadius: radii.md,
    paddingHorizontal: spacing.lg,
    paddingVertical: 10,
  },
  emptyActionText: { color: colors.white, fontWeight: '600' },
});
