import React, { useEffect, useMemo, useState } from "react";
import { View, StyleSheet, ScrollView, TouchableOpacity, Image } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { FLEX } from "@/theme/mixins";
import { COLOR_SCALES } from "@/theme/colors";
import { title, paragraph } from "@/theme/typography";
import { Text, Loading, Empty, ProfileHeader, DrawerMenu } from "@/components/common";
import { getAnalysisNotification } from "@/services/user";
import { Svg, G, Line, Path, Rect, Text as SvgText } from "react-native-svg";

export default function AnalyticsScreen() {
  
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const insets = useSafeAreaInsets();

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        const res = await getAnalysisNotification();
        if (res?.success && res?.data) {
          setData(res.data);
        } else {
          setData(null);
        }
      } catch (e) {
        setError(e);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  // Always call hooks in the same order across renders
  const mealsArr = useMemo(() => {
    return Object.entries(data?.meals ?? {}).map(([k, v]) => ({ key: k, count: v }));
  }, [data]);

  const placesArr = useMemo(() => {
    return Object.entries(data?.places ?? {}).map(([k, v]) => ({ key: k, count: v }));
  }, [data]);

  const foodsArr = data?.foods ?? [];
  const paretoArr = data?.foodsPareto ?? [];
  const totalDays = (data?.daysAnswered ?? 0);
  const daysYes = (data?.daysWasteYes ?? 0);
  const daysNo = (data?.daysWasteNo ?? 0);

  if (loading) {
    return (
      <SafeAreaView style={styles.container}>
        <Loading size="small" message="Analiz yükleniyor..." />
      </SafeAreaView>
    );
  }

  if (error || !data) {
    return (
      <SafeAreaView style={styles.container}>
        <Empty title="Analiz Bulunamadı" description="Son 1 ay için veri yok." fullscreen={false} />
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      {/* Left Drawer Menu Button */}
      <TouchableOpacity style={styles.menuButton} onPress={() => setDrawerVisible(true)}>
        <Image
          source={require("@/assets/images/icons/menu.png")}
          style={styles.menuIcon}
        />
      </TouchableOpacity>
      <ProfileHeader 
        pageTitle="Aylık Analizler" 
        showBackButton={true} 
        showNotification={false} 
        showUserInfo={false} 
      />
      <ScrollView style={styles.scroll} contentContainerStyle={styles.content}>
        <View style={styles.sectionHeaderBand}>
          <Text style={styles.sectionTitle}>Aylık Analizler</Text>
        </View>

        {/* Gıda israf edilen gün sayısı (pie-like proportions as stacked bar) */}
        <View style={styles.card}>
          <View style={styles.cardBand} />
          <Text style={styles.cardTitle}>Gıda israf edilen gün sayısı</Text>
          <Svg width={320} height={160}>
            <Rect x={10} y={60} width={300} height={24} rx={12} fill={COLOR_SCALES.gray[20]} />
            {(() => {
              const total = Math.max(totalDays, daysYes + daysNo);
              const yesW = total > 0 ? (300 * daysYes) / total : 0;
              const noW = total > 0 ? (300 * daysNo) / total : 0;
              return (
                <G>
                  <Rect x={10} y={60} width={yesW} height={24} rx={12} fill={COLOR_SCALES.primary[60]} />
                  <Rect x={10 + yesW} y={60} width={noW} height={24} rx={12} fill={COLOR_SCALES.secondary?.[60] ?? "#928464"} />
                  <SvgText x={20} y={54} fontSize={12} fill={COLOR_SCALES.colorGray[90]}>Evet: {daysYes}</SvgText>
                  <SvgText x={120} y={54} fontSize={12} fill={COLOR_SCALES.colorGray[90]}>Hayır: {daysNo}</SvgText>
                </G>
              );
            })()}
          </Svg>
        </View>

        {/* Öğün sıralaması (bar + pareto line style) */}
        <View style={styles.card}>
          <View style={styles.cardBand} />
          <Text style={styles.cardTitle}>Gıda İsraf Edilen Öğün Sıralaması</Text>
          <CategoryPareto data={mealsArr} />
        </View>

        {/* İsraf edilen gıdaların sıralaması (Pareto) */}
        <View style={styles.card}>
          <View style={styles.cardBand} />
          <Text style={styles.cardTitle}>İsraf Edilen Gıdaların Sıralaması</Text>
          <ParetoChart items={foodsArr} />
        </View>

        {/* İsraf ettiğiniz alan */}
        <View style={styles.card}>
          <View style={styles.cardBand} />
          <Text style={styles.cardTitle}>Gıda israf Ettiğiniz Alan</Text>
          <CategoryPareto data={placesArr} />
        </View>
      </ScrollView>

      {/* Drawer */}
      <DrawerMenu
        visible={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        userData={null}
      />
    </SafeAreaView>
  );
}

function ParetoChart({ items }) {
  const sorted = [...(items ?? [])].sort((a, b) => (b?.count ?? 0) - (a?.count ?? 0));
  const total = sorted.reduce((s, it) => s + (it?.count ?? 0), 0) || 1;
  const width = 320;
  const height = 200;
  const chartW = 280;
  const chartH = 120;
  const left = 30;
  const top = 40;

  // line path for cumulative percentage
  let acc = 0;
  const points = sorted.map((it, idx) => {
    acc += (it?.count ?? 0);
    const pct = acc / total;
    const x = left + (idx + 0.5) * (chartW / Math.max(sorted.length, 1));
    const y = top + chartH * (1 - pct);
    return { x, y };
  });
  const pathD = points.reduce((d, p, i) => (i === 0 ? `M ${p.x} ${p.y}` : `${d} L ${p.x} ${p.y}`), "");

  return (
    <Svg width={width} height={height}>
      {/* axes */}
      <Line x1={left} y1={top} x2={left} y2={top + chartH} stroke={COLOR_SCALES.gray[50]} strokeWidth={1} />
      <Line x1={left} y1={top + chartH} x2={left + chartW} y2={top + chartH} stroke={COLOR_SCALES.gray[50]} strokeWidth={1} />

      {/* bars */}
      {sorted.map((it, idx) => {
        const barW = chartW / Math.max(sorted.length, 1) - 8;
        const barH = chartH * ((it?.count ?? 0) / total);
        const x = left + idx * (chartW / Math.max(sorted.length, 1)) + 4;
        const y = top + chartH - barH;
        return (
          <G key={`${it?.typeId ?? idx}`}> 
            <Rect x={x} y={y} width={barW} height={barH} fill={COLOR_SCALES.primary[70]} />
            <SvgText x={x + barW / 2} y={top + chartH + 14} fontSize={10} fill={COLOR_SCALES.colorGray[90]} textAnchor="middle">
              {(it?.name ?? "-")}
            </SvgText>
            <SvgText x={x + barW / 2} y={y - 6} fontSize={10} fill={COLOR_SCALES.colorGray[90]} textAnchor="middle">
              {(it?.count ?? 0)}
            </SvgText>
          </G>
        );
      })}

      {/* pareto line */}
      <Path d={pathD} stroke={COLOR_SCALES.secondary?.[60] ?? "#928464"} strokeWidth={2} fill="none" />
    </Svg>
  );
}

function CategoryPareto({ data }) {
  const items = [...(data ?? [])].sort((a, b) => (b?.count ?? 0) - (a?.count ?? 0));
  const total = items.reduce((s, it) => s + (it?.count ?? 0), 0) || 1;
  const width = 320;
  const height = 200;
  const chartW = 280;
  const chartH = 120;
  const left = 30;
  const top = 40;

  let acc = 0;
  const points = items.map((it, idx) => {
    acc += (it?.count ?? 0);
    const pct = acc / total;
    const x = left + (idx + 0.5) * (chartW / Math.max(items.length, 1));
    const y = top + chartH * (1 - pct);
    return { x, y };
  });
  const pathD = points.reduce((d, p, i) => (i === 0 ? `M ${p.x} ${p.y}` : `${d} L ${p.x} ${p.y}`), "");

  return (
    <Svg width={width} height={height}>
      <Line x1={left} y1={top} x2={left} y2={top + chartH} stroke={COLOR_SCALES.gray[50]} strokeWidth={1} />
      <Line x1={left} y1={top + chartH} x2={left + chartW} y2={top + chartH} stroke={COLOR_SCALES.gray[50]} strokeWidth={1} />
      {items.map((it, idx) => {
        const barW = chartW / Math.max(items.length, 1) - 8;
        const barH = chartH * ((it?.count ?? 0) / total);
        const x = left + idx * (chartW / Math.max(items.length, 1)) + 4;
        const y = top + chartH - barH;
        return (
          <G key={`${it?.key ?? idx}`}>
            <Rect x={x} y={y} width={barW} height={barH} fill={COLOR_SCALES.primary[70]} />
            <SvgText x={x + barW / 2} y={top + chartH + 14} fontSize={10} fill={COLOR_SCALES.colorGray[90]} textAnchor="middle">
              {(it?.key ?? "-")}
            </SvgText>
            <SvgText x={x + barW / 2} y={y - 6} fontSize={10} fill={COLOR_SCALES.colorGray[90]} textAnchor="middle">
              {(it?.count ?? 0)}
            </SvgText>
          </G>
        );
      })}
      <Path d={pathD} stroke={COLOR_SCALES.secondary?.[60] ?? "#928464"} strokeWidth={2} fill="none" />
    </Svg>
  );
}

const styles = StyleSheet.create({
  container: {
    ...FLEX.fill,
    backgroundColor: COLOR_SCALES.white?.white ?? "#fff",
  },
  menuButton: {
    position: "absolute",
    top: 44,
    left: 16,
    zIndex: 20,
    width: 40,
    height: 40,
    alignItems: "center",
    justifyContent: "center",
  },
  menuIcon: {
    width: 28,
    height: 28,
  },
  scroll: {
    flex: 1,
  },
  content: {
    padding: 16,
  },
  sectionTitle: {
    ...title["L/Bold"],
    color: COLOR_SCALES.colorGray[90],
    marginBottom: 12,
  },
  sectionHeaderBand: {
    backgroundColor: "#FFF200",
    paddingVertical: 6,
    paddingHorizontal: 8,
    marginBottom: 8,
  },
  card: {
    backgroundColor: "#FFFFFF",
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
  },
  cardBand: {
    height: 12,
    backgroundColor: "#FFF200",
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    marginTop: -16,
    marginHorizontal: -16,
    marginBottom: 8,
  },
  cardTitle: {
    ...paragraph["M/SemiBold"],
    color: COLOR_SCALES.primary[70],
    marginBottom: 8,
  },
});


