import { useEffect, useRef, useState } from "react";
import {
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { router, useLocalSearchParams } from "expo-router";
import * as DocumentPicker from "expo-document-picker";
import { extractText, isAvailable } from "expo-pdf-text-extract";
import { ScreenContainer } from "@/components/screen-container";
import { useStore } from "@/lib/store";
import { useColors } from "@/hooks/use-colors";
import {
  ReadingType,
  Reading,
  CATEGORY_DISPLAY,
  CATEGORY_ICONS,
  CATEGORY_UNIT,
  CONTEXTS,
  METHODS,
  GUIDANCE,
  REQUIRED_MAP,
  computeAlert,
  alertStyle,
  kgToLb,
  fToC,
  agpStatusAndSummary,
} from "@/lib/health-data";

// ─── Field config per category ────────────────────────────────────────────────

interface FieldDef {
  key: keyof Reading;
  label: string;
  placeholder: string;
  keyboardType?: "numeric" | "default";
  required?: boolean;
  readOnly?: boolean;
  hint?: string;
}

const FIELDS: Record<ReadingType, FieldDef[]> = {
  BP: [
    { key: "systolicBP",  label: "Systolic (mmHg) ★",  placeholder: "e.g. 120", keyboardType: "numeric", required: true },
    { key: "diastolicBP", label: "Diastolic (mmHg) ★", placeholder: "e.g. 80",  keyboardType: "numeric", required: true },
  ],
  "Heart Rate": [
    { key: "heartRate", label: "Heart Rate (BPM) ★", placeholder: "e.g. 72", keyboardType: "numeric", required: true },
  ],
  SpO2: [
    { key: "spo2",      label: "Blood Oxygen (%) ★", placeholder: "e.g. 98", keyboardType: "numeric", required: true },
    { key: "heartRate", label: "Heart Rate (BPM)",   placeholder: "e.g. 72", keyboardType: "numeric" },
  ],
  Glucose: [
    { key: "bloodGlucose", label: "Blood Glucose (mg/dL) ★", placeholder: "e.g. 95", keyboardType: "numeric", required: true },
  ],
  Weight: [
    { key: "weightKg", label: "Weight (kg) ★",       placeholder: "e.g. 70.5", keyboardType: "numeric", required: true },
    { key: "weightLb", label: "Weight (lb)  — auto", placeholder: "auto-calculated", readOnly: true },
  ],
  Temperature: [
    { key: "temperatureF", label: "Temperature (°F) ★",       placeholder: "e.g. 98.6", keyboardType: "numeric", required: true },
    { key: "temperatureC", label: "Temperature (°C)  — auto", placeholder: "auto-calculated", readOnly: true },
  ],
  HRV: [
    { key: "hrv", label: "HRV (ms) ★", placeholder: "e.g. 55", keyboardType: "numeric", required: true },
  ],
  Sleep: [
    { key: "sleepHours", label: "Sleep Duration (hrs) ★", placeholder: "e.g. 7.5", keyboardType: "numeric", required: true },
  ],
};

// ─── Screen ───────────────────────────────────────────────────────────────────

export default function EntryScreen() {
  const { category, editId } = useLocalSearchParams<{ category: string; editId?: string }>();
  const { readings, saveReading, updateReading, agpThresholds, profile } = useStore();
  const colors = useColors();

  const cat = category as ReadingType;
  const isAGP = category === "AGP";

  // Find existing reading if editing
  const existingReading = editId ? readings.find((r) => r.id === editId) ?? null : null;

  const now = new Date();
  const todayDate = now.toISOString().slice(0, 10);
  const todayTime = now.toTimeString().slice(0, 5);

  // Form state
  const [fields, setFields] = useState<Record<string, string>>(() => {
    if (existingReading) {
      const init: Record<string, string> = {};
      for (const f of FIELDS[cat] ?? []) {
        const val = existingReading[f.key];
        init[f.key] = val != null ? String(val) : "";
      }
      return init;
    }
    return {};
  });
  const [date, setDate]       = useState(existingReading?.date ?? todayDate);
  const [time, setTime]       = useState(existingReading?.time ?? todayTime);
  const [context, setContext] = useState(existingReading?.context ?? "");
  const [method, setMethod]   = useState(existingReading?.deviceMethod ?? "Manual");
  const [notes, setNotes]     = useState(existingReading?.notes ?? "");
  const [alertPreview, setAlertPreview] = useState<string | null>(null);
  const [saveStatus, setSaveStatus]     = useState<string | null>(null);
  const [importing, setImporting]       = useState(false);

  const isEditing = !!existingReading;

  // Auto-calc derived fields
  useEffect(() => {
    if (cat === "Weight") {
      const kg = parseFloat(fields.weightKg ?? "");
      if (!isNaN(kg)) {
        setFields((prev) => ({ ...prev, weightLb: String(kgToLb(kg)) }));
      }
    }
    if (cat === "Temperature") {
      const f = parseFloat(fields.temperatureF ?? "");
      if (!isNaN(f)) {
        setFields((prev) => ({ ...prev, temperatureC: String(fToC(f)) }));
      }
    }
  }, [fields.weightKg, fields.temperatureF]);

  // Live alert preview
  useEffect(() => {
    if (isAGP) return;
    const partial: Partial<Reading> = {};
    for (const f of FIELDS[cat] ?? []) {
      const val = parseFloat(fields[f.key] ?? "");
      if (!isNaN(val)) (partial as any)[f.key] = val;
    }
    const alert = computeAlert(partial);
    setAlertPreview(alert);
  }, [fields]);

  if (isAGP) {
    return <AgpImportScreen colors={colors} agpThresholds={agpThresholds} profile={profile} />;
  }

  const fieldDefs = FIELDS[cat] ?? [];
  const displayName = CATEGORY_DISPLAY[cat] ?? cat;
  const icon = CATEGORY_ICONS[cat] ?? "📋";
  const unit = CATEGORY_UNIT[cat] ?? "";
  const guidance = GUIDANCE[cat] ?? "";

  function handleFieldChange(key: string, value: string) {
    setFields((prev) => ({ ...prev, [key]: value }));
  }

  function buildReadingData(): Partial<Reading> & { readingType: ReadingType } {
    const data: any = {
      readingType: cat,
      date,
      time,
      context,
      deviceMethod: method,
      notes,
      patientName: profile?.name ?? "",
    };
    for (const f of fieldDefs) {
      if (f.readOnly) continue;
      const raw = fields[f.key] ?? "";
      if (raw.trim() !== "") {
        const num = parseFloat(raw);
        data[f.key] = isNaN(num) ? raw : num;
      }
    }
    return data;
  }

  async function handleSave() {
    const data = buildReadingData();
    const required = REQUIRED_MAP[cat] ?? [];
    const missing = required.filter((k) => {
      const val = (data as any)[k];
      return val == null || String(val).trim() === "";
    });
    if (missing.length > 0) {
      Alert.alert("Required Fields", `Please fill in: ${missing.join(", ")}`);
      return;
    }

    try {
      if (isEditing && existingReading) {
        const updated: Reading = {
          ...existingReading,
          ...data,
          alertStatus: computeAlert(data),
        } as Reading;
        await updateReading(updated);
        setSaveStatus(`✓ Updated  ${date} ${time}`);
      } else {
        const saved = await saveReading(data);
        setSaveStatus(`✓ Saved  ${saved.date} ${saved.time}  |  ${saved.alertStatus}`);
      }
      Alert.alert("Saved", isEditing ? "Reading updated." : "Reading saved.", [
        {
          text: "OK",
          onPress: () => router.replace("/(tabs)"),
        },
      ]);
    } catch (e: any) {
      Alert.alert("Error", `Could not save reading.\n\n${e?.message ?? e}`);
    }
  }

  const alertInfo = alertPreview ? alertStyle(alertPreview) : null;
  const alertColor =
    alertInfo?.severity === "Critical" ? colors.error :
    alertInfo?.severity === "Warning"  ? colors.warning : colors.success;

  return (
    <ScreenContainer>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={{ flex: 1 }}
      >
        {/* Header */}
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            paddingHorizontal: 16,
            paddingTop: 12,
            paddingBottom: 8,
            borderBottomWidth: 0.5,
            borderBottomColor: colors.border,
          }}
        >
          <TouchableOpacity
            onPress={() => router.back()}
            style={{
              marginRight: 12,
              backgroundColor: colors.surface,
              borderRadius: 8,
              paddingHorizontal: 10,
              paddingVertical: 6,
            }}
          >
            <Text style={{ color: colors.primary, fontSize: 14, fontWeight: "600" }}>← Back</Text>
          </TouchableOpacity>
          <Text style={{ fontSize: 22, marginRight: 8 }}>{icon}</Text>
          <View style={{ flex: 1 }}>
            <Text style={{ color: colors.foreground, fontSize: 17, fontWeight: "700" }}>
              {isEditing ? `Edit ${displayName}` : `New ${displayName}`}
            </Text>
            <Text style={{ color: colors.muted, fontSize: 12 }}>{unit}</Text>
          </View>
          <TouchableOpacity
            onPress={handleSave}
            style={{
              backgroundColor: colors.primary,
              borderRadius: 10,
              paddingHorizontal: 16,
              paddingVertical: 8,
            }}
          >
            <Text style={{ color: "#fff", fontWeight: "700", fontSize: 14 }}>
              {isEditing ? "Update" : "Save"}
            </Text>
          </TouchableOpacity>
        </View>

        <ScrollView
          contentContainerStyle={{ padding: 16, paddingBottom: 40 }}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          {/* Guidance */}
          <View
            style={{
              backgroundColor: colors.surface,
              borderRadius: 12,
              padding: 12,
              marginBottom: 16,
              borderWidth: 1,
              borderColor: colors.border,
            }}
          >
            <Text style={{ color: colors.muted, fontSize: 13 }}>{guidance}</Text>
          </View>

          {/* Metric fields */}
          <View
            style={{
              backgroundColor: colors.surface,
              borderRadius: 14,
              padding: 14,
              marginBottom: 14,
              borderWidth: 1,
              borderColor: colors.border,
            }}
          >
            <Text style={{ color: colors.foreground, fontWeight: "700", fontSize: 15, marginBottom: 12 }}>
              Reading Details
            </Text>
            {fieldDefs.map((f) => (
              <FieldInput
                key={String(f.key)}
                def={f}
                value={fields[f.key] ?? ""}
                onChange={(v) => handleFieldChange(String(f.key), v)}
                colors={colors}
              />
            ))}
          </View>

          {/* Context / metadata */}
          <View
            style={{
              backgroundColor: colors.surface,
              borderRadius: 14,
              padding: 14,
              marginBottom: 14,
              borderWidth: 1,
              borderColor: colors.border,
            }}
          >
            <Text style={{ color: colors.foreground, fontWeight: "700", fontSize: 15, marginBottom: 12 }}>
              Entry Context
            </Text>
            <MetaRow label="Date" colors={colors}>
              <TextInput
                value={date}
                onChangeText={setDate}
                placeholder="YYYY-MM-DD"
                placeholderTextColor={colors.muted}
                style={inputStyle(colors)}
              />
            </MetaRow>
            <MetaRow label="Time" colors={colors}>
              <TextInput
                value={time}
                onChangeText={setTime}
                placeholder="HH:MM"
                placeholderTextColor={colors.muted}
                style={inputStyle(colors)}
              />
            </MetaRow>
            <MetaRow label="Context" colors={colors}>
              <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                <View style={{ flexDirection: "row", gap: 6 }}>
                  {CONTEXTS.filter(Boolean).map((c) => (
                    <TouchableOpacity
                      key={c}
                      onPress={() => setContext(c === context ? "" : c)}
                      style={{
                        backgroundColor: context === c ? colors.primary : colors.background,
                        borderRadius: 8,
                        paddingHorizontal: 10,
                        paddingVertical: 6,
                        borderWidth: 1,
                        borderColor: context === c ? colors.primary : colors.border,
                      }}
                    >
                      <Text
                        style={{
                          color: context === c ? "#fff" : colors.muted,
                          fontSize: 12,
                          fontWeight: "600",
                        }}
                      >
                        {c}
                      </Text>
                    </TouchableOpacity>
                  ))}
                </View>
              </ScrollView>
            </MetaRow>
            <MetaRow label="Device / Method" colors={colors}>
              <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                <View style={{ flexDirection: "row", gap: 6 }}>
                  {METHODS.filter(Boolean).map((m) => (
                    <TouchableOpacity
                      key={m}
                      onPress={() => setMethod(m === method ? "" : m)}
                      style={{
                        backgroundColor: method === m ? colors.primary : colors.background,
                        borderRadius: 8,
                        paddingHorizontal: 10,
                        paddingVertical: 6,
                        borderWidth: 1,
                        borderColor: method === m ? colors.primary : colors.border,
                      }}
                    >
                      <Text
                        style={{
                          color: method === m ? "#fff" : colors.muted,
                          fontSize: 12,
                          fontWeight: "600",
                        }}
                      >
                        {m}
                      </Text>
                    </TouchableOpacity>
                  ))}
                </View>
              </ScrollView>
            </MetaRow>
          </View>

          {/* Notes */}
          <View
            style={{
              backgroundColor: colors.surface,
              borderRadius: 14,
              padding: 14,
              marginBottom: 14,
              borderWidth: 1,
              borderColor: colors.border,
            }}
          >
            <Text style={{ color: colors.foreground, fontWeight: "700", fontSize: 15, marginBottom: 8 }}>
              Notes
            </Text>
            <TextInput
              value={notes}
              onChangeText={setNotes}
              placeholder="Optional notes…"
              placeholderTextColor={colors.muted}
              multiline
              numberOfLines={4}
              style={{
                ...inputStyle(colors),
                height: 90,
                textAlignVertical: "top",
              }}
            />
          </View>

          {/* Alert preview */}
          {alertPreview && (
            <View
              style={{
                backgroundColor: colors.surface,
                borderRadius: 12,
                padding: 12,
                marginBottom: 14,
                borderWidth: 1,
                borderColor: colors.border,
                flexDirection: "row",
                alignItems: "center",
                gap: 8,
              }}
            >
              <Text style={{ color: colors.muted, fontSize: 13 }}>Alert Preview:</Text>
              <Text style={{ color: alertColor, fontSize: 13, fontWeight: "700" }}>
                {alertPreview}
              </Text>
            </View>
          )}

          {/* Save status */}
          {saveStatus && (
            <View
              style={{
                backgroundColor: colors.surface,
                borderRadius: 12,
                padding: 12,
                marginBottom: 14,
                borderWidth: 1,
                borderColor: colors.border,
              }}
            >
              <Text style={{ color: colors.success, fontSize: 13 }}>{saveStatus}</Text>
            </View>
          )}

          {/* Bottom save button */}
          <TouchableOpacity
            onPress={handleSave}
            style={{
              backgroundColor: colors.primary,
              borderRadius: 14,
              paddingVertical: 16,
              alignItems: "center",
              marginTop: 4,
            }}
          >
            <Text style={{ color: "#fff", fontSize: 16, fontWeight: "700" }}>
              {isEditing ? `Update ${displayName}` : `Save ${displayName}`}
            </Text>
          </TouchableOpacity>

          {/* Clear form */}
          <TouchableOpacity
            onPress={() => {
              setFields({});
              setContext("");
              setMethod("Manual");
              setNotes("");
              setAlertPreview(null);
              setSaveStatus(null);
            }}
            style={{
              borderRadius: 14,
              paddingVertical: 12,
              alignItems: "center",
              marginTop: 8,
              borderWidth: 1,
              borderColor: colors.border,
            }}
          >
            <Text style={{ color: colors.muted, fontSize: 14 }}>Clear Form</Text>
          </TouchableOpacity>
        </ScrollView>
      </KeyboardAvoidingView>
    </ScreenContainer>
  );
}

