/**
 * Showing detail — instructions, directions, status controls, feedback.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
} from 'react-native';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { ShowingsStackParamList } from '../../navigation/stacks/ShowingsStack';
import { useTheme } from '../../themes/ThemeProvider';
import { getShowings, updateShowingStatus, Showing } from '../../services/api';
import { openNavigationApp } from '../../services/location';

type Props = NativeStackScreenProps<ShowingsStackParamList, 'ShowingDetail'>;

export default function ShowingDetail({ route, navigation }: Props) {
  const { theme } = useTheme();
  const { id } = route.params;
  const [showing, setShowing] = useState<Showing | null>(null);

  const load = useCallback(async () => {
    const res = await getShowings({ id: String(id) });
    if (res.success && res.data) {
      const list = res.data as Showing[];
      setShowing(list[0] ?? null);
    }
  }, [id]);

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

  const handleStatusChange = async (status: Showing['status']) => {
    if (!showing) return;
    await updateShowingStatus(showing.id, status);
    setShowing({ ...showing, status });
  };

  const handleConfirm = () => handleStatusChange('confirmed');
  const handleCancel = () => {
    Alert.alert('Cancel Showing', 'Are you sure?', [
      { text: 'No', style: 'cancel' },
      { text: 'Yes, Cancel', style: 'destructive', onPress: () => handleStatusChange('cancelled') },
    ]);
  };
  const handleComplete = () => {
    handleStatusChange('completed');
    if (showing) {
      navigation.navigate('Feedback', { showingId: showing.id });
    }
  };

  const handleNavigate = () => {
    if (showing?.latitude && showing?.longitude) {
      openNavigationApp({ latitude: showing.latitude, longitude: showing.longitude });
    } else {
      Alert.alert('No Location', 'This showing does not have GPS coordinates.');
    }
  };

  const formatTime = (time: string): string => {
    try {
      const [hours, minutes] = time.split(':').map(Number);
      const ampm = hours >= 12 ? 'PM' : 'AM';
      return `${hours % 12 || 12}:${minutes.toString().padStart(2, '0')} ${ampm}`;
    } catch {
      return time;
    }
  };

  const statusConfig: Record<string, { color: string; label: string }> = {
    requested: { color: theme.colors.warning, label: 'Requested' },
    confirmed: { color: theme.colors.success, label: 'Confirmed' },
    cancelled: { color: theme.colors.error, label: 'Cancelled' },
    completed: { color: theme.colors.info, label: 'Completed' },
  };

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

  const config = statusConfig[showing.status] ?? statusConfig.requested;

  return (
    <ScrollView style={[styles.container, { backgroundColor: theme.colors.background }]}>
      {/* Status Banner */}
      <View style={[styles.statusBanner, { backgroundColor: config.color }]}>
        <Text style={styles.statusText}>{config.label}</Text>
      </View>

      {/* Main Info */}
      <View style={[styles.card, { backgroundColor: theme.colors.card }]}>
        <Text style={[styles.propertyId, { color: theme.colors.text }]}>
          Property #{showing.property_id}
        </Text>
        <View style={styles.dateTimeRow}>
          <Text style={[styles.date, { color: theme.colors.textSecondary }]}>
            {new Date(showing.showing_date + 'T12:00:00').toLocaleDateString('en-US', {
              weekday: 'long',
              month: 'long',
              day: 'numeric',
            })}
          </Text>
          <Text style={[styles.time, { color: theme.colors.primary }]}>
            {formatTime(showing.showing_time)}
          </Text>
        </View>
      </View>

      {/* Instructions */}
      {showing.instructions && (
        <View style={[styles.card, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.cardTitle, { color: theme.colors.text }]}>Instructions</Text>
          <Text style={[styles.instructions, { color: theme.colors.textSecondary }]}>
            {showing.instructions}
          </Text>
        </View>
      )}

      {/* Lockbox */}
      {showing.lockbox_code && (
        <View style={[styles.card, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.cardTitle, { color: theme.colors.text }]}>Access</Text>
          <View style={[styles.lockboxDisplay, { backgroundColor: theme.colors.inputBg }]}>
            <Text style={[styles.lockboxLabel, { color: theme.colors.textSecondary }]}>
              Lockbox Code
            </Text>
            <Text style={[styles.lockboxCode, { color: theme.colors.primary }]}>
              {showing.lockbox_code}
            </Text>
          </View>
        </View>
      )}

      {/* Feedback */}
      {showing.feedback && (
        <View style={[styles.card, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.cardTitle, { color: theme.colors.text }]}>Feedback</Text>
          {showing.rating && (
            <Text style={[styles.rating, { color: theme.colors.accent }]}>
              {'★'.repeat(showing.rating)}{'☆'.repeat(5 - showing.rating)}
            </Text>
          )}
          <Text style={[styles.feedbackText, { color: theme.colors.textSecondary }]}>
            {showing.feedback}
          </Text>
        </View>
      )}

      {/* Actions */}
      <View style={styles.actions}>
        <TouchableOpacity
          style={[styles.actionBtn, { backgroundColor: theme.colors.info }]}
          onPress={handleNavigate}
        >
          <Text style={styles.actionBtnText}>Navigate</Text>
        </TouchableOpacity>

        {showing.status === 'requested' && (
          <>
            <TouchableOpacity
              style={[styles.actionBtn, { backgroundColor: theme.colors.success }]}
              onPress={handleConfirm}
            >
              <Text style={styles.actionBtnText}>Confirm</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.actionBtn, { backgroundColor: theme.colors.error }]}
              onPress={handleCancel}
            >
              <Text style={styles.actionBtnText}>Decline</Text>
            </TouchableOpacity>
          </>
        )}

        {showing.status === 'confirmed' && (
          <>
            <TouchableOpacity
              style={[styles.actionBtn, { backgroundColor: theme.colors.success }]}
              onPress={handleComplete}
            >
              <Text style={styles.actionBtnText}>Complete & Feedback</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.actionBtn, { backgroundColor: theme.colors.error }]}
              onPress={handleCancel}
            >
              <Text style={styles.actionBtnText}>Cancel</Text>
            </TouchableOpacity>
          </>
        )}

        {showing.status === 'completed' && !showing.feedback && (
          <TouchableOpacity
            style={[styles.actionBtn, { backgroundColor: theme.colors.accent }]}
            onPress={() => navigation.navigate('Feedback', { showingId: showing.id })}
          >
            <Text style={styles.actionBtnText}>Add Feedback</Text>
          </TouchableOpacity>
        )}
      </View>

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

