/**
 * Showing feedback form — star rating + notes.
 * Submitted after completing a showing.
 */

import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
} from 'react-native';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { ShowingsStackParamList } from '../../navigation/stacks/ShowingsStack';
import { useTheme } from '../../themes/ThemeProvider';
import { submitShowingFeedback } from '../../services/api';

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

export default function Feedback({ route, navigation }: Props) {
  const { theme } = useTheme();
  const { showingId } = route.params;
  const [rating, setRating] = useState(0);
  const [feedback, setFeedback] = useState('');
  const [saving, setSaving] = useState(false);

  const handleSubmit = async () => {
    if (rating === 0) {
      Alert.alert('Rating Required', 'Please select a star rating.');
      return;
    }

    setSaving(true);
    const res = await submitShowingFeedback(showingId, feedback, rating);
    setSaving(false);

    if (res.success) {
      Alert.alert('Submitted', 'Feedback recorded.', [
        { text: 'OK', onPress: () => navigation.goBack() },
      ]);
    } else {
      Alert.alert('Error', res.error ?? 'Failed to submit feedback');
    }
  };

  return (
    <KeyboardAvoidingView
      style={[styles.container, { backgroundColor: theme.colors.background }]}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ScrollView contentContainerStyle={styles.content}>
        <Text style={[styles.title, { color: theme.colors.text }]}>How was the showing?</Text>

        {/* Star Rating */}
        <View style={styles.stars}>
          {[1, 2, 3, 4, 5].map((star) => (
            <TouchableOpacity key={star} onPress={() => setRating(star)} style={styles.starBtn}>
              <Text style={[styles.star, { color: star <= rating ? theme.colors.accent : theme.colors.border }]}>
                {star <= rating ? '★' : '☆'}
              </Text>
            </TouchableOpacity>
          ))}
        </View>
        <Text style={[styles.ratingLabel, { color: theme.colors.textSecondary }]}>
          {rating === 0 ? 'Tap to rate' :
           rating === 1 ? 'Not interested' :
           rating === 2 ? 'Maybe' :
           rating === 3 ? 'Interested' :
           rating === 4 ? 'Very interested' :
           'Ready to make an offer'}
        </Text>

        {/* Feedback Text */}
        <Text style={[styles.label, { color: theme.colors.textSecondary }]}>Notes</Text>
        <TextInput
          style={[styles.textArea, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
          value={feedback}
          onChangeText={setFeedback}
          placeholder="Client feedback, property condition, follow-up needed..."
          placeholderTextColor={theme.colors.textSecondary}
          multiline
          numberOfLines={6}
          textAlignVertical="top"
        />

        {/* Quick Feedback Chips */}
        <Text style={[styles.label, { color: theme.colors.textSecondary }]}>Quick Tags</Text>
        <View style={styles.chipRow}>
          {[
            'Loved the kitchen',
            'Too small',
            'Great location',
            'Needs work',
            'Price too high',
            'Want to see again',
            'Making offer',
          ].map((tag) => (
            <TouchableOpacity
              key={tag}
              style={[styles.chip, {
                backgroundColor: feedback.includes(tag) ? theme.colors.primary : theme.colors.surface,
                borderColor: theme.colors.border,
              }]}
              onPress={() => {
                setFeedback((prev) =>
                  prev.includes(tag) ? prev.replace(tag, '').trim() : `${prev} ${tag}`.trim()
                );
              }}
            >
              <Text style={[styles.chipText, {
                color: feedback.includes(tag) ? '#FFF' : theme.colors.textSecondary,
              }]}>
                {tag}
              </Text>
            </TouchableOpacity>
          ))}
        </View>

        <TouchableOpacity
          style={[styles.submitBtn, { backgroundColor: theme.colors.primary, opacity: saving ? 0.6 : 1 }]}
          onPress={handleSubmit}
          disabled={saving}
        >
          <Text style={styles.submitBtnText}>{saving ? 'Submitting...' : 'Submit Feedback'}</Text>
        </TouchableOpacity>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  content: { padding: 24 },
  title: { fontSize: 22, fontWeight: '700', textAlign: 'center', marginBottom: 20 },
  stars: { flexDirection: 'row', justifyContent: 'center', gap: 12 },
  starBtn: { padding: 4 },
  star: { fontSize: 40 },
  ratingLabel: { textAlign: 'center', fontSize: 14, marginTop: 8, marginBottom: 24 },
  label: { fontSize: 13, fontWeight: '600', marginBottom: 6, marginTop: 16 },
  textArea: {
    height: 120,
    borderRadius: 10,
    borderWidth: 1,
    padding: 14,
    fontSize: 15,
    lineHeight: 22,
  },
  chipRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
  chip: { paddingHorizontal: 12, paddingVertical: 6, borderRadius: 20, borderWidth: 1 },
  chipText: { fontSize: 13 },
  submitBtn: {
    height: 50,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 28,
  },
  submitBtnText: { color: '#FFF', fontSize: 17, fontWeight: '700' },
});
