// Analytics screen — loads real history from the backend API.
// Falls back to demo data when the backend is offline or the tank has no deviceId.
const A_ = Recharts;

const RANGE_HOURS = { '24H': 24, '7D': 168, '30D': 720, '90D': 2160 };

const Analytics = ({ tanks }) => {
  const [range,    setRange]    = useState('7D');
  const [tankSel,  setTankSel]  = useState('all');
  const [history,  setHistory]  = useState([]);
  const [weekData, setWeekData] = useState({ volumeWeek: [], energyWeek: [], motorWeek: [] });
  const [loading,  setLoading]  = useState(false);

  // Resolve the deviceId to query for the selected tank pill
  const deviceId = useMemo(() => {
    if (tankSel === 'all') return tanks.find(t => t.deviceId)?.deviceId ?? null;
    return tanks.find(t => t.id === tankSel)?.deviceId ?? null;
  }, [tankSel, tanks]);

  // Fetch whenever the selected tank or time range changes
  useEffect(() => {
    if (!deviceId || !window.API) return;
    setLoading(true);
    const hours = RANGE_HOURS[range] || 24;
    Promise.all([
      API.get(`/api/tanks/history?deviceId=${encodeURIComponent(deviceId)}&hours=${hours}`),
      API.get(`/api/tanks/week?deviceId=${encodeURIComponent(deviceId)}`),
    ])
      .then(([hist, week]) => {
        setHistory(hist);
        setWeekData(week);
      })
      .catch(e => console.warn('[Analytics] API unavailable:', e.message))
      .finally(() => setLoading(false));
  }, [deviceId, range]);

  // Use real data when available, fall back to demo constants
  const data24      = history.length      > 0 ? history                  : AC.gen24h();
  const vcDay       = history.length      > 0 ? history                  : AC.vcDay;
  const volumeWeek  = weekData.volumeWeek.length > 0 ? weekData.volumeWeek : AC.volumeWeek;
  const energyWeek  = weekData.energyWeek.length > 0 ? weekData.energyWeek : AC.energyWeek;
  const motorWeek   = weekData.motorWeek.length  > 0 ? weekData.motorWeek  : AC.motorWeek;

  const summary = useMemo(() => {
    if (weekData.volumeWeek.length === 0) return { volume: 8580, energy: 28.4, runtime: '14h 35m', avg: 1225, cost: 198.5 };
    const vol     = volumeWeek.reduce((s, r) => s + r.L,      0);
    const energy  = energyWeek.reduce((s, r) => s + r.kWh,    0);
    const runMin  = motorWeek.reduce( (s, r) => s + r.runMin, 0);
    return {
      volume:  vol,
      energy:  +energy.toFixed(2),
      runtime: `${Math.floor(runMin / 60)}h ${Math.round(runMin % 60)}m`,
      avg:     volumeWeek.length > 0 ? Math.round(vol / volumeWeek.length) : 0,
      cost:    +(energy * 7).toFixed(1),   // rough ₹7/kWh estimate
    };
  }, [weekData, volumeWeek, energyWeek, motorWeek]);

  const tankPills = [{ id: 'all', label: 'All Tanks' }, ...tanks.map(t => ({ id: t.id, label: t.name.split(' — ')[0] }))];

  return (
    <div style={{ padding: '8px 16px 100px' }}>
      <div style={{ padding: '6px 4px 14px' }}>
        <div style={{ fontSize: 22, fontWeight: 600 }}>Analytics</div>
        <div style={{ fontSize: 13, color: 'var(--text-2)', marginTop: 2 }}>
          Historical data & insights{loading && <span style={{ color: 'var(--cyan)', marginLeft: 8, fontSize: 11 }}>Loading…</span>}
        </div>
      </div>

      {/* Range selector */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
        <Segmented options={['24H','7D','30D','90D'].map(r=>({value:r,label:r}))} value={range} onChange={setRange}/>
        <button style={{ background: 'rgba(255,255,255,0.06)', border: '1px solid var(--border)', borderRadius: 10, width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-2)' }}>
          <Ic name="calendar" size={16}/>
        </button>
      </div>

      {/* Tank selector */}
      <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 4, marginBottom: 14, scrollbarWidth: 'none' }}>
        {tankPills.map(p => (
          <button key={p.id} onClick={() => setTankSel(p.id)} style={{
            padding: '6px 12px', borderRadius: 999, whiteSpace: 'nowrap',
            background: tankSel === p.id ? 'rgba(0,212,255,0.15)' : 'rgba(255,255,255,0.04)',
            border: `1px solid ${tankSel === p.id ? 'rgba(0,212,255,0.4)' : 'var(--border)'}`,
            color: tankSel === p.id ? 'var(--cyan)' : 'var(--text-2)',
            fontSize: 12, fontWeight: 500,
          }}>{p.label}</button>
        ))}
      </div>

      {/* Summary cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 8, marginBottom: 18 }}>
        <SummaryCard label="Volume"   value={`${(summary.volume/1000).toFixed(2)}k`} unit="L"   icon="waves"    tone="cyan"/>
        <SummaryCard label="Energy"   value={summary.energy}                          unit="kWh" icon="zap"      tone="amber"/>
        <SummaryCard label="Runtime"  value={summary.runtime}                                    icon="clock"    tone="teal"/>
        <SummaryCard label="Avg Daily" value={AC.fmtNum(summary.avg)}                 unit="L"   icon="activity" tone="info"/>
        <SummaryCard label="Est. Cost" value={`₹${summary.cost}`}                               icon="rupee"    tone="green" span/>
      </div>

      {/* Level history */}
      <ChartCard title="Water Level History" subtitle={`Last ${range} · auto-start & auto-stop bounds`}>
        <ResponsiveContainer width="100%" height={200}>
          <A_.AreaChart data={data24} margin={{ top: 10, right: 12, bottom: 0, left: 8 }}>
            <defs>
              <linearGradient id="lvl2" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%"   stopColor="#00d4ff" stopOpacity={0.55}/>
                <stop offset="100%" stopColor="#00d4ff" stopOpacity={0}/>
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="3 3" vertical={false}/>
            <XAxis dataKey="t" interval={4} tickLine={false} axisLine={false}/>
            <YAxis domain={[0, 100]} tickLine={false} axisLine={false} width={28}/>
            <Tooltip/>
            <A_.ReferenceLine y={25} stroke="#00e676" strokeDasharray="4 4" strokeOpacity={0.6}/>
            <A_.ReferenceLine y={90} stroke="#ffab40" strokeDasharray="4 4" strokeOpacity={0.6}/>
            <Area type="monotone" dataKey="level" stroke="#00d4ff" strokeWidth={2} fill="url(#lvl2)"/>
          </A_.AreaChart>
        </ResponsiveContainer>
      </ChartCard>

      <ChartCard title="Volume Consumed" subtitle="Daily breakdown · Liters">
        <ResponsiveContainer width="100%" height={180}>
          <BarChart data={volumeWeek} margin={{ top: 10, right: 12, bottom: 0, left: 8 }}>
            <defs>
              <linearGradient id="bvol" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%"   stopColor="#00d4ff"/>
                <stop offset="100%" stopColor="#00b894" stopOpacity={0.7}/>
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="3 3" vertical={false}/>
            <XAxis dataKey="d" tickLine={false} axisLine={false}/>
            <YAxis tickLine={false} axisLine={false} width={36}/>
            <Tooltip/>
            <Bar dataKey="L" fill="url(#bvol)" radius={[6,6,0,0]} maxBarSize={28}/>
          </BarChart>
        </ResponsiveContainer>
      </ChartCard>

      <ChartCard title="Energy Consumption" subtitle="kWh · ₹7/kWh estimated cost">
        <ResponsiveContainer width="100%" height={180}>
          <LineChart data={energyWeek} margin={{ top: 10, right: 12, bottom: 0, left: 8 }}>
            <CartesianGrid strokeDasharray="3 3" vertical={false}/>
            <XAxis dataKey="d" tickLine={false} axisLine={false}/>
            <YAxis tickLine={false} axisLine={false} width={28}/>
            <Tooltip/>
            <Line type="monotone" dataKey="kWh" stroke="#ffab40" strokeWidth={2.5} dot={{ r:4, fill:'#ffab40', stroke:'#0a0e27', strokeWidth:2 }} activeDot={{ r:6 }}/>
          </LineChart>
        </ResponsiveContainer>
      </ChartCard>

      <ChartCard title="Motor Run Statistics" subtitle="Runtime (min) per day">
        <ResponsiveContainer width="100%" height={200}>
          <ComposedChart data={motorWeek} margin={{ top: 10, right: 12, bottom: 0, left: 8 }}>
            <CartesianGrid strokeDasharray="3 3" vertical={false}/>
            <XAxis dataKey="d" tickLine={false} axisLine={false}/>
            <YAxis yAxisId="left"  tickLine={false} axisLine={false} width={32}/>
            <YAxis yAxisId="right" orientation="right" tickLine={false} axisLine={false} width={20}/>
            <Tooltip/>
            <Bar  yAxisId="left"  dataKey="runMin" name="Runtime (min)" fill="#00b894" radius={[6,6,0,0]} maxBarSize={28}/>
            <Line yAxisId="right" type="monotone" dataKey="cycles" name="Cycles" stroke="#00d4ff" strokeWidth={2.5} dot={{ r:4, fill:'#00d4ff', stroke:'#0a0e27', strokeWidth:2 }}/>
          </ComposedChart>
        </ResponsiveContainer>
      </ChartCard>

      <ChartCard title="Voltage & Current" subtitle="Mains monitoring · 24h">
        <ResponsiveContainer width="100%" height={200}>
          <LineChart data={vcDay} margin={{ top: 10, right: 12, bottom: 0, left: 8 }}>
            <CartesianGrid strokeDasharray="3 3" vertical={false}/>
            <XAxis dataKey="t" interval={5} tickLine={false} axisLine={false}/>
            <YAxis yAxisId="left"  domain={[180, 260]} tickLine={false} axisLine={false} width={32}/>
            <YAxis yAxisId="right" orientation="right" domain={[0, 10]} tickLine={false} axisLine={false} width={22}/>
            <Tooltip/>
            <A_.ReferenceArea yAxisId="left" y1={180} y2={195} fill="#ff5252" fillOpacity={0.05}/>
            <A_.ReferenceArea yAxisId="left" y1={245} y2={260} fill="#ff5252" fillOpacity={0.05}/>
            <Line yAxisId="left"  type="monotone" dataKey="V"       stroke="#ffab40" strokeWidth={2} dot={false} name="Voltage (V)"/>
            <Line yAxisId="right" type="monotone" dataKey="current" stroke="#00d4ff" strokeWidth={2} dot={false} name="Current (A)"/>
          </LineChart>
        </ResponsiveContainer>
      </ChartCard>
    </div>
  );
};

