import React, { useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Dimensions,
  Platform,
} from 'react-native';
import { Image } from 'expo-image';
import { MaterialIcons, Ionicons, Feather } from '@expo/vector-icons';
import { useTheme } from '../hooks/useTheme';
import { usePosts } from '../hooks/usePosts';
import { Post } from '../types';
import { SPACING, TYPOGRAPHY, LAYOUT } from '../constants/theme';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

interface PostCardProps {
  post: Post;
  onCommentPress: () => void;
  onSharePress: () => void;
}

export function PostCard({ post, onCommentPress, onSharePress }: PostCardProps) {
  const { colors } = useTheme();
  const { toggleLike, toggleBookmark, addSignal } = usePosts();
  const [currentImageIndex, setCurrentImageIndex] = useState(0);

  const handleLike = () => {
    toggleLike(post.id);
  };

  const handleBookmark = () => {
    toggleBookmark(post.id);
  };

  const handleYesSignal = () => {
    addSignal(post.id, 'yes');
  };

  const handleNoSignal = () => {
    addSignal(post.id, 'no');
  };

  return (
    <View style={[styles.container, { borderBottomColor: colors.border }]}>
      {/* Header */}
      <View style={styles.header}>
        <View style={styles.headerLeft}>
          <Image source={{ uri: post.user.avatar }} style={styles.avatar} />
          <View>
            <View style={styles.usernameRow}>
              <Text style={[styles.username, { color: colors.text }]}>
                {post.user.username}
              </Text>
              {post.user.isVerified && (
                <MaterialIcons
                  name="verified"
                  size={14}
                  color={colors.verified}
                  style={styles.verifiedBadge}
                />
              )}
              {post.user.isMonetized && (
                <Text style={[styles.monetizedBadge, { color: colors.monetized }]}>
                  $
                </Text>
              )}
            </View>
            {post.location && (
              <Text style={[styles.location, { color: colors.textSecondary }]}>
                {post.location}
              </Text>
            )}
          </View>
        </View>
        <TouchableOpacity>
          <Feather name="more-vertical" size={20} color={colors.text} />
        </TouchableOpacity>
      </View>

      {/* Image */}
      <View>
        <Image
          source={{ uri: post.media[currentImageIndex] }}
          style={styles.image}
          contentFit="cover"
        />
        {post.type === 'carousel' && post.media.length > 1 && (
          <View style={styles.carouselIndicator}>
            {post.media.map((_, index) => (
              <View
                key={index}
                style={[
                  styles.dot,
                  {
                    backgroundColor:
                      index === currentImageIndex ? colors.primary : colors.border,
                  },
                ]}
              />
            ))}
          </View>
        )}
      </View>

      {/* Actions */}
      <View style={styles.actions}>
        <View style={styles.actionsLeft}>
          <TouchableOpacity onPress={handleLike} style={styles.actionButton}>
            <Ionicons
              name={post.isLiked ? 'heart' : 'heart-outline'}
              size={26}
              color={post.isLiked ? colors.error : colors.text}
            />
          </TouchableOpacity>
          <TouchableOpacity onPress={onCommentPress} style={styles.actionButton}>
            <Ionicons name="chatbubble-outline" size={24} color={colors.text} />
          </TouchableOpacity>
          <TouchableOpacity onPress={onSharePress} style={styles.actionButton}>
            <Feather name="send" size={24} color={colors.text} />
          </TouchableOpacity>
        </View>
        <TouchableOpacity onPress={handleBookmark}>
          <Ionicons
            name={post.isBookmarked ? 'bookmark' : 'bookmark-outline'}
            size={24}
            color={colors.text}
          />
        </TouchableOpacity>
      </View>

      {/* Likes & Caption */}
      <View style={styles.content}>
        <Text style={[styles.likes, { color: colors.text }]}>
          {post.likesCount.toLocaleString()} likes
        </Text>
        <Text style={[styles.caption, { color: colors.text }]}>
          <Text style={styles.captionUsername}>{post.user.username}</Text>{' '}
          {post.caption}
        </Text>
        {post.commentsCount > 0 && (
          <TouchableOpacity onPress={onCommentPress}>
            <Text style={[styles.viewComments, { color: colors.textSecondary }]}>
              View all {post.commentsCount} comments
            </Text>
          </TouchableOpacity>
        )}
        <Text style={[styles.timestamp, { color: colors.textSecondary }]}>
          {formatTimestamp(post.timestamp)}
        </Text>
      </View>

      {/* Yes/No Signals */}
      <View style={[styles.signals, { borderTopColor: colors.border }]}>
        <TouchableOpacity
          style={[
            styles.signalButton,
            post.hasUserSignaled === 'yes' && {
              backgroundColor: colors.success + '20',
            },
          ]}
          onPress={handleYesSignal}
        >
          <Ionicons
            name="thumbs-up"
            size={18}
            color={
              post.hasUserSignaled === 'yes' ? colors.success : colors.textSecondary
            }
          />
          <Text
            style={[
              styles.signalText,
              {
                color:
                  post.hasUserSignaled === 'yes' ? colors.success : colors.textSecondary,
              },
            ]}
          >
            Yes {post.yesCount}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[
            styles.signalButton,
            post.hasUserSignaled === 'no' && {
              backgroundColor: colors.error + '20',
            },
          ]}
          onPress={handleNoSignal}
        >
          <Ionicons
            name="thumbs-down"
            size={18}
            color={post.hasUserSignaled === 'no' ? colors.error : colors.textSecondary}
          />
          <Text
            style={[
              styles.signalText,
              {
                color:
                  post.hasUserSignaled === 'no' ? colors.error : colors.textSecondary,
              },
            ]}
          >
            No {post.noCount}
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

function formatTimestamp(date: Date): string {
  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);

  if (diffInSeconds < 60) return `${diffInSeconds}s ago`;
  if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}m ago`;
  if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}h ago`;
  if (diffInSeconds < 604800) return `${Math.floor(diffInSeconds / 86400)}d ago`;
  return `${Math.floor(diffInSeconds / 604800)}w ago`;
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'transparent',
    borderBottomWidth: 1,
    marginBottom: SPACING.sm,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.md,
  },
  headerLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  avatar: {
    width: 32,
    height: 32,
    borderRadius: 16,
    marginRight: SPACING.sm,
  },
  usernameRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  username: {
    fontSize: TYPOGRAPHY.sizes.sm,
    fontWeight: TYPOGRAPHY.weights.semibold,
  },
  verifiedBadge: {
    marginLeft: 4,
  },
  monetizedBadge: {
    marginLeft: 4,
    fontSize: TYPOGRAPHY.sizes.base,
    fontWeight: TYPOGRAPHY.weights.bold,
  },
  location: {
    fontSize: TYPOGRAPHY.sizes.xs,
  },
  image: {
    width: Platform.select({ web: '100%', default: SCREEN_WIDTH }),
    height: Platform.select({ web: 600, default: SCREEN_WIDTH }),
  },
  carouselIndicator: {
    position: 'absolute',
    bottom: SPACING.md,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'center',
    gap: 4,
  },
  dot: {
    width: 6,
    height: 6,
    borderRadius: 3,
  },
  actions: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.sm,
  },
  actionsLeft: {
    flexDirection: 'row',
  },
  actionButton: {
    marginRight: SPACING.lg,
  },
  content: {
    paddingHorizontal: SPACING.lg,
  },
  likes: {
    fontSize: TYPOGRAPHY.sizes.sm,
    fontWeight: TYPOGRAPHY.weights.semibold,
    marginBottom: SPACING.xs,
  },
  caption: {
    fontSize: TYPOGRAPHY.sizes.sm,
    lineHeight: 18,
    marginBottom: SPACING.xs,
  },
  captionUsername: {
    fontWeight: TYPOGRAPHY.weights.semibold,
  },
  viewComments: {
    fontSize: TYPOGRAPHY.sizes.sm,
    marginBottom: SPACING.xs,
  },
  timestamp: {
    fontSize: TYPOGRAPHY.sizes.xs,
    marginBottom: SPACING.sm,
  },
  signals: {
    flexDirection: 'row',
    paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.md,
    borderTopWidth: 1,
    gap: SPACING.sm,
  },
  signalButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: SPACING.md,
    paddingVertical: SPACING.xs,
    borderRadius: 16,
    gap: 4,
  },
  signalText: {
    fontSize: TYPOGRAPHY.sizes.xs,
    fontWeight: TYPOGRAPHY.weights.medium,
  },
});