import { useCallback } from 'react';
import { useDispatch } from 'react-redux';
import { masterService } from '../services/master.service';
import { 
  setMasterData, setLoading, setError,
  setAreasData, setAreasLoading
} from '../store/slices/masterSlice';
import { toast } from 'sonner';

export const useMasterData = () => {
  const dispatch = useDispatch();

  const fetchInitialData = useCallback(async () => {
    try {
      dispatch(setLoading(true));
      
      const [
        rolesRes, zonesRes, permsRes, regionsRes, usersRes, 
        statesRes, emailTemplatesRes, districtsRes, areasRes, slaRes,
        asmsRes, zmsRes, ddLeadsRes
      ] = await Promise.all([
        masterService.getRoles().catch(() => ({ success: false })),
        masterService.getZones().catch(() => ({ success: false })),
        masterService.getPermissions().catch(() => ({ success: false })),
        masterService.getRegions().catch(() => ({ success: false })),
        masterService.getUsers().catch(() => ({ success: false })),
        masterService.getStates().catch(() => ({ success: false })),
        masterService.getEmailTemplates().catch(() => ({ success: false })),
        masterService.getDistricts({ limit: 'all' }).catch(() => ({ success: false })),
        masterService.getAreas({ limit: 'all' }).catch(() => ({ success: false })),
        masterService.getSlaConfigs().catch(() => ({ success: false })),
        (masterService as any).getASMs().catch(() => ({ success: false })),
        (masterService as any).getZonalManagers().catch(() => ({ success: false })),
        (masterService as any).getDDLeads().catch(() => ({ success: false }))
      ]);

      const getBody = (res: any) => res.success ? res : (res.data ? res.data : res);
      
      const bodyRoles = getBody(rolesRes);
      const bodyZones = getBody(zonesRes);
      const bodyPerms = getBody(permsRes);
      const bodyRegions = getBody(regionsRes);
      const bodyUsers = getBody(usersRes);
      const bodyStates = getBody(statesRes);
      const bodyEmail = getBody(emailTemplatesRes);
      const bodyDistricts = getBody(districtsRes);
      const bodyAreas = getBody(areasRes);
      const bodySla = getBody(slaRes);
      const bodyAsms = getBody(asmsRes);
      const bodyZms = getBody(zmsRes);
      const bodyDdLeads = getBody(ddLeadsRes);

      const users = (bodyUsers?.users || bodyUsers?.data || []).map((u: any) => {
        const territory = Array.isArray(u.territoryProfile) ? u.territoryProfile : [];
        const territoryZones = territory
          .filter((t: any) => String(t.locationType || '').toLowerCase() === 'zone')
          .map((t: any) => t.locationName || t.zone)
          .filter(Boolean);
        const territoryRegions = territory
          .filter((t: any) => String(t.locationType || '').toLowerCase() === 'region')
          .map((t: any) => t.locationName || t.region)
          .filter(Boolean);

        const zones = Array.from(new Set([...(u.allZones || []), ...territoryZones]));
        const regions = Array.from(new Set([...(u.allRegions || []), ...territoryRegions]));

        return {
          ...u,
          name: u.fullName || u.name,
          role: u.role?.roleName || (Array.isArray(u.allRoles) && u.allRoles.length > 0 ? u.allRoles[0] : 'System User'),
          zone: zones.length > 0 ? zones.join(', ') : 'Global',
          region: regions.length > 0 ? regions.join(', ') : 'Unassigned',
          status: u.isActive !== false ? 'Active' : 'Inactive'
        };
      });

      const roles = (bodyRoles?.roles || bodyRoles?.data || []).map((r: any) => ({
        id: r.id, name: r.roleName, permissions: r.permissions?.map((p: any) => p.permissionCode) || [], userCount: r.userCount || 0
      }));

      const zones = (bodyZones?.zones || bodyZones?.data || []).map((z: any) => {
        const zoneName = (z.name || z.zoneName || '').toUpperCase();
        // const zoneUsers = users.filter((u: any) => u.allZones?.includes(zoneName));
        
        return {
          id: z.id, name: zoneName, description: z.description || '',
          code: z.name ? z.name.substring(0, 3).toUpperCase() : 'ZON',
          regionCount: z.regionCount || 0,
          asmCount: z.asmCount || 0,
          regionalOfficerCount: z.regionalOfficerCount || 0,
          zmCount: z.zmCount || 0,
          states: z.states || [],
          zonalBusinessHead: { 
            name: z.zonalBusinessHead?.name || z.zonalBusinessHead?.fullName || 'Not Assigned', 
            email: z.zonalBusinessHead?.email || '', 
            phone: z.zonalBusinessHead?.mobileNumber || z.zonalBusinessHead?.phone || '' 
          },
          zonalManagers: (z.zonalManagers || []).map((m: any) => ({
            id: m.id,
            name: m.name || m.fullName || 'Unknown', 
            email: m.email || '', 
            phone: m.phone || m.mobileNumber || '',
            regions: m.regions || []
          }))
        };
      });

      const regionalOffices = (bodyRegions?.regions || bodyRegions?.data || []).map((r: any) => ({
        id: r.id,
        code: r.code || (r.name ? r.name.substring(0, 3).toUpperCase() : 'REG'),
        name: r.name || r.regionName,
        zoneId: r.zoneId,
        zoneName: r.zoneName || 'Unknown',
        states: r.states || [],
        cities: r.cities || [],
        districts: (r.districts || []).map((d: any) => ({ id: d.id, name: d.name, stateId: d.stateId })),
        asmCount: r.asmCount || 0,
        regionalOfficerCount: r.regionalOfficerCount || 0,
        regionalManager: r.regionalManager ? { 
          id: r.regionalManager.id, 
          name: r.regionalManager.fullName || r.regionalManager.name, 
          email: r.regionalManager.email, 
          phone: r.regionalManager.mobileNumber || r.regionalManager.phone
        } : undefined,
        status: r.isActive !== false ? 'Active' : 'Inactive'
      }));

      const asms = Array.isArray(bodyAsms?.data) ? bodyAsms.data : (Array.isArray(bodyAsms) ? bodyAsms : []);
      const zonalManagers = Array.isArray(bodyZms?.data) ? bodyZms.data : (Array.isArray(bodyZms) ? bodyZms : []);

      const zonalManagerMappings = zonalManagers.length > 0 ? zonalManagers : users.filter((u: any) => 
        u.allRoles?.some((r: string) => (r === 'ZM' || r === 'DD-ZM' || r.includes('ZONAL MANAGER')) && !r.includes('HEAD'))
      ).map((u: any) => {
        const zmT = (u.territoryProfile || []).find((t: any) => (t.roleCode === 'ZM' || t.roleCode === 'DD-ZM')) || {};
        const regions = (u.territoryProfile || [])
          .filter((t: any) => (t.roleCode === 'ZM' || t.roleCode === 'DD-ZM') && t.locationType === 'region')
          .map((t: any) => t.locationName);
        const regionIds = (u.territoryProfile || [])
          .filter((t: any) => (t.roleCode === 'ZM' || t.roleCode === 'DD-ZM') && t.locationType === 'region')
          .map((t: any) => t.locationId);

        return {
          id: u.id, 
          name: u.fullName, 
          zmCode: u.employeeId || 'N/A', 
          email: u.email, 
          phone: u.mobileNumber,
          zoneId: zmT.zoneId,
          zoneName: zmT.zone || u.zone || 'Not Assigned',
          regionNames: regions,
          assignedRegionIds: regionIds,
          status: u.status
        };
      });

      const allStates = (bodyStates?.states || bodyStates?.data || []).map((s: any) => ({
        ...s, stateName: s.name
      }));

      const allDistricts = (bodyDistricts?.districts || bodyDistricts?.data || []).map((d: any) => ({
        ...d, 
        districtName: d.name,
        stateId: d.stateId,
        asmId: d.asmId,
        ddAmId: d.ddAmId,
        zmId: d.zmId
      }));
 
      const allAreas = (bodyAreas.areas || bodyAreas.data || []).map((a: any) => ({
        ...a, 
        areaName: a.name,
        districtId: a.districtId // Now populated by backend's deep resolution
      }));

      const slaConfigs = (bodySla.data || []).map((s: any) => ({
        id: s.id, stage: s.stageCode || 'Unknown', days: s.tatValue || 0, enabled: s.isActive !== false,
        reminders: s.reminderConfig?.reminders || [], escalations: s.escalationConfig?.escalations || []
      }));

      const ddLeads = Array.isArray(bodyDdLeads?.data) ? bodyDdLeads.data : (Array.isArray(bodyDdLeads) ? bodyDdLeads : []);

      dispatch(setMasterData({
        zones, regionalOffices, asms, zonalManagerMappings, zonalManagers,
        roles, allStates, allDistricts, allAreas,
        availablePermissions: bodyPerms?.permissions || bodyPerms?.data || [],
        emailTemplates: bodyEmail?.data || [],
        slaConfigs,
        users,
        ddLeads,
        loading: false
      }));

    } catch (error) {
      console.error('[useMasterData] Error fetching data:', error);
      dispatch(setError('Could not load configuration data'));
      toast.error('Could not load configuration data');
    } finally {
      dispatch(setLoading(false));
    }
  }, [dispatch]);

  const fetchAreas = useCallback(async (params?: { search?: string; page?: number; limit?: number; stateId?: string; isOpportunity?: string }) => {
    try {
      dispatch(setAreasLoading(true));
      const res = await masterService.getAreas(params) as any;
      if (res.success) {
        dispatch(setAreasData({ data: res.data, pagination: res.pagination }));
      }
    } catch (error) {
      console.error('[useMasterData] Error fetching areas:', error);
      toast.error('Could not load locations');
    } finally {
      dispatch(setAreasLoading(false));
    }
  }, [dispatch]);

  return { fetchInitialData, fetchAreas };
};
