import {
  EmptyState,
  ResourceList,
  ResourceItem,
  InlineStack,
  Avatar,
  BlockStack,
  Text,
  Badge
} from "@shopify/polaris";

export function ReviewList({ reviews }) {
  if (reviews.length === 0) {
    return (
      <EmptyState
        heading="Manage your customer reviews"
        action={{ content: "View Online Store", url: "https://admin.shopify.com", external: true }}
        image="https://cdn.shopify.com/s/files/1/0262/4071/2726/files/emptystate-files.png"
      >
        <p>Track your customer feedback in one place. Your store has no reviews yet.</p>
      </EmptyState>
    );
  }

  return (
    <ResourceList
      resourceName={{ singular: 'review', plural: 'reviews' }}
      items={reviews}
      renderItem={(item) => {
        const { id, customer_name, content, rating, product_id } = item;
        const productIdNum = product_id?.split('/').pop() || '';

        return (
          <ResourceItem
            id={id}
            onClick={() => {
              window.open(`shopify:admin/products/${productIdNum}`, "_top");
            }}
            accessibilityLabel={`View details for ${customer_name}`}
          >
            <InlineStack align="space-between" blockAlign="center">
              <InlineStack gap="400" blockAlign="center">
                <Avatar size="md" initials={customer_name ? customer_name.charAt(0).toUpperCase() : 'A'} name={customer_name || 'Anonymous'} />
                <BlockStack gap="100">
                  <Text variant="bodyMd" fontWeight="bold" as="h3">
                    {customer_name || 'Anonymous'}
                  </Text>
                  <Text variant="bodySm" as="p" tone="subdued">
                    {content}
                  </Text>
                </BlockStack>
              </InlineStack>
              
              <InlineStack gap="300" blockAlign="center">
                <Badge tone="success">
                  {rating || "5"} / 5 ★
                </Badge>
                <Text variant="bodySm" as="span" tone="subdued">
                  Product ID: {productIdNum}
                </Text>
              </InlineStack>
            </InlineStack>
          </ResourceItem>
        );
      }}
    />
  );
}
