import React, { useEffect, useState } from "react";
import {
  View, Text, StyleSheet, TouchableOpacity, TextInput,
  ActivityIndicator, Alert, FlatList, Modal,
} from "react-native";
import RNPrint from "react-native-print";
import CalendarPicker, { toISO, fromISO, toDisplay } from "../components/CalendarPicker";
import { getEggData, EggRecord, EggGrade } from "../services/api";

const GRADE_CONFIG = {
  A:  { color: "#16a34a", bg: "#f0fdf4", borderColor: "#bbf7d0" },
  B:  { color: "#d97706", bg: "#fffbeb", borderColor: "#fde68a" },
  C:  { color: "#dc2626", bg: "#fef2f2", borderColor: "#fecaca" },
  TL: { color: "#6b7280", bg: "#f1f5f9", borderColor: "#cbd5e1" },
};

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;
};

type GradeFilter = "all" | EggGrade;


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

  const [allData, setAllData]         = useState<EggRecord[]>([]);
  const [gradeFilter, setGradeFilter] = useState<GradeFilter>("all");
  const [dateFrom, setDateFrom]       = useState(todayISO);
  const [dateTo, setDateTo]           = useState(todayISO);
  const [search, setSearch]           = useState("");
  const [loading, setLoading]         = useState(true);
  const [printing, setPrinting]       = useState(false);
  const [showCalFrom, setShowCalFrom] = useState(false);
  const [showCalTo, setShowCalTo]     = useState(false);

  useEffect(() => {
    const fetch = async () => {
      try {
        const result = await getEggData();
        setAllData(result);

      } catch (err) {
        setAllData([]);
      } finally { setLoading(false); }
    };
    fetch();
    const iv = setInterval(fetch, 8000);
    return () => clearInterval(iv);
  }, []);

  // ── Filter ────────────────────────────────────────────────────────────────
  const filtered = allData.filter((d) => {
    const matchGrade  = gradeFilter === "all" || d.grade === gradeFilter;
    const itemDate    = fromDisplay(d.date);
    const from        = fromISO(dateFrom);
    const to          = fromISO(dateTo); to.setHours(23,59,59,999);
    const matchDate   = itemDate ? itemDate >= from && itemDate <= to : true;
    const matchSearch = !search || (
      d.grade.toLowerCase().includes(search.toLowerCase()) ||
      d.weight.toString().includes(search) || d.date.includes(search)
    );
    return matchGrade && matchDate && matchSearch;
  });

  const countByGrade = (g: EggGrade) => filtered.filter(d => d.grade === g).length;

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

  // ── PDF ───────────────────────────────────────────────────────────────────
  const handlePrintPDF = async () => {
    setPrinting(true);
    try {
      const gradeLabel = gradeFilter === "all" ? "Semua Grade" : `Grade ${gradeFilter}`;
      const printDate  = new Date().toLocaleString("id-ID",{
        weekday:"long", year:"numeric", month:"long", day:"numeric", hour:"2-digit", minute:"2-digit"
      });

      const pct  = (n: number) => filtered.length > 0 ? ((n/filtered.length)*100).toFixed(1) : "0.0";
      const cntA = countByGrade("A"), cntB = countByGrade("B"),
            cntC = countByGrade("C"), cntTL = countByGrade("TL");

      const rows = filtered.length === 0
        ? `<tr><td colspan="5" style="text-align:center;padding:32px;color:#94a3b8;font-style:italic">Tidak ada data sesuai filter</td></tr>`
        : filtered.map((d,i) => `
          <tr>
            <td class="tc muted">${i+1}</td>
            <td>${d.date}</td>
            <td class="muted">${d.timestamp}</td>
            <td class="tc"><span class="badge grade-${d.grade}">${d.grade==="TL"?"Tidak Layak":"Grade "+d.grade}</span></td>
            <td class="tr mono">${d.weight} g</td>
          </tr>`).join("");

      const html = `<!DOCTYPE html>
<html lang="id"><head><meta charset="UTF-8"><title>Laporan Sortir Telur</title>
<style>
  *{box-sizing:border-box;margin:0;padding:0}
  body{font-family:Arial,sans-serif;font-size:12px;color:#1e293b;padding:28px 32px}
  .ph{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid #e2e8f0;padding-bottom:14px;margin-bottom:20px}
  .ph h1{font-size:18px;font-weight:800;color:#0f172a}.ph p{font-size:11px;color:#64748b;margin-top:2px}
  .meta{text-align:right;font-size:11px;color:#64748b;line-height:1.8}
  .bf{display:inline-block;background:#eef2ff;color:#4f46e5;border:1px solid #c7d2fe;border-radius:20px;padding:3px 12px;font-size:11px;font-weight:600;margin-top:4px}
  .sg{display:grid;grid-template-columns:repeat(5,1fr);gap:8px;margin-bottom:20px}
  .sc{border-radius:10px;border:1px solid #e2e8f0;padding:12px 8px;text-align:center;position:relative;overflow:hidden}
  .sc::before{content:'';position:absolute;top:0;left:0;right:0;height:3px}
  .sc.tot::before{background:#1e293b}.sc.tot .num{color:#0f172a}
  .sc.grA{background:#f0fdf4;border-color:#bbf7d0}.sc.grA::before{background:#16a34a}.sc.grA .num{color:#16a34a}
  .sc.grB{background:#fffbeb;border-color:#fde68a}.sc.grB::before{background:#d97706}.sc.grB .num{color:#d97706}
  .sc.grC{background:#fef2f2;border-color:#fecaca}.sc.grC::before{background:#dc2626}.sc.grC .num{color:#dc2626}
  .sc.grT{background:#f8fafc;border-color:#cbd5e1}.sc.grT::before{background:#6b7280}.sc.grT .num{color:#6b7280}
  .sc .num{font-size:26px;font-weight:800;line-height:1}.sc .lbl{font-size:10px;color:#64748b;margin-top:3px}.sc .pct{font-size:10px;color:#94a3b8}
  .db{background:#f1f5f9;border-radius:6px;height:12px;overflow:hidden;display:flex;margin-bottom:8px}
  .ds{height:100%}.ds.A{background:#16a34a}.ds.B{background:#d97706}.ds.C{background:#dc2626}.ds.TL{background:#94a3b8}
  .dl{display:flex;gap:14px;flex-wrap:wrap;margin-bottom:20px}
  .di{display:flex;align-items:center;gap:5px;font-size:10px;color:#64748b}
  .dot{width:8px;height:8px;border-radius:50%}.dot.A{background:#16a34a}.dot.B{background:#d97706}.dot.C{background:#dc2626}.dot.TL{background:#94a3b8}
  .ts h2{font-size:11px;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px}
  table{width:100%;border-collapse:collapse}thead tr{background:#0f172a}
  th{padding:9px 10px;text-align:left;font-size:10px;font-weight:600;color:#94a3b8;text-transform:uppercase;letter-spacing:.4px}
  td{padding:8px 10px;font-size:11px;border-bottom:1px solid #f1f5f9}tr:nth-child(even) td{background:#f8fafc}
  .tc{text-align:center}.tr{text-align:right}.muted{color:#94a3b8}.mono{font-family:'Courier New',monospace;font-weight:600}
  .badge{display:inline-block;padding:2px 8px;border-radius:20px;font-weight:700;font-size:10px}
  .grade-A{background:#dcfce7;color:#15803d;border:1px solid #bbf7d0}
  .grade-B{background:#fef9c3;color:#b45309;border:1px solid #fde68a}
  .grade-C{background:#fee2e2;color:#b91c1c;border:1px solid #fecaca}
  .grade-TL{background:#f1f5f9;color:#4b5563;border:1px solid #cbd5e1}
  .pf{margin-top:20px;padding-top:12px;border-top:1px solid #e2e8f0;display:flex;justify-content:space-between;font-size:10px;color:#94a3b8}
  @media print{body{padding:14px 18px}tr{page-break-inside:avoid}}
</style></head><body>
<div class="ph">
  <div><h1>🥚 Laporan Sortir Telur</h1><p>Sistem Sortir Telur Otomatis — NAKULA</p></div>
  <div class="meta">Dicetak: ${printDate}<br><span class="bf">${gradeLabel} · ${rangeLabel}</span></div>
</div>
<div class="sg">
  <div class="sc tot"><div class="num">${filtered.length}</div><div class="lbl">Total</div><div class="pct">100%</div></div>
  <div class="sc grA"><div class="num">${cntA}</div><div class="lbl">Grade A</div><div class="pct">${pct(cntA)}%</div></div>
  <div class="sc grB"><div class="num">${cntB}</div><div class="lbl">Grade B</div><div class="pct">${pct(cntB)}%</div></div>
  <div class="sc grC"><div class="num">${cntC}</div><div class="lbl">Grade C</div><div class="pct">${pct(cntC)}%</div></div>
  <div class="sc grT"><div class="num">${cntTL}</div><div class="lbl">Tdk Layak</div><div class="pct">${pct(cntTL)}%</div></div>
</div>
${filtered.length>0?`
<div class="db">
  <div class="ds A" style="width:${pct(cntA)}%"></div>
  <div class="ds B" style="width:${pct(cntB)}%"></div>
  <div class="ds C" style="width:${pct(cntC)}%"></div>
  <div class="ds TL" style="width:${pct(cntTL)}%"></div>
</div>
<div class="dl">
  <div class="di"><div class="dot A"></div>Grade A — ${cntA} butir (${pct(cntA)}%)</div>
  <div class="di"><div class="dot B"></div>Grade B — ${cntB} butir (${pct(cntB)}%)</div>
  <div class="di"><div class="dot C"></div>Grade C — ${cntC} butir (${pct(cntC)}%)</div>
  <div class="di"><div class="dot TL"></div>Tidak Layak — ${cntTL} butir (${pct(cntTL)}%)</div>
</div>`:""}
<div class="ts">
  <h2>Detail Data (${filtered.length} butir)</h2>
  <table>
    <thead><tr><th style="width:32px">#</th><th>Tanggal</th><th>Jam</th><th class="tc">Grade</th><th class="tr">Berat</th></tr></thead>
    <tbody>${rows}</tbody>
  </table>
</div>
<div class="pf">
  <span>Sistem Sortir Telur Otomatis © ${new Date().getFullYear()}</span>
  <span>${gradeLabel} · ${rangeLabel}</span>
</div>
</body></html>`;

      await RNPrint.print({ html });
    } catch (e: any) {
      Alert.alert("Gagal", e?.message ?? "Tidak dapat membuka dialog cetak.");
    } finally { setPrinting(false); }
  };

  // ── Render row ────────────────────────────────────────────────────────────
  const renderItem = ({ item, index }: { item: EggRecord; index: number }) => {
    const cfg = GRADE_CONFIG[item.grade] ?? GRADE_CONFIG.TL;
    return (
      <View style={[s.tableRow, { backgroundColor: index%2===0 ? "#fff" : "#f8fafc" }]}>
        <Text style={[s.cell, s.cellId]}>{item.id}</Text>
        <Text style={[s.cell, s.cellDate]}>{item.date}</Text>
        <Text style={[s.cell, s.cellTime]}>{item.timestamp}</Text>
        <View style={s.cellGradeCont}>
          <View style={[s.gradeBadge, { backgroundColor: cfg.bg, borderColor: cfg.borderColor }]}>
            <Text style={[s.gradeBadgeText, { color: cfg.color }]}>
              {item.grade==="TL" ? "Tdk Layak" : `Grade ${item.grade}`}
            </Text>
          </View>
        </View>
        <Text style={[s.cell, s.cellWeight]}>{item.weight}g</Text>
      </View>
    );
  };

  return (
    <View style={s.container}>

      {/* Header */}
      <View style={s.header}>
        <View>
          <Text style={s.title}>Laporan</Text>
          <Text style={s.subtitle}>Data realtime sortir telur</Text>
        </View>
      </View>

      {/* <View style={[
        s.statusBanner,
        {
          backgroundColor: error ? "#fef2f2" : "#f0fdf4",
          borderColor: error ? "#fecaca" : "#bbf7d0"
        }
      ]}>
        <Text style={[
          s.statusText,
          { color: error ? "#dc2626" : "#16a34a" }
        ]}>
          {error ? "🔴 OFFLINE — Server tidak terhubung" : "🟢 ONLINE — Terhubung ke server"}
        </Text>
      </View> */}

      {/* Filter Grade */}
      <View style={s.filterRow}>
        {(["all","A","B","C","TL"] as const).map((g) => {
          const active = gradeFilter === g;
          const color  = g==="all" ? "#4f46e5" : GRADE_CONFIG[g as EggGrade].color;
          const bg     = g==="all" ? "#eef2ff" : GRADE_CONFIG[g as EggGrade].bg;
          const border = g==="all" ? "#c7d2fe" : GRADE_CONFIG[g as EggGrade].borderColor;
          return (
            <TouchableOpacity key={g} onPress={() => setGradeFilter(g)}
              style={[s.filterChip,{ borderColor: active?border:"#e2e8f0", backgroundColor: active?bg:"#fff" }]}>
              <Text style={[s.filterChipText,{ color: active?color:"#94a3b8", fontWeight: active?"700":"400" }]}>
                {g==="all"?"Semua":g==="TL"?"TL":`Grade ${g}`}
              </Text>
            </TouchableOpacity>
          );
        })}
      </View>

      {/* Filter Tanggal — popup calendar */}
      <View style={s.dateRangeCard}>
        <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.dateFieldIcon}>📅</Text> */}
              <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.dateFieldIcon}>📅</Text> */}
              <Text style={s.dateFieldText}>{toDisplay(dateTo)}</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* Label aktif + Reset */}
        <View style={s.activeRow}>
          <Text style={s.activeText}>
            {rangeLabel}{"  ·  "}
            <Text style={{color:"#4f46e5",fontWeight:"700"}}>{filtered.length} data</Text>
          </Text>
          {(dateFrom!==todayISO || dateTo!==todayISO) && (
            <TouchableOpacity onPress={() => { setDateFrom(todayISO); setDateTo(todayISO); }}>
              <Text style={s.resetText}>Reset</Text>
            </TouchableOpacity>
          )}
        </View>
      </View>

      {/* Search */}
      <TextInput
        value={search} onChangeText={setSearch}
        placeholder="Cari grade / berat"
        placeholderTextColor="#cbd5e1"
        style={s.searchInput}
      />

      {/* Stats */}
      <View style={s.statsRow}>
        {(["A","B","C","TL"] as const).map((g) => {
          const cnt = countByGrade(g); const cfg = GRADE_CONFIG[g];
          return (
            <View key={g} style={[s.statBox,{
              backgroundColor: cnt>0?cfg.bg:"#f8fafc",
              borderColor: cnt>0?cfg.borderColor:"#e2e8f0",
            }]}>
              <Text style={[s.statNum,{color:cfg.color}]}>{cnt}</Text>
              <Text style={s.statLabel}>{g==="TL"?"TL":`Grade ${g}`}</Text>
            </View>
          );
        })}
        <View style={[s.statBox,{backgroundColor:"#f1f5f9",borderColor:"#e2e8f0"}]}>
          <Text style={[s.statNum,{color:"#1e293b"}]}>{filtered.length}</Text>
          <Text style={s.statLabel}>Total</Text>
        </View>
      </View>

      {/* Table Header */}
      <View style={s.tableHeader}>
        <Text style={[s.thText, s.cellId]}>#</Text>
        <Text style={[s.thText, s.cellDate]}>Tanggal</Text>
        <Text style={[s.thText, s.cellTime]}>Waktu</Text>
        <Text style={[s.thText, s.cellGrade]}>Grade</Text>
        <Text style={[s.thText, s.cellWeight]}>Berat</Text>
      </View>

      {/* Table Body */}
      {loading ? (
        <ActivityIndicator color="#94a3b8" style={{marginTop:40}} />
      ) : filtered.length===0 ? (
        <Text style={s.emptyText}>Tidak ada data pada rentang tanggal ini</Text>
      ) : (
        <FlatList
          data={filtered}
          keyExtractor={item => item.id.toString()}
          renderItem={renderItem}
          showsVerticalScrollIndicator={false}
          style={s.tableBody}
          contentContainerStyle={{paddingBottom:90}}
        />
      )}

      {/* FAB PDF */}
      <TouchableOpacity
        onPress={handlePrintPDF} disabled={printing}
        style={[s.fab, printing && {opacity:0.7}]}
        activeOpacity={0.85}
      >
        {printing
          ? <ActivityIndicator color="#fff" size="small" />
          : <Text style={s.fabText}>PDF</Text>
        }
      </TouchableOpacity>

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

    </View>
  );
}

