import { useState, useEffect, useCallback } from 'react';
import { supabase } from '../../lib/supabase';

const STATUSES = ['новая', 'замер', 'согласование', 'монтаж', 'закрыт'];

export function useAnalytics(dateFrom, dateTo) {
  const [analytics, setAnalytics] = useState({
    totalOrders: 0, closedOrders: 0, conversionRate: 0,
    totalRevenue: 0, avgDeal: 0,
    funnelData: STATUSES.map((s) => ({ status: s, count: 0 })),
    revenueByMonth: [], byObjectType: [], avgTimeData: [],
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchAnalytics = useCallback(async () => {
    setError(null);

    const { data: orders, error: ordersError } = await supabase
      .from('orders')
      .select('*')
      .gte('created_at', dateFrom)
      .lte('created_at', dateTo);

    if (ordersError) {
      setError(ordersError.message);
      setLoading(false);
      return;
    }

    const safeOrders = orders || [];
    const orderIds = safeOrders.map((o) => o.id);

    const { data: rawEvents } = orderIds.length > 0
      ? await supabase
          .from('order_events')
          .select('*')
          .eq('event_type', 'status_change')
          .in('order_id', orderIds)
          .order('created_at', { ascending: true })
      : { data: [] };

    const events = rawEvents || [];
    const closed = safeOrders.filter((o) => o.status === 'закрыт');
    const totalRevenue = closed.reduce((s, o) => s + (Number(o.final_cost) || 0), 0);
    const avgDeal = closed.length > 0 ? Math.round(totalRevenue / closed.length) : 0;

    const funnelData = STATUSES.map((status) => ({
      status,
      count: safeOrders.filter((o) => o.status === status).length,
    }));

    const revEntries = [];
    closed.forEach((o) => {
      const date = new Date(o.closed_at || o.created_at);
      const key = date.toLocaleString('ru-RU', { month: 'short', year: '2-digit' });
      const monthStart = new Date(date.getFullYear(), date.getMonth(), 1).getTime();
      const existing = revEntries.find((e) => e.month === key);
      if (existing) {
        existing.revenue += Number(o.final_cost) || 0;
      } else {
        revEntries.push({ month: key, revenue: Number(o.final_cost) || 0, _sort: monthStart });
      }
    });
    revEntries.sort((a, b) => a._sort - b._sort);
    const revenueByMonth = revEntries.map(({ month, revenue }) => ({ month, revenue }));

    const typeMap = {};
    safeOrders.forEach((o) => {
      const type = o.object_type || 'other';
      typeMap[type] = (typeMap[type] || 0) + 1;
    });
    const byObjectType = Object.entries(typeMap).map(([type, count]) => ({ type, count }));

    const timeMap = Object.fromEntries(STATUSES.slice(0, -1).map((s) => [s, []]));
    safeOrders.forEach((order) => {
      const oEvents = events.filter((e) => e.order_id === order.id);
      let prevTime = new Date(order.created_at);
      let prevStatus = 'новая';
      oEvents.forEach((e) => {
        const match = e.description?.match(/→ (.+)$/);
        if (match) {
          const days = (new Date(e.created_at) - prevTime) / 86400000;
          if (timeMap[prevStatus]) timeMap[prevStatus].push(days);
          prevStatus = match[1].trim();
          prevTime = new Date(e.created_at);
        }
      });
    });
    const avgTimeData = STATUSES.slice(0, -1).map((status) => ({
      status,
      avgDays: timeMap[status].length > 0
        ? Math.round((timeMap[status].reduce((a, b) => a + b, 0) / timeMap[status].length) * 10) / 10
        : 0,
    }));

    setAnalytics({
      totalOrders: safeOrders.length,
      closedOrders: closed.length,
      conversionRate: safeOrders.length > 0 ? Math.round((closed.length / safeOrders.length) * 100) : 0,
      totalRevenue, avgDeal, funnelData, revenueByMonth, byObjectType, avgTimeData,
    });
    setLoading(false);
  }, [dateFrom, dateTo]);

  useEffect(() => {
    setLoading(true);
    fetchAnalytics();
  }, [fetchAnalytics]);

  return { ...analytics, loading, error };
}
