import React, { useEffect } from 'react';
import {
  View,
  Text,
  ScrollView,
  Linking,
  Platform,
} from 'react-native';
import { RouteProp, useRoute } from '@react-navigation/native';
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 } from '@components';
import { LeadDetailHeader } from '../../components/leadDetailHeader/leadDetailHeader';

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

export const LeadDetailsScreen = () => {
  const route = useRoute<LeadDetailsRouteProp>();
  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 email press
  const handleEmailPress = () => {
    if (lead.email) {
      Linking.openURL(`mailto:${lead.email}`).catch(err =>
        console.error('Error opening email:', err),
      );
    }
  };

  // Handle phone press
  const handlePhonePress = () => {
    if (lead.phonenumber) {
      const phoneUrl =
        Platform.OS === 'ios'
          ? `telprompt:${lead.phonenumber}`
          : `tel:${lead.phonenumber}`;
      Linking.openURL(phoneUrl).catch(err =>
        console.error('Error opening phone:', err),
      );
    }
  };

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

  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}
        onPhonePress={handlePhonePress}
      />
    </ScrollView>
  );
};
