import React, { useEffect } from 'react';
import {
  View,
  Text,
  ScrollView,
  Linking,
  Platform,
} from 'react-native';
import { RouteProp, useRoute, useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useTheme } from '@theme';
import { useAppDispatch, useAppSelector, RootState } from '@store';
import { getLeadDetails } from './thunk';
import { getStyles } from './leadDetails.styles';
import { LeadsStackParamList } from '../../navigation/leadsStack';
import { Loader, LeadDetailHeader, ActionCard } from '@components';
import { handleEmailPress, handlePhonePress } from '@utils';
import { route as routes } from '@utils';

type LeadDetailsRouteProp = RouteProp<LeadsStackParamList, 'leadDetails'>;
type LeadDetailsNavigationProp = NativeStackNavigationProp<
  LeadsStackParamList,
  'leadDetails'
>;

export const LeadDetailsScreen = () => {
  const route = useRoute<LeadDetailsRouteProp>();
  const navigation = useNavigation<LeadDetailsNavigationProp>();
  const dispatch = useAppDispatch();
  const { theme: colors } = useTheme();
  const styles = getStyles(colors);

  // Get lead ID from route params
  const leadId = route.params?.lead?.id;

  // Get data from Redux store
  const { item: lead, loading, error } = useAppSelector(
    (state: RootState) => state.leadDetails,
  );
  const user_data = useAppSelector((state: RootState) => state.auth.user_data);

  // Fetch lead details on mount
  useEffect(() => {
    if (leadId && user_data?.staffid) {
      dispatch(getLeadDetails({ leadId, staffid: user_data.staffid }));
    }
  }, [dispatch, leadId, user_data]);

  // Show loader while loading
  if (loading) {
    return <Loader message="Loading lead details..." />;
  }

  // Show error if any
  if (error) {
    return (
      <View style={styles.container}>
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', padding: 32 }}>
          <Text style={{ color: '#EF4444', fontSize: 14, textAlign: 'center' }}>
            {error}
          </Text>
        </View>
      </View>
    );
  }

  if (!lead) {
    return (
      <View style={styles.container}>
        <Text style={styles.infoValue}>No lead data available</Text>
      </View>
    );
  }

  // Handle status press (for future status change functionality)
  const handleStatusPress = () => {
    // TODO: Show status list modal/picker
    console.log('Status pressed - show status list');
  };

  // Proposals handlers
  const handleAddProposal = () => {
    // TODO: Navigate to add proposal screen
    navigation.navigate(routes.leadProposals, { leadId: lead.id });
  };

  const handleViewAllProposals = () => {
      console.log('view Proposal pressed');
  };

  // Tasks handlers
  const handleAddTask = () => {
    // TODO: Navigate to add task screen
    navigation.navigate(routes.leadTasks, { leadId: lead.id });
  };

  const handleViewAllTasks = () => {
    console.log('view Add Task pressed');
  };

  // Notes handlers
  const handleAddNote = () => {
    // TODO: Navigate to add note screen
    navigation.navigate(routes.leadNotes, { leadId: lead.id });
  };

  const handleViewAllNotes = () => {
    console.log('view Add Note pressed');
  };

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.scrollContent}>
      {/* Header with Avatar */}
      <LeadDetailHeader
        name={lead.name}
        company={lead.company}
        email={lead.email}
        phonenumber={lead.phonenumber}
        statusName={lead.status_name || lead.status}
        statusColor={lead.color}
        onStatusPress={handleStatusPress}
        onEmailPress={() => handleEmailPress(lead.email)}
        onPhonePress={() => handlePhonePress(lead.phonenumber)}
      />

      {/* Action Cards Section */}
      <View style={styles.cardsContainer}>
        <ActionCard
          title="Proposals"
          icon="document-text-outline"
          count={0}
          onAddPress={handleAddProposal}
          onViewAllPress={handleViewAllProposals}
        />

        <ActionCard
          title="Tasks"
          icon="checkbox-outline"
          count={0}
          onAddPress={handleAddTask}
          onViewAllPress={handleViewAllTasks}
        />

        <ActionCard
          title="Notes"
          icon="create-outline"
          count={0}
          onAddPress={handleAddNote}
          onViewAllPress={handleViewAllNotes}
        />
      </View>
    </ScrollView>
  );
};
