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

export function useClients() {
  const [clients, setClients] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let isMounted = true;
    supabase
      .from('orders')
      .select('id, name, phone, film_thickness, area_sqm, final_cost, status, created_at, address')
      .order('created_at', { ascending: false })
      .then(({ data, error: err }) => {
        if (!isMounted) return;
        if (err) { setError(err.message); setLoading(false); return; }
        const map = {};
        (data || []).forEach((order) => {
          const key = order.phone || 'unknown';
          if (!map[key]) {
            map[key] = { phone: key, name: order.name, orders: [], totalSpent: 0 };
          }
          map[key].orders.push(order);
          if (order.status === 'закрыт' && order.final_cost) {
            map[key].totalSpent += Number(order.final_cost);
          }
        });
        // Sort clients by most recent order (orders are already newest-first)
        const list = Object.values(map);
        setClients(list);
        setLoading(false);
      });
    return () => { isMounted = false; };
  }, []);

  return { clients, loading, error };
}
