import React, { useEffect, useState } from "react";
import {
  View, Text, ScrollView, StyleSheet,
  ActivityIndicator, TouchableOpacity,
} from "react-native";
import { getEggData, EggRecord, EggGrade } from "../services/api";
import Sparkline from "../components/Sparkline";
import BarChart from "../components/BarChart";
import CalendarPicker, { toISO, fromISO, toDisplay } from "../components/CalendarPicker";
import { HistoryPoint } from "../services/api";

const GRADE_CONFIG = {
  A:  { color:"#16a34a", bg:"#f0fdf4", borderColor:"#bbf7d0", label:"Grade A",     range:"> 60g",    key:"gradeA"  as const },
  B:  { color:"#d97706", bg:"#fffbeb", borderColor:"#fde68a", label:"Grade B",     range:"50 – 60g", key:"gradeB"  as const },
  C:  { color:"#dc2626", bg:"#fef2f2", borderColor:"#fecaca", label:"Grade C",     range:"< 50g",    key:"gradeC"  as const },
  TL: { color:"#6b7280", bg:"#f1f5f9", borderColor:"#cbd5e1", label:"Tidak Layak", range:"Reject",   key:"gradeTL" as const },
};

/** dd/mm/yyyy*/
const fromDisplay = (s: string): Date | null => {
  const p = s.split("/");
  if (p.length !== 3) return null;
  const d = new Date(+p[2], +p[1]-1, +p[0]);
  d.setHours(0,0,0,0);
  return isNaN(d.getTime()) ? null : d;
};

/** Hitung total & history yg sdh di filter */
function buildSummary(data: EggRecord[]) {
  const acc: Record<EggGrade, { count: number; totalW: number }> = {
    A:  { count:0, totalW:0 },
    B:  { count:0, totalW:0 },
    C:  { count:0, totalW:0 },
    TL: { count:0, totalW:0 },
  };
  data.forEach(d => {
    const g = d.grade in acc ? d.grade : "TL";
    acc[g].count++;
    acc[g].totalW += d.weight;
  });

  const avg = (g: EggGrade) =>
    acc[g].count > 0 ? parseFloat((acc[g].totalW / acc[g].count).toFixed(1)) : 0;
  const slotMap: Record<string, Record<EggGrade, number>> = {};

  data.forEach(d => {
    const [hStr, mStr] = d.timestamp.split(":");
    const h = parseInt(hStr) || 0;
    const m = parseInt(mStr) || 0;
    const slot30 = `${String(h).padStart(2,"0")}:${m < 30 ? "00" : "30"}`;
    const key = `${d.date} ${slot30}`;
    if (!slotMap[key]) slotMap[key] = { A:0, B:0, C:0, TL:0 };
    const g = d.grade in slotMap[key] ? d.grade : "TL";
    slotMap[key][g]++;
  });

  const history: HistoryPoint[] = Object.entries(slotMap)
    .sort(([a],[b]) => a.localeCompare(b))
    .slice(-5)
    .map(([key, v]) => ({
      time: key.split(" ")[1],
      A: v.A, B: v.B, C: v.C, TL: v.TL,
    }));

  return {
    gradeA:  { count: acc.A.count,  avgWeight: avg("A")  },
    gradeB:  { count: acc.B.count,  avgWeight: avg("B")  },
    gradeC:  { count: acc.C.count,  avgWeight: avg("C")  },
    gradeTL: { count: acc.TL.count, avgWeight: avg("TL") },
    history,
  };
}

// Data dummy
const _today = new Date();
const MOCK_DATA: EggRecord[] = Array.from({ length: 50 }, (_, i) => {
  const grades: EggGrade[] = ["A","B","C","TL"];
  const grade = grades[i % 4];

  const weightMap = {
    A: 64,
    B: 55,
    C: 47,
    TL: 30,
  };

  const d = new Date(_today);
  d.setDate(_today.getDate() - Math.floor(i / 10));
  d.setHours(8 + (i % 10), 0, 0, 0);

  return {
    id: i + 1,
    grade,
    weight: weightMap[grade],
    timestamp: `${String(d.getHours()).padStart(2,"0")}:00`,
    date: `${String(d.getDate()).padStart(2,"0")}/${String(d.getMonth()+1).padStart(2,"0")}/${d.getFullYear()}`,
  };
});

// ─Komponen utama