const SummaryCard = ({ label, value, unit, icon, tone, span }) => {
  const c = { cyan:'var(--cyan)', amber:'var(--amber)', teal:'var(--teal)', info:'var(--info)', green:'var(--green)' }[tone] || 'var(--cyan)';
  return (
    <div style={{ gridColumn: span ? '1 / -1' : undefined, background: 'rgba(255,255,255,0.04)', border: '1px solid var(--border)', borderRadius: 14, padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ width: 36, height: 36, borderRadius: 10, background: `${c}20`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Ic name={icon} size={18} color={c}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: 0.6 }}>{label}</div>
        <div className="num" style={{ fontSize: 18, fontWeight: 600, marginTop: 2 }}>
          {value} {unit && <span style={{ fontSize: 11, color: 'var(--text-2)', fontWeight: 500 }}>{unit}</span>}
        </div>
      </div>
    </div>
  );
};

const ChartCard = ({ title, subtitle, children }) => (
  <Card style={{ padding: 14, marginBottom: 12 }}>
    <div style={{ marginBottom: 6 }}>
      <div style={{ fontSize: 14, fontWeight: 600 }}>{title}</div>
      {subtitle && <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>{subtitle}</div>}
    </div>
    {children}
  </Card>
);

window.Analytics = Analytics;
