import { Alert, FlatList, Text, TouchableOpacity, View } from "react-native";
import { router } from "expo-router";
import { ScreenContainer } from "@/components/screen-container";
import { useStore } from "@/lib/store";
import { useColors } from "@/hooks/use-colors";
import {
  CATEGORY_DISPLAY,
  CATEGORY_ICONS,
  Reading,
  readingValueSummary,
  alertStyle,
} from "@/lib/health-data";

export default function RecentScreen() {
  const { readings, deleteReading } = useStore();
  const colors = useColors();
  const sorted = [...readings].reverse();

  function handleDelete(r: Reading) {
    Alert.alert(
      "Delete Reading",
      `Delete this reading?\n\n${r.date} ${r.time}  —  ${CATEGORY_DISPLAY[r.readingType] ?? r.readingType}\n${readingValueSummary(r)}`,
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Delete",
          style: "destructive",
          onPress: () => deleteReading(r.id),
        },
      ],
    );
  }

  function handleEdit(r: Reading) {
    router.push({
      pathname: `/entry/${r.readingType}` as any,
      params: { editId: r.id },
    });
  }

  return (
    <ScreenContainer>
      <View style={{ padding: 16, paddingBottom: 0 }}>
        <Text className="text-2xl font-bold text-foreground mb-1">Recent Readings</Text>
        <Text className="text-muted text-sm mb-4">
          {sorted.length} reading{sorted.length !== 1 ? "s" : ""} recorded
        </Text>
      </View>

      {sorted.length === 0 ? (
        <View style={{ flex: 1, alignItems: "center", justifyContent: "center", padding: 32 }}>
          <Text style={{ fontSize: 48, marginBottom: 12 }}>📋</Text>
          <Text style={{ color: colors.muted, textAlign: "center", fontSize: 15 }}>
            No readings yet. Add your first reading from the Add Reading tab.
          </Text>
        </View>
      ) : (
        <FlatList
          data={sorted}
          keyExtractor={(item) => item.id}
          contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 32 }}
          ItemSeparatorComponent={() => (
            <View style={{ height: 8 }} />
          )}
          renderItem={({ item }) => (
            <ReadingCard
              reading={item}
              colors={colors}
              onEdit={() => handleEdit(item)}
              onDelete={() => handleDelete(item)}
            />
          )}
        />
      )}
    </ScreenContainer>
  );
}

function ReadingCard({
  reading,
  colors,
  onEdit,
  onDelete,
}: {
  reading: Reading;
  colors: any;
  onEdit: () => void;
  onDelete: () => void;
}) {
  const { severity } = alertStyle(reading.alertStatus);
  const alertColor =
    severity === "Critical" ? colors.error :
    severity === "Warning"  ? colors.warning : colors.success;

  return (
    <View
      style={{
        backgroundColor: colors.surface,
        borderRadius: 14,
        padding: 14,
        borderWidth: 1,
        borderColor: colors.border,
      }}
    >
      <View style={{ flexDirection: "row", alignItems: "flex-start" }}>
        <Text style={{ fontSize: 26, marginRight: 12, marginTop: 2 }}>
          {CATEGORY_ICONS[reading.readingType] ?? "📋"}
        </Text>
        <View style={{ flex: 1 }}>
          <View style={{ flexDirection: "row", alignItems: "center", justifyContent: "space-between" }}>
            <Text style={{ color: colors.foreground, fontWeight: "700", fontSize: 14 }}>
              {CATEGORY_DISPLAY[reading.readingType] ?? reading.readingType}
            </Text>
            <Text style={{ color: alertColor, fontSize: 12, fontWeight: "600" }}>
              {reading.alertStatus || "OK"}
            </Text>
          </View>
          <Text style={{ color: colors.foreground, fontSize: 15, fontWeight: "700", marginTop: 4 }}>
            {readingValueSummary(reading)}
          </Text>
          <Text style={{ color: colors.muted, fontSize: 12, marginTop: 2 }}>
            {reading.date} {reading.time}
            {reading.context ? `  •  ${reading.context}` : ""}
            {reading.deviceMethod ? `  •  ${reading.deviceMethod}` : ""}
          </Text>
          {!!reading.notes && (
            <Text style={{ color: colors.muted, fontSize: 11, marginTop: 4 }} numberOfLines={2}>
              {reading.notes}
            </Text>
          )}
        </View>
      </View>

      <View style={{ flexDirection: "row", justifyContent: "flex-end", gap: 8, marginTop: 10 }}>
        <TouchableOpacity
          onPress={onEdit}
          style={{
            backgroundColor: colors.background,
            borderRadius: 8,
            paddingHorizontal: 14,
            paddingVertical: 7,
            borderWidth: 1,
            borderColor: colors.border,
          }}
        >
          <Text style={{ color: colors.primary, fontSize: 13, fontWeight: "600" }}>Edit</Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={onDelete}
          style={{
            backgroundColor: colors.background,
            borderRadius: 8,
            paddingHorizontal: 14,
            paddingVertical: 7,
            borderWidth: 1,
            borderColor: colors.border,
          }}
        >
          <Text style={{ color: colors.error, fontSize: 13, fontWeight: "600" }}>Delete</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}