export default function DashboardScreen() {
  const todayISO = toISO(new Date());

  const [allData, setAllData]         = useState<EggRecord[]>([]);
  const [loading, setLoading]         = useState(true);
  const [error, setError]             = useState<string | null>(null);
  // const [usingMock, setUsingMock]     = useState(false);
  const [dateFrom, setDateFrom]       = useState(todayISO);
  const [dateTo, setDateTo]           = useState(todayISO);
  const [showCalFrom, setShowCalFrom] = useState(false);
  const [showCalTo, setShowCalTo]     = useState(false);

  // ── Fetch semua data sekali, filter di frontend ───────────────────────────
  useEffect(() => {
    const fetch = async () => {
      try {
        const result = await getEggData();
        setAllData(result);
        // setUsingMock(false);
        setError(null);
      } catch {
        // setAllData(MOCK_DATA);
        // setUsingMock(true);
        setAllData([]);
        setError("Server belum terhubung");
      } finally {
        setLoading(false);
      }
    };
    fetch();
    const iv = setInterval(fetch, 5000);
    return () => clearInterval(iv);
  }, []);

  // ── Filter data berdasarkan rentang tanggal ───────────────────────────────
  const filtered = allData.filter(d => {
    const itemDate = fromDisplay(d.date);
    const from     = fromISO(dateFrom);
    const to       = fromISO(dateTo);
    to.setHours(23,59,59,999);
    return itemDate ? itemDate >= from && itemDate <= to : true;
  });

  // ── Hitung summary dari data yang sudah difilter ──────────────────────────
  const summary = buildSummary(filtered);

  const totalEggs =
    summary.gradeA.count + summary.gradeB.count +
    summary.gradeC.count + summary.gradeTL.count;

  const rangeLabel = dateFrom === dateTo
    ? `Hari ini, ${toDisplay(dateFrom)}`
    : `${toDisplay(dateFrom)} – ${toDisplay(dateTo)}`;

  // Helper ambil data per key
  const getSummaryByKey = (key: "gradeA"|"gradeB"|"gradeC"|"gradeTL") => summary[key];
  const getSparkByGrade = (grade: EggGrade) => summary.history.map(h => h[grade]);

  return (
    <ScrollView
      style={s.container}
      contentContainerStyle={s.content}
      showsVerticalScrollIndicator={false}
    >
      {/* Header */}
     <View style={s.header}>
      <View>
        <Text style={s.title}>Dashboard</Text>
        <Text style={s.subtitle}>Live · Refresh 5s</Text>
      </View>

      <View style={[
        s.statusBadge,
        {
          backgroundColor: error ? "#fef2f2" : "#f0fdf4",
          borderColor: error ? "#fecaca" : "#bbf7d0"
        }
      ]}>
        <View style={[
          s.statusDot,
          { backgroundColor: error ? "#dc2626" : "#16a34a" }
        ]} />

        <Text style={[
          s.statusText,
          { color: error ? "#dc2626" : "#16a34a" }
        ]}>
          {error ? "OFFLINE" : "ONLINE"}
        </Text>
      </View>
    </View>

      {/* Filter Tanggal */}
      <View style={s.dateCard}>
        <View style={s.dateRangeRow}>
          {/* Dari */}
          <View style={s.dateField}>
            <Text style={s.dateFieldLabel}>Dari Tanggal</Text>
            <TouchableOpacity onPress={() => setShowCalFrom(true)} style={s.dateFieldBtn}>
              <Text style={s.dateFieldText}>{toDisplay(dateFrom)}</Text>
            </TouchableOpacity>
          </View>

          <Text style={s.dateDash}>—</Text>

          {/* Sampai */}
          <View style={s.dateField}>
            <Text style={s.dateFieldLabel}>Sampai Tanggal</Text>
            <TouchableOpacity onPress={() => setShowCalTo(true)} style={s.dateFieldBtn}>
              <Text style={s.dateFieldText}>{toDisplay(dateTo)}</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* Label aktif + Reset */}
        <View style={s.activeRow}>
          {(dateFrom!==todayISO || dateTo!==todayISO) && (
            <TouchableOpacity onPress={() => { setDateFrom(todayISO); setDateTo(todayISO); }}>
              <Text style={s.resetText}>Reset ke Hari Ini</Text>
            </TouchableOpacity>
          )}
        </View>
      </View>

      {/* Total Card */}
      <View style={s.totalCard}>
        <View>
          <Text style={s.totalLabel}>Total Telur</Text>
          {loading ? (
            <ActivityIndicator color="#4f46e5" style={{marginTop:8}} />
          ) : (
            <Text style={s.totalValue}>{String(totalEggs).padStart(3,"0")}</Text>
          )}
          <Text style={s.totalSub}>{rangeLabel}</Text>
        </View>
        <View style={s.gradeBadgeRow}>
          <Text style={s.totalSubLabel}>Grade</Text>
          <View style={s.gradeBadgesContainer}>
            {(["A","B","C","TL"] as const).map((g) => (
              <View key={g} style={[s.gradeBadge,{
                backgroundColor: GRADE_CONFIG[g].bg,
                borderColor:     GRADE_CONFIG[g].borderColor,
              }]}>
                <Text style={[s.gradeBadgeText,{color:GRADE_CONFIG[g].color}]}>{g}</Text>
              </View>
            ))}
          </View>
        </View>
      </View>

      {/* Grade Cards — A, B, C, TL */}
      {(["A","B","C","TL"] as const).map((grade) => {
        const cfg       = GRADE_CONFIG[grade];
        const d         = getSummaryByKey(cfg.key);
        const sparkData = getSparkByGrade(grade);

        return (
          <View key={grade} style={[s.gradeCard,{backgroundColor:cfg.bg,borderColor:cfg.borderColor}]}>
            <View style={s.gradeCardInner}>
              <View style={{flex:1}}>
                <View style={s.gradeTagRow}>
                  <View style={[s.gradeTag,{backgroundColor:cfg.color}]}>
                    <Text style={s.gradeTagText}>{cfg.label}</Text>
                  </View>
                  <Text style={s.gradeRange}>{cfg.range}</Text>
                </View>
                <View style={s.statsRow}>
                  <View>
                    <Text style={s.statLabel}>Jumlah</Text>
                    <Text style={[s.statValue,{color:cfg.color}]}>
                      {loading ? "—" : d.count}
                    </Text>
                    <Text style={s.statUnit}>butir</Text>
                  </View>
                  <View style={{marginLeft:24}}>
                    <Text style={s.statLabel}>Rata-rata</Text>
                    <Text style={[s.statValue,{color:"#1e293b"}]}>
                      {loading ? "—" : d.avgWeight > 0 ? d.avgWeight.toFixed(1) : "0"}
                    </Text>
                    <Text style={s.statUnit}>gram</Text>
                  </View>
                </View>
              </View>
              <View style={s.sparklineContainer}>
                {sparkData.length >= 2
                  ? <Sparkline data={sparkData} color={cfg.color} width={80} height={40} />
                  : <View style={s.noSparkline}><Text style={s.noSparklineText}>—</Text></View>
                }
              </View>
            </View>
          </View>
        );
      })}

      {/* Bar Chart */}
      <View style={s.chartCard}>
        <Text style={s.chartTitle}>Distribusi per Waktu · {rangeLabel}</Text>
        {loading ? (
          <ActivityIndicator color="#94a3b8" style={{marginTop:20}} />
        ) : summary.history.length > 0 ? (
          <BarChart history={summary.history} />
        ) : (
          <Text style={s.emptyChart}>Belum ada data pada rentang tanggal ini</Text>
        )}
      </View>

      {/* Calendar popup — Dari */}
      <CalendarPicker
        visible={showCalFrom}
        value={dateFrom}
        maxDate={dateTo}
        title="Pilih Tanggal Awal"
        onConfirm={(v) => { setDateFrom(v); if (v > dateTo) setDateTo(v); }}
        onClose={() => setShowCalFrom(false)}
      />

      {/* Calendar popup — Sampai */}
      <CalendarPicker
        visible={showCalTo}
        value={dateTo}
        minDate={dateFrom}
        maxDate={todayISO}
        title="Pilih Tanggal Akhir"
        onConfirm={(v) => setDateTo(v)}
        onClose={() => setShowCalTo(false)}
      />

    </ScrollView>
  );
}