// ─── Field Input ──────────────────────────────────────────────────────────────

function FieldInput({
  def,
  value,
  onChange,
  colors,
}: {
  def: FieldDef;
  value: string;
  onChange: (v: string) => void;
  colors: any;
}) {
  return (
    <View style={{ marginBottom: 14 }}>
      <Text
        style={{
          color: def.required ? colors.warning : colors.muted,
          fontSize: 12,
          fontWeight: "600",
          marginBottom: 4,
        }}
      >
        {def.label}
      </Text>
      <TextInput
        value={value}
        onChangeText={onChange}
        placeholder={def.placeholder}
        placeholderTextColor={colors.muted}
        keyboardType={def.keyboardType ?? "default"}
        editable={!def.readOnly}
        style={{
          ...inputStyle(colors),
          opacity: def.readOnly ? 0.6 : 1,
        }}
      />
    </View>
  );
}

function MetaRow({
  label,
  children,
  colors,
}: {
  label: string;
  children: React.ReactNode;
  colors: any;
}) {
  return (
    <View style={{ marginBottom: 12 }}>
      <Text style={{ color: colors.muted, fontSize: 12, fontWeight: "600", marginBottom: 4 }}>
        {label}
      </Text>
      {children}
    </View>
  );
}

function inputStyle(colors: any) {
  return {
    backgroundColor: colors.background,
    color: colors.foreground,
    borderColor: colors.border,
    borderWidth: 1,
    borderRadius: 10,
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 15,
  };
}

