/**
 * Client detail — full timeline, lead score, interactions, contact info.
 * FUB replacement: everything about one contact.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Linking,
  Alert,
  RefreshControl,
} from 'react-native';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { ClientsStackParamList } from '../../navigation/stacks/ClientsStack';
import { useTheme } from '../../themes/ThemeProvider';
import { getClient, getClientTimeline, logInteraction, Client } from '../../services/api';

type Props = NativeStackScreenProps<ClientsStackParamList, 'ClientDetail'>;

interface Interaction {
  id: number;
  type: string;
  notes: string;
  duration_minutes: number | null;
  created_at: string;
}

export default function ClientDetail({ route, navigation }: Props) {
  const { theme } = useTheme();
  const { id } = route.params;
  const [client, setClient] = useState<Client | null>(null);
  const [timeline, setTimeline] = useState<Interaction[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    const [clientRes, timelineRes] = await Promise.allSettled([
      getClient(id),
      getClientTimeline(id),
    ]);

    if (clientRes.status === 'fulfilled' && clientRes.value.data) {
      setClient(clientRes.value.data);
      navigation.setOptions({
        title: `${clientRes.value.data.first_name} ${clientRes.value.data.last_name}`,
      });
    }

    if (timelineRes.status === 'fulfilled' && timelineRes.value.data) {
      setTimeline(timelineRes.value.data as Interaction[]);
    }
  }, [id, navigation]);

  useEffect(() => {
    load();
  }, [load]);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await load();
    setRefreshing(false);
  }, [load]);

  const handleCall = () => {
    if (client?.phone) {
      Linking.openURL(`tel:${client.phone}`);
    }
  };

  const handleEmail = () => {
    if (client?.email) {
      Linking.openURL(`mailto:${client.email}`);
    }
  };

  const handleLogCall = () => {
    Alert.prompt?.(
      'Log Call',
      'Enter call notes',
      async (notes: string) => {
        if (notes) {
          await logInteraction({
            client_id: id,
            type: 'call',
            notes,
            duration_minutes: 5,
          });
          await load();
        }
      }
    ) ??
      Alert.alert('Log Call', 'Call logged for this client');
  };

  const lifecycleColor = (lc: string): string => {
    switch (lc) {
      case 'lead': return theme.colors.info;
      case 'active': return theme.colors.success;
      case 'closed': return theme.colors.accent;
      case 'repeat': return '#8B5CF6';
      default: return theme.colors.textSecondary;
    }
  };

  const formatDate = (ts: string): string => {
    try {
      return new Date(ts).toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
        hour: 'numeric',
        minute: '2-digit',
      });
    } catch {
      return ts;
    }
  };

  const interactionIcon = (type: string): string => {
    switch (type) {
      case 'call': return '📞';
      case 'email': return '✉️';
      case 'meeting': return '🤝';
      case 'text': return '💬';
      case 'showing': return '🏠';
      case 'note': return '📝';
      default: return '•';
    }
  };

  if (!client) {
    return (
      <View style={[styles.loading, { backgroundColor: theme.colors.background }]}>
        <Text style={{ color: theme.colors.textSecondary }}>Loading...</Text>
      </View>
    );
  }

  return (
    <ScrollView
      style={[styles.container, { backgroundColor: theme.colors.background }]}
      refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />}
    >
      {/* Contact Header */}
      <View style={[styles.header, { backgroundColor: theme.colors.card }]}>
        <View style={[styles.avatar, { backgroundColor: theme.colors.primary }]}>
          <Text style={styles.avatarText}>
            {(client.first_name?.[0] ?? '').toUpperCase()}
            {(client.last_name?.[0] ?? '').toUpperCase()}
          </Text>
        </View>
        <Text style={[styles.name, { color: theme.colors.text }]}>
          {client.first_name} {client.last_name}
        </Text>
        <View style={[styles.lifecycleBadge, { backgroundColor: lifecycleColor(client.lifecycle) + '20' }]}>
          <Text style={[styles.lifecycleText, { color: lifecycleColor(client.lifecycle) }]}>
            {client.lifecycle.toUpperCase()}
          </Text>
        </View>

        {/* Lead Score */}
        {client.lead_score > 0 && (
          <View style={styles.scoreRow}>
            <Text style={[styles.scoreLabel, { color: theme.colors.textSecondary }]}>Lead Score</Text>
            <View style={styles.scoreBar}>
              <View
                style={[
                  styles.scoreFill,
                  {
                    width: `${Math.min(client.lead_score, 100)}%`,
                    backgroundColor:
                      client.lead_score >= 70 ? theme.colors.success :
                      client.lead_score >= 40 ? theme.colors.warning : theme.colors.error,
                  },
                ]}
              />
            </View>
            <Text style={[styles.scoreValue, { color: theme.colors.text }]}>{client.lead_score}</Text>
          </View>
        )}

        {/* Action Buttons */}
        <View style={styles.actions}>
          <TouchableOpacity style={[styles.actionBtn, { backgroundColor: theme.colors.success }]} onPress={handleCall}>
            <Text style={styles.actionIcon}>📞</Text>
            <Text style={styles.actionLabel}>Call</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.actionBtn, { backgroundColor: theme.colors.info }]} onPress={handleEmail}>
            <Text style={styles.actionIcon}>✉️</Text>
            <Text style={styles.actionLabel}>Email</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.actionBtn, { backgroundColor: theme.colors.accent }]} onPress={handleLogCall}>
            <Text style={styles.actionIcon}>📝</Text>
            <Text style={styles.actionLabel}>Log Call</Text>
          </TouchableOpacity>
        </View>
      </View>

      {/* Contact Info */}
      <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>Contact Info</Text>
        {client.email && (
          <View style={styles.infoRow}>
            <Text style={[styles.infoLabel, { color: theme.colors.textSecondary }]}>Email</Text>
            <Text style={[styles.infoValue, { color: theme.colors.text }]}>{client.email}</Text>
          </View>
        )}
        {client.phone && (
          <View style={styles.infoRow}>
            <Text style={[styles.infoLabel, { color: theme.colors.textSecondary }]}>Phone</Text>
            <Text style={[styles.infoValue, { color: theme.colors.text }]}>{client.phone}</Text>
          </View>
        )}
        {client.source && (
          <View style={styles.infoRow}>
            <Text style={[styles.infoLabel, { color: theme.colors.textSecondary }]}>Source</Text>
            <Text style={[styles.infoValue, { color: theme.colors.text }]}>{client.source}</Text>
          </View>
        )}
        {client.notes && (
          <View style={styles.infoRow}>
            <Text style={[styles.infoLabel, { color: theme.colors.textSecondary }]}>Notes</Text>
            <Text style={[styles.infoValue, { color: theme.colors.text }]}>{client.notes}</Text>
          </View>
        )}
      </View>

      {/* Timeline */}
      <View style={[styles.section, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>
          Activity ({timeline.length})
        </Text>
        {timeline.length === 0 ? (
          <Text style={[styles.emptyTimeline, { color: theme.colors.textSecondary }]}>
            No interactions yet
          </Text>
        ) : (
          timeline.map((item) => (
            <View key={item.id} style={[styles.timelineItem, { borderLeftColor: theme.colors.border }]}>
              <View style={styles.timelineHeader}>
                <Text style={styles.timelineIcon}>{interactionIcon(item.type)}</Text>
                <Text style={[styles.timelineType, { color: theme.colors.text }]}>
                  {item.type.charAt(0).toUpperCase() + item.type.slice(1)}
                </Text>
                {item.duration_minutes && (
                  <Text style={[styles.timelineDuration, { color: theme.colors.textSecondary }]}>
                    {item.duration_minutes}min
                  </Text>
                )}
                <Text style={[styles.timelineDate, { color: theme.colors.textSecondary }]}>
                  {formatDate(item.created_at)}
                </Text>
              </View>
              {item.notes && (
                <Text style={[styles.timelineNotes, { color: theme.colors.textSecondary }]}>
                  {item.notes}
                </Text>
              )}
            </View>
          ))
        )}
      </View>

      <View style={styles.bottomPad} />
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  loading: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  container: { flex: 1 },
  header: {
    alignItems: 'center',
    padding: 24,
    marginBottom: 8,
  },
  avatar: {
    width: 72,
    height: 72,
    borderRadius: 36,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 12,
  },
  avatarText: { color: '#FFF', fontSize: 24, fontWeight: '700' },
  name: { fontSize: 22, fontWeight: '700', marginBottom: 8 },
  lifecycleBadge: {
    paddingHorizontal: 12,
    paddingVertical: 4,
    borderRadius: 12,
    marginBottom: 16,
  },
  lifecycleText: { fontSize: 12, fontWeight: '700' },
  scoreRow: {
    flexDirection: 'row',
    alignItems: 'center',
    width: '100%',
    paddingHorizontal: 20,
    marginBottom: 16,
    gap: 8,
  },
  scoreLabel: { fontSize: 12, width: 70 },
  scoreBar: {
    flex: 1,
    height: 8,
    backgroundColor: '#E5E7EB',
    borderRadius: 4,
    overflow: 'hidden',
  },
  scoreFill: { height: '100%', borderRadius: 4 },
  scoreValue: { fontSize: 14, fontWeight: '700', width: 30, textAlign: 'right' },
  actions: {
    flexDirection: 'row',
    gap: 12,
  },
  actionBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderRadius: 10,
    gap: 6,
  },
  actionIcon: { fontSize: 16 },
  actionLabel: { color: '#FFF', fontWeight: '600', fontSize: 14 },
  section: {
    marginBottom: 8,
    padding: 16,
  },
  sectionTitle: { fontSize: 17, fontWeight: '700', marginBottom: 12 },
  infoRow: {
    flexDirection: 'row',
    paddingVertical: 8,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#E5E7EB',
  },
  infoLabel: { width: 70, fontSize: 13 },
  infoValue: { flex: 1, fontSize: 14 },
  emptyTimeline: { fontSize: 14, paddingVertical: 12 },
  timelineItem: {
    borderLeftWidth: 2,
    paddingLeft: 14,
    paddingBottom: 16,
    marginLeft: 8,
  },
  timelineHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
  },
  timelineIcon: { fontSize: 14 },
  timelineType: { fontSize: 14, fontWeight: '600' },
  timelineDuration: { fontSize: 12 },
  timelineDate: { fontSize: 12, marginLeft: 'auto' },
  timelineNotes: { fontSize: 13, marginTop: 4, lineHeight: 18 },
  bottomPad: { height: 40 },
});