const styles = StyleSheet.create({
  loading: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  container: { flex: 1 },
  statusBanner: {
    paddingVertical: 10,
    alignItems: 'center',
  },
  statusText: { color: '#FFF', fontWeight: '700', fontSize: 15 },
  card: {
    margin: 16,
    marginBottom: 0,
    borderRadius: 12,
    padding: 16,
  },
  propertyId: { fontSize: 20, fontWeight: '700', marginBottom: 8 },
  dateTimeRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  date: { fontSize: 15 },
  time: { fontSize: 18, fontWeight: '700' },
  cardTitle: { fontSize: 16, fontWeight: '700', marginBottom: 8 },
  instructions: { fontSize: 14, lineHeight: 20 },
  lockboxDisplay: {
    padding: 16,
    borderRadius: 10,
    alignItems: 'center',
  },
  lockboxLabel: { fontSize: 12, marginBottom: 4 },
  lockboxCode: { fontSize: 28, fontWeight: '800', fontFamily: 'Courier', letterSpacing: 4 },
  rating: { fontSize: 20, marginBottom: 8 },
  feedbackText: { fontSize: 14, lineHeight: 20 },
  actions: {
    padding: 16,
    gap: 10,
  },
  actionBtn: {
    height: 48,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
  },
  actionBtnText: { color: '#FFF', fontSize: 16, fontWeight: '700' },
  bottomPad: { height: 40 },
});
