import { ScrollView, Text, TouchableOpacity, View, Alert } 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 {
  DASHBOARD_ORDER,
  CATEGORY_DISPLAY,
  CATEGORY_ICONS,
  CATEGORY_UNIT,
  Reading,
  readingValueSummary,
  alertStyle,
  metricForTrend,
  trendDirection,
  agpStatusAndSummary,
} from "@/lib/health-data";

export default function DashboardScreen() {
  const {
    readings,
    profile,
    agpThresholds,
    deleteReading,
    clearAllReadings,
    getLatestHeartRateReading,
    getAgpSummaryFromReadings,
  } = useStore();
  const colors = useColors();

  // Build latest-by-category and history-by-category maps
  const latestByCat: Record<string, Reading> = {};
  const historyByCat: Record<string, Reading[]> = {};
  for (const r of readings) {
    const cat = r.readingType;
    historyByCat[cat] = historyByCat[cat] ?? [];
    historyByCat[cat].push(r);
    latestByCat[cat] = r;
  }

  const agpSummary = getAgpSummaryFromReadings();
  const last3 = [...readings].reverse().slice(0, 3);
  const recent10 = [...readings].reverse().slice(0, 10);

  function handleCardPress(cat: string) {
    if (cat === "AGP") {
      router.push("/entry/AGP" as any);
    } else {
      router.push(`/entry/${cat}` as any);
    }
  }

  function handleClearAll() {
    Alert.alert(
      "Clear All Data",
      "This will permanently delete all readings. Are you sure?",
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Delete All",
          style: "destructive",
          onPress: () => clearAllReadings(),
        },
      ],
    );
  }

  function handleDeleteRecent(id: string, label: string) {
    Alert.alert("Delete Reading", `Delete this reading?\n\n${label}`, [
      { text: "Cancel", style: "cancel" },
      {
        text: "Delete",
        style: "destructive",
        onPress: () => deleteReading(id),
      },
    ]);
  }

  return (
    <ScreenContainer>
      <ScrollView
        contentContainerStyle={{ padding: 16, paddingBottom: 32 }}
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <View className="flex-row items-center justify-between mb-4">
          <View>
            <Text className="text-2xl font-bold text-foreground">Dashboard</Text>
            {profile?.name ? (
              <Text className="text-muted text-sm">{profile.name}</Text>
            ) : null}
          </View>
          <TouchableOpacity
            onPress={handleClearAll}
            style={{
              backgroundColor: colors.surface,
              borderColor: colors.border,
              borderWidth: 1,
              borderRadius: 8,
              paddingHorizontal: 10,
              paddingVertical: 6,
            }}
          >
            <Text style={{ color: colors.error, fontSize: 12, fontWeight: "600" }}>
              Clear Data
            </Text>
          </TouchableOpacity>
        </View>

        {/* Metric Cards Grid */}
        <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 10, marginBottom: 20 }}>
          {DASHBOARD_ORDER.map((cat) => (
            <MetricCard
              key={cat}
              cat={cat}
              latestByCat={latestByCat}
              historyByCat={historyByCat}
              agpSummary={agpSummary}
              agpThresholds={agpThresholds}
              getLatestHeartRateReading={getLatestHeartRateReading}
              colors={colors}
              onPress={() => handleCardPress(cat)}
            />
          ))}
        </View>

        {/* Last 3 Readings */}
        <View
          className="rounded-2xl p-4 mb-4 border border-border"
          style={{ backgroundColor: colors.surface }}
        >
          <Text className="text-foreground font-semibold text-base mb-3">
            Last 3 Readings
          </Text>
          {last3.length === 0 ? (
            <Text className="text-muted text-sm">No readings recorded yet.</Text>
          ) : (
            last3.map((r) => (
              <ReadingRow key={r.id} reading={r} colors={colors} />
            ))
          )}
        </View>

        {/* Manage Recent */}
        <View
          className="rounded-2xl p-4 border border-border"
          style={{ backgroundColor: colors.surface }}
        >
          <Text className="text-foreground font-semibold text-base mb-3">
            Manage Recent (last 10)
          </Text>
          {recent10.length === 0 ? (
            <Text className="text-muted text-sm">No readings recorded yet.</Text>
          ) : (
            recent10.map((r) => {
              const label = `${r.date} ${r.time}  ${CATEGORY_ICONS[r.readingType] ?? ""}  ${CATEGORY_DISPLAY[r.readingType] ?? r.readingType}  ${readingValueSummary(r)}`;
              return (
                <View
                  key={r.id}
                  style={{
                    flexDirection: "row",
                    alignItems: "center",
                    paddingVertical: 8,
                    borderBottomWidth: 0.5,
                    borderBottomColor: colors.border,
                  }}
                >
                  <View style={{ flex: 1 }}>
                    <Text style={{ color: colors.foreground, fontSize: 13 }} numberOfLines={1}>
                      {CATEGORY_ICONS[r.readingType] ?? ""} {CATEGORY_DISPLAY[r.readingType] ?? r.readingType}
                    </Text>
                    <Text style={{ color: colors.muted, fontSize: 12 }}>
                      {r.date} {r.time}  •  {readingValueSummary(r)}
                    </Text>
                  </View>
                  <TouchableOpacity
                    onPress={() =>
                      router.push({
                        pathname: `/entry/${r.readingType}` as any,
                        params: { editId: r.id },
                      })
                    }
                    style={{
                      paddingHorizontal: 10,
                      paddingVertical: 6,
                      backgroundColor: colors.background,
                      borderRadius: 6,
                      marginRight: 6,
                    }}
                  >
                    <Text style={{ color: colors.primary, fontSize: 12, fontWeight: "600" }}>
                      Edit
                    </Text>
                  </TouchableOpacity>
                  <TouchableOpacity
                    onPress={() => handleDeleteRecent(r.id, label)}
                    style={{
                      paddingHorizontal: 10,
                      paddingVertical: 6,
                      backgroundColor: colors.background,
                      borderRadius: 6,
                    }}
                  >
                    <Text style={{ color: colors.error, fontSize: 12, fontWeight: "600" }}>
                      Del
                    </Text>
                  </TouchableOpacity>
                </View>
              );
            })
          )}
        </View>
      </ScrollView>
    </ScreenContainer>
  );
}