// ─── Styles ───────────────────────────────────────────────────────────────────
const s = StyleSheet.create({
  container: { flex:1, backgroundColor:"#f8fafc" },
  content:   { padding:16, paddingBottom:24 },

  header:     { flexDirection:"row", justifyContent:"space-between", alignItems:"center", marginBottom:14 },
  title:      { fontSize:24, fontWeight:"800", color:"#0f172a", letterSpacing:-0.5 },
  subtitle:   { fontSize:12, color:"#94a3b8", marginTop:2 },
  statusBadge:{ flexDirection:"row", alignItems:"center", gap:6, borderWidth:1, borderRadius:20, paddingHorizontal:12, paddingVertical:6 },
  statusDot:  { width:7, height:7, borderRadius:4 },
  statusText: { fontSize:10, fontWeight:"700" },

  mockBanner: { backgroundColor:"#fffbeb", borderWidth:1, borderColor:"#fde68a", borderRadius:10, padding:9, marginBottom:12 },
  mockText:   { fontSize:11, color:"#92400e" },

  // Date card
  dateCard:       { backgroundColor:"#fff", borderWidth:1, borderColor:"#e2e8f0", borderRadius:14, padding:12, marginBottom:14 },
  dateRangeRow:   { flexDirection:"row", alignItems:"center", gap:8 },
  dateField:      { flex:1 },
  dateFieldLabel: { fontSize:10, color:"#94a3b8", fontWeight:"600", marginBottom:4 },
  dateFieldBtn:   { flexDirection:"row", alignItems:"center", gap:6, backgroundColor:"#f8fafc", borderWidth:1, borderColor:"#e2e8f0", borderRadius:10, paddingHorizontal:10, paddingVertical:9 },
  dateFieldIcon:  { fontSize:14 },
  dateFieldText:  { fontSize:13, color:"#0f172a", fontWeight:"600" },
  dateDash:       { fontSize:18, color:"#cbd5e1", marginTop:16 },
  activeRow:      { flexDirection:"row", justifyContent:"space-between", alignItems:"center", marginTop:10 },
  activeText:     { fontSize:11, color:"#64748b" },
  resetText:      { fontSize:11, color:"#4f46e5", fontWeight:"700" },

  // Total Card
  totalCard:           { backgroundColor:"#eef2ff", borderWidth:1, borderColor:"#c7d2fe", borderRadius:16, padding:16, marginBottom:14, flexDirection:"row", justifyContent:"space-between", alignItems:"center" },
  totalLabel:          { fontSize:11, color:"#4f46e5", marginBottom:2, fontWeight:"600" },
  totalValue:          { fontSize:36, fontWeight:"800", color:"#1e1b4b", fontFamily:"monospace" },
  totalSub:            { fontSize:10, color:"#818cf8", marginTop:2 },
  gradeBadgeRow:       { alignItems:"flex-end" },
  totalSubLabel:       { fontSize:11, color:"#94a3b8", marginBottom:6 },
  gradeBadgesContainer:{ flexDirection:"row", gap:5 },
  gradeBadge:          { width:28, height:28, borderRadius:7, borderWidth:1, alignItems:"center", justifyContent:"center" },
  gradeBadgeText:      { fontSize:9, fontWeight:"700" },

  // Grade Cards
  gradeCard:      { borderWidth:1, borderRadius:16, padding:14, marginBottom:12 },
  gradeCardInner: { flexDirection:"row", justifyContent:"space-between", alignItems:"flex-start" },
  gradeTagRow:    { flexDirection:"row", alignItems:"center", gap:8, marginBottom:10 },
  gradeTag:       { paddingHorizontal:8, paddingVertical:3, borderRadius:6 },
  gradeTagText:   { fontSize:11, fontWeight:"800", color:"#fff" },
  gradeRange:     { fontSize:10, color:"#94a3b8" },
  statsRow:       { flexDirection:"row" },
  statLabel:      { fontSize:10, color:"#94a3b8", marginBottom:2 },
  statValue:      { fontSize:28, fontWeight:"800", fontFamily:"monospace", lineHeight:32 },
  statUnit:       { fontSize:9, color:"#94a3b8" },
  sparklineContainer: { alignItems:"flex-end", paddingTop:4 },
  noSparkline:    { width:80, height:40, justifyContent:"center", alignItems:"center" },
  noSparklineText:{ color:"#cbd5e1", fontSize:18 },

  // Chart
  chartCard:  { backgroundColor:"#fff", borderWidth:1, borderColor:"#e2e8f0", borderRadius:16, padding:16 },
  chartTitle: { fontSize:12, color:"#64748b", fontWeight:"600", marginBottom:12 },
  emptyChart: { fontSize:12, color:"#94a3b8", textAlign:"center", paddingVertical:20 },
});