import React, { useState } from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Share, Alert } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { ColorPalette, IdentificationResult } from '../types';
import { useColors } from '../constants/Colors';
import { SafeImage } from './SafeImage';

interface ResultCardProps {
  result: IdentificationResult;
  imageUri: string;
  onSave: () => void;
  onClose: () => void;
  t: any;
  isDark: boolean;
  colorPalette: ColorPalette;
  isGuest?: boolean;
}

export const ResultCard: React.FC<ResultCardProps> = ({
  result,
  imageUri,
  onSave,
  onClose,
  t,
  isDark,
  colorPalette,
  isGuest = false,
}) => {
  const colors = useColors(isDark, colorPalette);
  const insets = useSafeAreaInsets();
  const [showDetails, setShowDetails] = useState(false);

  const handleShare = async () => {
    try {
      await Share.share({
        message: `I just identified a ${result.name} (${result.botanicalName}) with ${Math.round(result.confidence * 100)}% confidence using GreenLens!`,
      });
    } catch (error: any) {
      Alert.alert('Error', error.message);
    }
  };

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={['top', 'bottom']}>
      {/* Header */}
      <View style={[styles.header, { paddingTop: insets.top + 8 }]}>
        <TouchableOpacity
          style={[styles.headerBtn, { backgroundColor: colors.heroButton, borderColor: colors.heroButtonBorder }]}
          onPress={onClose}
        >
          <Ionicons name="arrow-back" size={20} color={colors.text} />
        </TouchableOpacity>
        <View style={[styles.headerBadge, { backgroundColor: colors.heroButton, borderColor: colors.heroButtonBorder }]}>
          <Text style={[styles.headerBadgeText, { color: colors.text }]}>{t.result}</Text>
        </View>
        <TouchableOpacity
          style={[styles.headerBtn, { backgroundColor: colors.heroButton, borderColor: colors.heroButtonBorder }]}
          onPress={handleShare}
        >
          <Ionicons name="share-outline" size={20} color={colors.text} />
        </TouchableOpacity>
      </View>

      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={[
          styles.scrollContent,
          { paddingTop: insets.top + 76, paddingBottom: insets.bottom + 36 },
        ]}
      >
        {/* Hero Image */}
        <View style={[styles.heroContainer, { shadowColor: colors.overlayStrong }]}>
          <SafeImage uri={imageUri} style={styles.heroImage} />
          <View style={[styles.confidenceBadge, { backgroundColor: colors.heroButton }]}>
            <Ionicons name="checkmark-circle" size={14} color={colors.success} />
            <Text style={[styles.confidenceText, { color: colors.success }]}>
              {Math.round(result.confidence * 100)}% {t.match}
            </Text>
          </View>
        </View>

        {/* Info */}
        <Text style={[styles.plantName, { color: colors.text }]}>{result.name}</Text>
        <Text style={[styles.botanical, { color: colors.textMuted }]}>{result.botanicalName}</Text>
        <Text style={[styles.description, { color: colors.textSecondary }]}>
          {result.description || t.noDescription}
        </Text>

        {/* Care Check */}
        <View style={styles.careHeader}>
          <Text style={[styles.sectionTitle, { color: colors.text }]}>{t.careCheck}</Text>
          <TouchableOpacity onPress={() => setShowDetails(!showDetails)}>
            <Text style={[styles.detailsToggle, { color: colors.primaryDark }]}>
              {showDetails ? t.hideDetails : t.showDetails}
            </Text>
          </TouchableOpacity>
        </View>

        <View style={styles.careGrid}>
          {[
            { icon: 'water' as const, label: t.water, value: t.waterEveryXDays.replace('{0}', result.careInfo.waterIntervalDays.toString()), color: colors.info, bg: colors.infoSoft },
            { icon: 'sunny' as const, label: t.light, value: (result.careInfo.light && result.careInfo.light !== 'Unknown') ? result.careInfo.light : t.unknown, color: colors.warning, bg: colors.warningSoft },
            { icon: 'thermometer' as const, label: t.temp, value: (result.careInfo.temp && result.careInfo.temp !== 'Unknown') ? result.careInfo.temp : t.unknown, color: colors.danger, bg: colors.dangerSoft },
          ].map((item) => (
            <View key={item.label} style={[styles.careCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
              <View style={[styles.careIcon, { backgroundColor: item.bg }]}>
                <Ionicons name={item.icon} size={16} color={item.color} />
              </View>
              <Text style={[styles.careLabel, { color: colors.textMuted }]}>{item.label}</Text>
              <Text style={[styles.careValue, { color: colors.text }]}>{item.value}</Text>
            </View>
          ))}
        </View>

        {showDetails && (
          <View style={[styles.detailsBox, { backgroundColor: colors.surfaceMuted, borderColor: colors.border }]}>
            <Text style={[styles.detailsTitle, { color: colors.textSecondary }]}>{t.detailedCare}</Text>
            {[
              { text: t.careTextWater.replace('{0}', result.careInfo.waterIntervalDays.toString()), color: colors.success },
              { text: t.careTextLight.replace('{0}', (result.careInfo.light && result.careInfo.light !== 'Unknown') ? result.careInfo.light : t.unknown), color: colors.warning },
              { text: t.careTextTemp.replace('{0}', (result.careInfo.temp && result.careInfo.temp !== 'Unknown') ? result.careInfo.temp : t.unknown), color: colors.danger },
            ].map((item, i) => (
              <View key={i} style={styles.detailRow}>
                <View style={[styles.detailDot, { backgroundColor: item.color }]} />
                <Text style={[styles.detailText, { color: colors.textSecondary }]}>{item.text}</Text>
              </View>
            ))}
          </View>
        )}

        {/* Save */}
        <View style={styles.localInfo}>
          <View style={[styles.localIcon, { borderColor: colors.borderStrong }]} />
          <Text style={[styles.localText, { color: colors.textMuted }]}>{t.dataSavedLocally}</Text>
        </View>

        <TouchableOpacity
          style={[
            styles.saveBtn,
            { backgroundColor: colors.primary, shadowColor: colors.primary },
          ]}
          activeOpacity={0.8}
          onPress={onSave}
        >
          <Ionicons name={isGuest ? "person-add" : "checkmark-circle"} size={16} color={colors.onPrimary} />
          <Text style={[styles.saveBtnText, { color: colors.onPrimary }]}>
            {isGuest ? t.registerToSave : t.addToPlants}
          </Text>
        </TouchableOpacity>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1 },
  header: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    zIndex: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 20,
  },
  headerBtn: {
    borderRadius: 20,
    padding: 8,
    borderWidth: 1,
  },
  headerBadge: {
    borderRadius: 20,
    paddingHorizontal: 12,
    paddingVertical: 4,
    borderWidth: 1,
  },
  headerBadgeText: { fontWeight: '700', fontSize: 13 },
  scrollContent: { paddingHorizontal: 16 },
  heroContainer: {
    width: '100%',
    aspectRatio: 4 / 3,
    borderRadius: 24,
    overflow: 'hidden',
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.15,
    shadowRadius: 8,
    elevation: 6,
  },
  heroImage: { width: '100%', height: '100%', resizeMode: 'cover' },
  confidenceBadge: {
    position: 'absolute',
    bottom: 14,
    left: 14,
    borderRadius: 20,
    paddingHorizontal: 10,
    paddingVertical: 6,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
  },
  confidenceText: { fontSize: 11, fontWeight: '700' },
  plantName: { fontSize: 28, fontWeight: '700', marginBottom: 2 },
  botanical: { fontSize: 13, fontStyle: 'italic', marginBottom: 14 },
  description: { fontSize: 13, lineHeight: 20, marginBottom: 24 },
  careHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-end',
    marginBottom: 12,
  },
  sectionTitle: { fontSize: 16, fontWeight: '700' },
  detailsToggle: { fontSize: 10, fontWeight: '700', textTransform: 'uppercase', letterSpacing: 0.5 },
  careGrid: { flexDirection: 'row', gap: 10, marginBottom: 20 },
  careCard: {
    flex: 1,
    alignItems: 'center',
    padding: 12,
    borderRadius: 18,
    borderWidth: 1,
    gap: 6,
  },
  careIcon: { width: 32, height: 32, borderRadius: 16, justifyContent: 'center', alignItems: 'center' },
  careLabel: { fontSize: 10, fontWeight: '500' },
  careValue: {
    width: '100%',
    fontSize: 11,
    lineHeight: 14,
    fontWeight: '700',
    textAlign: 'center',
    flexShrink: 1,
  },
  detailsBox: {
    borderRadius: 18,
    borderWidth: 1,
    padding: 16,
    marginBottom: 20,
    gap: 10,
  },
  detailsTitle: { fontSize: 11, fontWeight: '700', textTransform: 'uppercase', letterSpacing: 0.5 },
  detailRow: { flexDirection: 'row', alignItems: 'flex-start', gap: 10 },
  detailDot: { width: 6, height: 6, borderRadius: 3, marginTop: 6 },
  detailText: { fontSize: 13, flex: 1 },
  localInfo: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', gap: 6, marginBottom: 12 },
  localIcon: { width: 12, height: 12, borderRadius: 2, borderWidth: 1, borderColor: '#d6d3d1' },
  localText: { fontSize: 11 },
  saveBtn: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 8,
    backgroundColor: '#4ade80',
    paddingVertical: 16,
    borderRadius: 14,
    shadowColor: '#4ade80',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 6,
  },
  saveBtnText: { fontWeight: '700', fontSize: 14 },
});