// ─── Metric Card ──────────────────────────────────────────────────────────────

function MetricCard({
  cat,
  latestByCat,
  historyByCat,
  agpSummary,
  agpThresholds,
  getLatestHeartRateReading,
  colors,
  onPress,
}: any) {
  const cardWidth = "47%";

  if (cat === "AGP") {
    const agpStatus = agpStatusAndSummary(agpSummary, agpThresholds);
    const statusColor =
      agpStatus.color === "ok"   ? colors.success :
      agpStatus.color === "warn" ? colors.warning :
      agpStatus.color === "crit" ? colors.error   : colors.muted;

    return (
      <TouchableOpacity
        onPress={onPress}
        style={{
          width: cardWidth,
          backgroundColor: colors.surface,
          borderRadius: 16,
          padding: 14,
          borderWidth: 1,
          borderColor: colors.border,
        }}
      >
        <Text style={{ fontSize: 22 }}>{CATEGORY_ICONS[cat]}</Text>
        <Text style={{ color: colors.muted, fontSize: 11, fontWeight: "600", marginTop: 4 }}>
          {CATEGORY_DISPLAY[cat]}
        </Text>
        <Text style={{ color: colors.muted, fontSize: 10 }}>{CATEGORY_UNIT[cat]}</Text>
        <Text
          style={{ color: statusColor, fontSize: 15, fontWeight: "700", marginTop: 8 }}
          numberOfLines={1}
        >
          {agpStatus.label}
        </Text>
        {agpSummary ? (
          <Text style={{ color: colors.muted, fontSize: 10, marginTop: 2 }} numberOfLines={2}>
            {agpSummary.tir ? `TIR ${agpSummary.tir}%` : ""}
            {agpSummary.gmi ? `  GMI ${agpSummary.gmi}%` : ""}
          </Text>
        ) : (
          <Text style={{ color: colors.muted, fontSize: 10, marginTop: 2 }}>
            Tap to import PDF
          </Text>
        )}
        <Text style={{ color: statusColor, fontSize: 11, marginTop: 4 }} numberOfLines={2}>
          {agpStatus.short}
        </Text>
      </TouchableOpacity>
    );
  }

  const row = cat === "Heart Rate" ? getLatestHeartRateReading() : latestByCat[cat];
  const hist = historyByCat[cat] ?? [];
  const curr = hist.length > 0 ? metricForTrend(hist[hist.length - 1]) : null;
  const prev = hist.length > 1 ? metricForTrend(hist[hist.length - 2]) : null;
  const { arrow, word } = trendDirection(cat, curr, prev);

  const trendColor =
    word === "Improving" ? colors.success :
    word === "Worsening" ? colors.error   : colors.muted;

  let alertColor = colors.muted;
  let alertLabel = "Not Recorded";
  if (row) {
    const { severity } = alertStyle(row.alertStatus);
    alertColor =
      severity === "Critical" ? colors.error :
      severity === "Warning"  ? colors.warning : colors.success;
    alertLabel = row.alertStatus || "OK";
  }

  return (
    <TouchableOpacity
      onPress={onPress}
      style={{
        width: cardWidth,
        backgroundColor: colors.surface,
        borderRadius: 16,
        padding: 14,
        borderWidth: 1,
        borderColor: colors.border,
      }}
    >
      <Text style={{ fontSize: 22 }}>{CATEGORY_ICONS[cat]}</Text>
      <Text style={{ color: colors.muted, fontSize: 11, fontWeight: "600", marginTop: 4 }}>
        {CATEGORY_DISPLAY[cat]}
      </Text>
      <Text style={{ color: colors.muted, fontSize: 10 }}>{CATEGORY_UNIT[cat]}</Text>
      <Text
        style={{
          color: row ? colors.foreground : colors.muted,
          fontSize: 15,
          fontWeight: "700",
          marginTop: 8,
        }}
        numberOfLines={1}
      >
        {row ? readingValueSummary(row) : "No data"}
      </Text>
      <Text style={{ color: colors.muted, fontSize: 10, marginTop: 2 }}>
        {row
          ? `${row.date} ${row.time}${cat === "Heart Rate" && row.readingType === "SpO2" ? "  • from SpO2" : ""}`
          : "No reading yet"}
      </Text>
      <Text style={{ color: trendColor, fontSize: 12, fontWeight: "600", marginTop: 4 }}>
        {arrow} {word}
      </Text>
      <Text style={{ color: alertColor, fontSize: 11, marginTop: 2 }} numberOfLines={1}>
        {alertLabel}
      </Text>
    </TouchableOpacity>
  );
}

// ─── Reading Row ──────────────────────────────────────────────────────────────

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

  return (
    <View
      style={{
        paddingVertical: 8,
        borderBottomWidth: 0.5,
        borderBottomColor: colors.border,
      }}
    >
      <View style={{ flexDirection: "row", alignItems: "center", justifyContent: "space-between" }}>
        <Text style={{ color: colors.foreground, fontSize: 13, fontWeight: "600" }}>
          {CATEGORY_ICONS[reading.readingType] ?? ""} {CATEGORY_DISPLAY[reading.readingType] ?? reading.readingType}
        </Text>
        <Text style={{ color: alertColor, fontSize: 11, fontWeight: "600" }}>
          {reading.alertStatus || "OK"}
        </Text>
      </View>
      <Text style={{ color: colors.muted, fontSize: 12, marginTop: 2 }}>
        {readingValueSummary(reading)}  •  {reading.date} {reading.time}
      </Text>
    </View>
  );
}
