import { memo } from "react";
import { Text, View, TouchableOpacity } from "react-native";
import { Card, Divider } from "react-native-paper";

import { SearchResult } from "@/store/api/searchApi";
import { normalizeEnumLike } from "@/utils/formattingUtils";

interface ResultRowProps {
  item: SearchResult;
  expanded: boolean;
  onToggle: (id: string) => void;
}

const ResultRowComponent = ({ item, expanded, onToggle }: ResultRowProps) => {
  return (
    <Card className="mb-4 overflow-hidden">
      <TouchableOpacity onPress={() => onToggle(item.id)}>
        <View className="p-3">
          <Text className="font-semibold text-base" numberOfLines={1}>
            {item.title}
          </Text>
          {item.subtitle ? (
            <Text className="text-sm text-gray-600" numberOfLines={1}>
              {normalizeEnumLike(item.subtitle)}
            </Text>
          ) : null}
          {item.description ? (
            <Text className="text-xs text-gray-500" numberOfLines={2}>
              {normalizeEnumLike(item.description)}
            </Text>
          ) : null}
        </View>
      </TouchableOpacity>
      {expanded && (
        <View className="px-3 pb-3">
          <Divider />
          <View className="mt-3">
            <Text className="text-xs text-gray-500 mb-1">
              Type:{" "}
              {item.type.charAt(0).toUpperCase() +
                item.type.slice(1).toLowerCase()}
            </Text>
            {item.createdAt ? (
              <Text className="text-xs text-gray-500 mb-1">
                Created: {new Date(item.createdAt).toLocaleString()}
              </Text>
            ) : null}
            {item.meta ? (
              <>
                {item.type !== "todo" ? (
                  <>
                    {item.meta?.isLocked !== undefined ? (
                      <Text className="text-xs text-gray-500 mb-1">
                        Locked: {item.meta.isLocked ? "Yes" : "No"}
                      </Text>
                    ) : null}
                  </>
                ) : (
                  <>
                    {item.meta?.createdBy ? (
                      <Text className="text-xs text-gray-500 mb-1">
                        Created by: {item.meta.createdBy}
                      </Text>
                    ) : null}
                    {item.meta?.assignees ? (
                      <Text className="text-xs text-gray-500 mb-1">
                        Assignees: {item.meta.assignees}
                      </Text>
                    ) : null}
                  </>
                )}
              </>
            ) : null}
          </View>
        </View>
      )}
    </Card>
  );
};

export const ResultRow = memo(ResultRowComponent);
ResultRow.displayName = "ResultRow";