// ─── AGP Import Screen ────────────────────────────────────────────────────────

function AgpImportScreen({
  colors,
  agpThresholds,
  profile,
}: {
  colors: any;
  agpThresholds: any;
  profile: any;
}) {
  const { saveReading, getAgpSummaryFromReadings } = useStore();
  const [importing, setImporting] = useState(false);
  const [result, setResult]       = useState<string | null>(null);
  const agpSummary = getAgpSummaryFromReadings();
  const agpStatus  = agpStatusAndSummary(agpSummary, agpThresholds);

  const statusColor =
    agpStatus.color === "ok"   ? colors.success :
    agpStatus.color === "warn" ? colors.warning :
    agpStatus.color === "crit" ? colors.error   : colors.muted;

  async function handleImport() {
    try {
      setImporting(true);

      // Check if native PDF extraction is available (requires dev/production build, not Expo Go)
      if (!isAvailable()) {
        Alert.alert(
          "PDF Import Not Available",
          "PDF import requires a full app build. It is not available in Expo Go preview mode. Please use the published APK.",
        );
        setImporting(false);
        return;
      }

      const res = await DocumentPicker.getDocumentAsync({
        type: "application/pdf",
        copyToCacheDirectory: true,
      });
      if (res.canceled || !res.assets?.[0]) {
        setImporting(false);
        return;
      }
      const asset = res.assets[0];
      const uri = asset.uri;

      // Use native PDF text extraction (PDFBox on Android, PDFKit on iOS)
      let pdfText: string;
      try {
        pdfText = await extractText(uri);
      } catch (extractErr: any) {
        Alert.alert(
          "PDF Read Error",
          `Could not read PDF text.\n\n${extractErr?.message ?? extractErr}\n\nMake sure this is a digital LibreView PDF (not a scanned image).`,
        );
        setImporting(false);
        return;
      }

      // ── Extract key AGP summary statistics ──────────────────────────────────
      const find = (pattern: RegExp): string | undefined => {
        const m = pdfText.match(pattern);
        return m?.[1];
      };

      const avg     = find(/Average Glucose\s+(\d{2,3})\s*mg\/dL/);
      const gmi     = find(/Glucose Management Indicator \(GMI\)\s+([\d.]+)%/);
      const varVal  = find(/Glucose Variability\s+([\d.]+)%/);
      // TIR: LibreView shows "Target Range 70 - 180 mg/dL\nNN%" or "NN % in target"
      const tir     = find(/Target Range\s+\d+\s*-\s*\d+\s*mg\/dL\s+(\d{1,3})%/) ??
                      find(/%(\s+in\s+target\s+)(\d{1,3})%/);

      // ── Extract report date range ────────────────────────────────────────────
      const dateRangeMatch = pdfText.match(
        /([A-Za-z]+\s+\d{1,2},\s+\d{4})\s*-\s*([A-Za-z]+\s+\d{1,2},\s+\d{4})/
      );

      let reportStart: Date | null = null;
      let reportEnd:   Date | null = null;
      if (dateRangeMatch) {
        try {
          reportStart = new Date(dateRangeMatch[1].trim());
          reportEnd   = new Date(dateRangeMatch[2].trim());
        } catch { /* ignore parse errors */ }
      }

      // ── Extract daily glucose values from Monthly Summary page ───────────────
      // Strategy: find the Monthly Summary section, extract all "NNN mg/dL" values
      // in order, then pair them with dates starting from report_start.
      // LibreView Monthly Summary lists each day's average glucose in calendar order.
      const monthlySectionMatch = pdfText.match(/Monthly Summary[\s\S]*?(?=SOURCES:|$)/);
      const monthlySection = monthlySectionMatch?.[0] ?? "";

      // Extract month/year from Monthly Summary header
      const monthYearMatch = monthlySection.match(/Monthly Summary\s+([A-Za-z]+)\s+(\d{4})/);
      let sectionYear  = reportStart?.getFullYear() ?? new Date().getFullYear();
      let sectionMonth = reportStart ? reportStart.getMonth() + 1 : new Date().getMonth() + 1;
      if (monthYearMatch) {
        const parsedDate = new Date(`${monthYearMatch[1]} 1, ${monthYearMatch[2]}`);
        if (!isNaN(parsedDate.getTime())) {
          sectionYear  = parsedDate.getFullYear();
          sectionMonth = parsedDate.getMonth() + 1;
        }
      }

      // Extract all glucose values from the monthly section
      const glucoseMatches = [...monthlySection.matchAll(/(\d{2,3})\s*mg\/dL/g)];
      const glucoseValues  = glucoseMatches.map((m) => m[1]);

      if (glucoseValues.length === 0 && !avg && !gmi) {
        Alert.alert(
          "Import Failed",
          "Could not find glucose data in this PDF.\n\nPlease ensure this is a LibreView AGP report with a Monthly Summary page.",
        );
        setImporting(false);
        return;
      }

      // ── Build note string with all AGP metrics ───────────────────────────────
      const noteBits = [
        `Imported from LibreView PDF: ${asset.name}`,
        avg    ? `Report Avg ${avg} mg/dL` : "",
        gmi    ? `GMI ${gmi}%`             : "",
        tir    ? `Time in Range ${tir}%`   : "",
        varVal ? `Variability ${varVal}%`  : "",
      ].filter(Boolean).join(" | ");

      // ── Pair glucose values with dates ───────────────────────────────────────
      // If we have a report date range, use it to assign exact dates.
      // Otherwise fall back to sequential dates starting from the 1st of the month.
      const rows: Array<{
        readingType: "Glucose";
        date: string;
        time: string;
        context: string;
        deviceMethod: string;
        bloodGlucose: number;
        notes: string;
        patientName: string;
      }> = [];

      if (reportStart && reportEnd && glucoseValues.length > 0) {
        const numDays = Math.round(
          (reportEnd.getTime() - reportStart.getTime()) / (1000 * 60 * 60 * 24)
        ) + 1;
        const count = Math.min(glucoseValues.length, numDays);
        for (let i = 0; i < count; i++) {
          const dt = new Date(reportStart);
          dt.setDate(dt.getDate() + i);
          const y = dt.getFullYear();
          const mo = String(dt.getMonth() + 1).padStart(2, "0");
          const d  = String(dt.getDate()).padStart(2, "0");
          rows.push({
            readingType: "Glucose" as const,
            date: `${y}-${mo}-${d}`,
            time: "12:00",
            context: "CGM Import",
            deviceMethod: "Imported Device",
            bloodGlucose: parseInt(glucoseValues[i], 10),
            notes: noteBits,
            patientName: profile?.name ?? "",
          });
        }
      } else if (glucoseValues.length > 0) {
        // Fallback: assign sequential days starting from day 1 of the section month
        for (let i = 0; i < glucoseValues.length; i++) {
          const day = String(i + 1).padStart(2, "0");
          const mo  = String(sectionMonth).padStart(2, "0");
          rows.push({
            readingType: "Glucose" as const,
            date: `${sectionYear}-${mo}-${day}`,
            time: "12:00",
            context: "CGM Import",
            deviceMethod: "Imported Device",
            bloodGlucose: parseInt(glucoseValues[i], 10),
            notes: noteBits,
            patientName: profile?.name ?? "",
          });
        }
      }

      // If no daily rows but we have summary stats, save one summary row
      if (rows.length === 0 && (avg || gmi)) {
        const now = new Date();
        rows.push({
          readingType: "Glucose" as const,
          date: now.toISOString().slice(0, 10),
          time: "12:00",
          context: "CGM Import",
          deviceMethod: "Imported Device",
          bloodGlucose: avg ? parseInt(avg, 10) : 0,
          notes: noteBits,
          patientName: profile?.name ?? "",
        });
      }

      Alert.alert(
        "Confirm Import",
        `Import ${rows.length} daily Blood Glucose reading(s) from this PDF?\n\n` +
        (avg    ? `Average Glucose: ${avg} mg/dL\n` : "") +
        (gmi    ? `GMI: ${gmi}%\n`                  : "") +
        (tir    ? `Time in Range: ${tir}%\n`         : "") +
        (varVal ? `Variability: ${varVal}%`           : ""),
        [
          { text: "Cancel", style: "cancel", onPress: () => setImporting(false) },
          {
            text: "Import",
            onPress: async () => {
              for (const row of rows) {
                await saveReading(row);
              }
              const status = agpStatusAndSummary({ avg, gmi, tir, var: varVal }, agpThresholds);
              setResult(
                `Imported ${rows.length} reading(s).\n\n${status.label}\n${status.detail}`,
              );
              setImporting(false);
              Alert.alert(
                "Import Complete",
                `Imported ${rows.length} reading(s).\n\n${status.label}: ${status.detail}`,
                [{ text: "OK", onPress: () => router.replace("/(tabs)") }],
              );
            },
          },
        ],
      );
    } catch (e: any) {
      Alert.alert("Import Error", `Could not parse PDF.\n\n${e?.message ?? e}`);
      setImporting(false);
    }
  }

  return (
    <ScreenContainer>
      {/* Header */}
      <View
        style={{
          flexDirection: "row",
          alignItems: "center",
          paddingHorizontal: 16,
          paddingTop: 12,
          paddingBottom: 8,
          borderBottomWidth: 0.5,
          borderBottomColor: colors.border,
        }}
      >
        <TouchableOpacity
          onPress={() => router.back()}
          style={{
            marginRight: 12,
            backgroundColor: colors.surface,
            borderRadius: 8,
            paddingHorizontal: 10,
            paddingVertical: 6,
          }}
        >
          <Text style={{ color: colors.primary, fontSize: 14, fontWeight: "600" }}>← Back</Text>
        </TouchableOpacity>
        <Text style={{ fontSize: 22, marginRight: 8 }}>📈</Text>
        <Text style={{ color: colors.foreground, fontSize: 17, fontWeight: "700" }}>
          AGP Report
        </Text>
      </View>

      <ScrollView contentContainerStyle={{ padding: 16, paddingBottom: 40 }}>
        {/* Current status */}
        <View
          style={{
            backgroundColor: colors.surface,
            borderRadius: 14,
            padding: 16,
            marginBottom: 16,
            borderWidth: 1,
            borderColor: colors.border,
          }}
        >
          <Text style={{ color: colors.muted, fontSize: 12, fontWeight: "600", marginBottom: 8 }}>
            CURRENT AGP STATUS
          </Text>
          <Text style={{ color: statusColor, fontSize: 20, fontWeight: "700" }}>
            {agpStatus.label}
          </Text>
          <Text style={{ color: statusColor, fontSize: 13, marginTop: 4 }}>
            {agpStatus.detail}
          </Text>
          {agpSummary && (
            <View style={{ marginTop: 10, gap: 4 }}>
              {agpSummary.avg && (
                <Text style={{ color: colors.muted, fontSize: 12 }}>
                  Average Glucose: {agpSummary.avg} mg/dL
                </Text>
              )}
              {agpSummary.tir && (
                <Text style={{ color: colors.muted, fontSize: 12 }}>
                  Time in Range: {agpSummary.tir}%
                </Text>
              )}
              {agpSummary.gmi && (
                <Text style={{ color: colors.muted, fontSize: 12 }}>
                  GMI: {agpSummary.gmi}%
                </Text>
              )}
              {agpSummary.var && (
                <Text style={{ color: colors.muted, fontSize: 12 }}>
                  Glucose Variability: {agpSummary.var}%
                </Text>
              )}
              {agpSummary.date && (
                <Text style={{ color: colors.muted, fontSize: 11 }}>
                  Last imported: {agpSummary.date}
                </Text>
              )}
            </View>
          )}
        </View>

        {/* Import */}
        <View
          style={{
            backgroundColor: colors.surface,
            borderRadius: 14,
            padding: 16,
            marginBottom: 16,
            borderWidth: 1,
            borderColor: colors.border,
          }}
        >
          <Text style={{ color: colors.foreground, fontWeight: "700", fontSize: 15, marginBottom: 8 }}>
            Import LibreView CGM PDF
          </Text>
          <Text style={{ color: colors.muted, fontSize: 13, marginBottom: 14, lineHeight: 20 }}>
            Select a LibreView AGP/Monthly Summary PDF to import daily Blood Glucose readings and
            extract your AGP summary metrics (Average Glucose, Time in Range, GMI, Variability).
          </Text>
          <TouchableOpacity
            onPress={handleImport}
            disabled={importing}
            style={{
              backgroundColor: importing ? colors.border : colors.primary,
              borderRadius: 12,
              paddingVertical: 14,
              alignItems: "center",
            }}
          >
            <Text style={{ color: "#fff", fontWeight: "700", fontSize: 15 }}>
              {importing ? "Importing…" : "Select PDF to Import"}
            </Text>
          </TouchableOpacity>
        </View>

        {/* Thresholds info */}
        <View
          style={{
            backgroundColor: colors.surface,
            borderRadius: 14,
            padding: 16,
            borderWidth: 1,
            borderColor: colors.border,
          }}
        >
          <Text style={{ color: colors.foreground, fontWeight: "700", fontSize: 14, marginBottom: 8 }}>
            AGP Thresholds
          </Text>
          <Text style={{ color: colors.muted, fontSize: 12, lineHeight: 20 }}>
            Green: TIR ≥ {agpThresholds.tir_green_min}%,  GMI ≤ {agpThresholds.gmi_green_max}%,  Variability ≤ {agpThresholds.var_green_max}%{"\n"}
            Yellow: TIR ≥ {agpThresholds.tir_yellow_min}%,  GMI ≤ {agpThresholds.gmi_yellow_max}%,  Variability ≤ {agpThresholds.var_yellow_max}%{"\n"}
            Red: Below Yellow thresholds
          </Text>
        </View>
      </ScrollView>
    </ScreenContainer>
  );
}
