import { useState, useEffect } from 'react';
import apiService from '../services/apiService';

export interface DocTypeField {
  fieldname: string;
  fieldtype: string;
  label: string;
  allow_on_submit: number; // 0 or 1
  reqd: number; // 0 or 1 for required
  read_only: number; // 0 or 1
}

export const useDocTypeMeta = (doctype: string) => {
  const [fields, setFields] = useState<DocTypeField[]>([]);
  const [allowOnSubmitFields, setAllowOnSubmitFields] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchDocTypeMeta = async () => {
      if (!doctype) {
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        const response = await apiService.apiCall<any>(
          `/api/resource/DocType/${doctype}`
        );
        
        // Handle different response structures from Frappe API
        // Response can be: { data: {...} } or directly {...}
        const docTypeData = response.data || response;
        const fieldsList: DocTypeField[] = docTypeData.fields || [];
        
        // Extract fields that allow editing on submit
        const allowOnSubmitSet = new Set<string>();
        fieldsList.forEach((field: DocTypeField) => {
          // Check both number (1) and boolean (true) formats
          // if (field.allow_on_submit === 1 || field.allow_on_submit === true) {
          if (field.allow_on_submit === 1){
            allowOnSubmitSet.add(field.fieldname);
          }
        });
        
        // Debug logging (development only)
        if (import.meta.env.DEV) {
          console.log(`[DocTypeMeta] Loaded ${fieldsList.length} fields for ${doctype}`);
          console.log(`[DocTypeMeta] Fields with allow_on_submit:`, Array.from(allowOnSubmitSet));
        }
        
        setFields(fieldsList);
        setAllowOnSubmitFields(allowOnSubmitSet);
        setError(null);
      } catch (err) {
        console.error(`[DocTypeMeta] Error fetching DocType meta for ${doctype}:`, err);
        setError(err instanceof Error ? err.message : 'Unknown error');
        // Don't block the UI if metadata fetch fails - allow all fields to be editable
        // This is a graceful degradation
        setFields([]);
        setAllowOnSubmitFields(new Set());
      } finally {
        setLoading(false);
      }
    };

    fetchDocTypeMeta();
  }, [doctype]);

  const isAllowedOnSubmit = (fieldname: string): boolean => {
    return allowOnSubmitFields.has(fieldname);
  };

  return { fields, allowOnSubmitFields, isAllowedOnSubmit, loading, error };
};