// ─── Styles ───────────────────────────────────────────────────────────────────
const s = StyleSheet.create({
  container: { flex:1, backgroundColor:"#f8fafc", paddingTop:16, paddingHorizontal:16 },

  header:   { flexDirection:"row", justifyContent:"space-between", alignItems:"flex-start", marginBottom:10 },
  title:    { fontSize:24, fontWeight:"800", color:"#0f172a", letterSpacing:-0.5 },
  subtitle: { fontSize:12, color:"#94a3b8", marginTop:2 },

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

  statusText: {
    fontSize: 12,
    fontWeight: "600",
  },

  filterRow:     { flexDirection:"row", gap:6, marginBottom:10 },
  filterChip:    { flex:1, paddingVertical:7, borderRadius:20, borderWidth:1, alignItems:"center" },
  filterChipText:{ fontSize:11 },

  // Date range card
  dateRangeCard: {
    backgroundColor:"#fff", borderWidth:1, borderColor:"#e2e8f0",
    borderRadius:14, padding:12, marginBottom:10,
  },
  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" },

  searchInput: {
    backgroundColor:"#fff", borderWidth:1, borderColor:"#e2e8f0",
    borderRadius:10, paddingHorizontal:12, paddingVertical:9,
    color:"#0f172a", fontSize:13, marginBottom:10,
  },

  statsRow: { flexDirection:"row", gap:6, marginBottom:10 },
  statBox:  { flex:1, borderWidth:1, borderRadius:10, padding:6, alignItems:"center" },
  statNum:  { fontSize:16, fontWeight:"800", fontFamily:"monospace" },
  statLabel:{ fontSize:8, color:"#94a3b8", marginTop:2 },

  tableHeader: { flexDirection:"row", paddingVertical:10, paddingHorizontal:4, borderBottomWidth:1, borderBottomColor:"#e2e8f0" },
  thText:      { fontSize:10, color:"#94a3b8", fontWeight:"600" },
  tableBody:   { flex:1 },
  tableRow:    { flexDirection:"row", alignItems:"center", paddingVertical:9, paddingHorizontal:4, borderBottomWidth:1, borderBottomColor:"#f1f5f9" },
  cell:        { fontSize:11, color:"#334155" },
  cellId:      { width:28, color:"#94a3b8", fontFamily:"monospace", fontSize:10 },
  cellDate:    { width:68, fontSize:10, color:"#64748b" },
  cellTime:    { width:44, fontSize:10, color:"#64748b" },
  cellGrade:   { flex:1 },
  cellGradeCont:{ flex:1 },
  gradeBadge:  { alignSelf:"flex-start", paddingHorizontal:6, paddingVertical:2, borderRadius:6, borderWidth:1 },
  gradeBadgeText:{ fontSize:9, fontWeight:"700" },
  cellWeight:  { width:46, fontFamily:"monospace", fontWeight:"600", textAlign:"right", color:"#1e293b", fontSize:11 },
  emptyText:   { textAlign:"center", color:"#94a3b8", marginTop:40, fontSize:13 },

  fab: {
    position:"absolute", bottom:24, right:20,
    backgroundColor:"#4f46e5", borderRadius:18,
    paddingHorizontal:22, paddingVertical:14,
    shadowColor:"#4f46e5", shadowOffset:{width:0,height:6},
    shadowOpacity:0.4, shadowRadius:12, elevation:10,
  },
  fabText: { color:"#fff", fontSize:14, fontWeight:"800", letterSpacing:0.3 },
});