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

export function useArchive() {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);

  const fetch = useCallback(async () => {
    let isMounted = true;
    setLoading(true);
    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - 30);

    const { data } = await supabase
      .from('orders')
      .select('id, name, phone, status, final_cost, created_at, closed_at, assigned_to, film_thickness, area_sqm, address')
      .eq('status', 'закрыт')
      .lt('created_at', cutoff.toISOString())
      .order('closed_at', { ascending: false, nullsFirst: false });

    if (isMounted) { setOrders(data ?? []); setLoading(false); }
    return () => { isMounted = false; };
  }, []);

  useEffect(() => { fetch(); }, [fetch]);

  const restoreOrder = async (orderId) => {
    const { error } = await supabase
      .from('orders')
      .update({ status: 'новая', closed_at: null })
      .eq('id', orderId);
    if (!error) await fetch();
    return { error };
  };

  return { orders, loading, restoreOrder, refetch: fetch };
}
